<?php

namespace App\Models;

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

class Teacher extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'designation',
        'department',
        'qualification',
        'specialization',
        'email',
        'phone',
        'bio',
        'photo',
        'display_order',
        'is_active',
        'is_principal',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'is_principal' => 'boolean',
            'display_order' => 'integer',
        ];
    }

    /**
     * Scope a query to only include active teachers.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope a query to order teachers (principal first, then by display_order).
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('is_principal', 'desc')
                    ->orderBy('display_order', 'asc')
                    ->orderBy('name', 'asc');
    }

    /**
     * Scope a query to search teachers.
     */
    public function scopeSearch($query, $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('designation', 'like', "%{$search}%")
              ->orWhere('department', 'like', "%{$search}%")
              ->orWhere('qualification', 'like', "%{$search}%")
              ->orWhere('specialization', 'like', "%{$search}%");
        });
    }

    /**
     * Get the photo URL or default placeholder.
     */
    public function getPhotoUrlAttribute()
    {
        if ($this->photo) {
            return asset('storage/' . $this->photo);
        }
        return asset('assets/img/default-teacher.png');
    }
}

