<?php

namespace Modules\Guardians\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Guardian extends Model
{
    use HasFactory;

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory()
    {
        return \Database\Factories\GuardianFactory::new();
    }

    protected $fillable = [
        'user_id',
        'first_name',
        'last_name',
        'phone',
        'address',
        'occupation',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

    /**
     * Get the user account for this guardian
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class);
    }

    /**
     * Get the students this guardian is responsible for
     */
    public function students(): BelongsToMany
    {
        return $this->belongsToMany(
            \Modules\Students\Models\Student::class,
            'student_guardians',
            'guardian_id',
            'student_id'
        )->withPivot(['relationship'])
         ->withTimestamps();
    }

    /**
     * Get the full name of the guardian
     */
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

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

    /**
     * Get all results for students under this guardian's care
     */
    public function getStudentResults($academicYearId = null, $examTypeId = null)
    {
        $students = $this->students()->with(['results' => function ($query) use ($academicYearId, $examTypeId) {
            if ($academicYearId) {
                $query->where('academic_year_id', $academicYearId);
            }
            if ($examTypeId) {
                $query->where('exam_type_id', $examTypeId);
            }
            $query->with(['subject', 'examType', 'academicYear']);
        }])->get();

        return $students;
    }
}
