<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Guru extends Model
{
    // Memastikan nama tabel sesuai dengan database
    protected $table = 'gurus';

    
    protected $fillable = ['user_id', 'id_guru', 'nama_guru'];

    
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id_guru)) {
                $nextNumber = ((int) static::max('id')) + 1;
                $candidate = 'GRU' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);

                while (static::where('id_guru', $candidate)->exists()) {
                    $nextNumber++;
                    $candidate = 'GRU' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);
                }

                $model->id_guru = $candidate;
            }
        });
    }
}