<?php
// app/Models/ParentConnection.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ParentConnection extends Model
{
    use HasFactory;

    protected $fillable = [
        'parent_id',
        'student_id',
        'connection_code',
        'status',
    ];

    protected $casts = [
        'status' => 'string',
    ];

    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id');
    }

    public function student()
    {
        return $this->belongsTo(User::class, 'student_id');
    }

    // Generate kode koneksi unik
    public static function generateCode()
    {
        do {
            $code = strtoupper(substr(md5(uniqid() . microtime()), 0, 8));
        } while (self::where('connection_code', $code)->exists());

        return $code;
    }

    // Scope untuk koneksi pending
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    // Scope untuk koneksi connected
    public function scopeConnected($query)
    {
        return $query->where('status', 'connected');
    }
}