<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\Archivable;

class Teacher extends Model
{
    use HasFactory, SoftDeletes, Archivable;

    /**
     * The primary key type.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Primary key is non-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'franchisee_id',
        'parent_teachers_id',
        'name',
        'qualification',
        'experience',
        'profile_image',
        'is_global',
        'status',
        'order_no',
    ];

    /**
     * The attribute type casting.
     */
    protected $casts = [
        'experience' => 'integer',
        'order_no' => 'integer',
        'status' => 'string',
        'franchisee_id' => 'string',
        'parent_teachers_id' => 'string',
        'language' => 'string',
        'is_global' => 'boolean',
    ];

    /**
     * Boot function to auto-generate UUID.
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = (string) Str::uuid();
            }

            // Set default status if not provided
            if (empty($model->status)) {
                $model->status = 'Active';
            }

            // Set default order_no if not provided
            if (empty($model->order_no)) {
                $query = self::query();

                if ($model->is_global) {
                    // For global/super admin testimonials
                    $query->where('is_global', true);
                } else {
                    // For franchise-specific testimonials
                    $query->where('franchisee_id', $model->franchisee_id);
                }

                $maxOrder = $query->max('order_no') ?? 0;
                $model->order_no = $maxOrder + 1;
            }
        });
    }

    /**
     * Parent teacher (if this is a franchise-specific copy)
     */
    public function parentTeacher()
    {
        return $this->belongsTo(Teacher::class, 'parent_teachers_id');
    }

    /**
     * Franchise-specific copies of this teacher
     */
    public function franchiseCopies()
    {
        return $this->hasMany(Teacher::class, 'parent_teachers_id');
    }

    /**
     * Franchise relationship
     */
    public function franchisee()
    {
        return $this->belongsTo(Franchisee::class, 'franchisee_id');
    }
}
