<?php

namespace App\Models;

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

class AdmissionSeat extends Model
{
    use HasFactory;

    protected $table = 'admission_seats';
    
    protected $fillable = [
        'academic_year',
        'class_id',
        'total_seats',
        'available_seats',
        'boy_seats',
        'girl_seats',
        'minority_quota',
        'disabled_quota',
        'merit_quota',
        'application_start_date',
        'application_end_date',
        'result_date',
        'status'
    ];

    protected $casts = [
        'academic_year' => 'integer',
        'total_seats' => 'integer',
        'available_seats' => 'integer',
        'boy_seats' => 'integer',
        'girl_seats' => 'integer',
        'minority_quota' => 'integer',
        'disabled_quota' => 'integer',
        'merit_quota' => 'integer',
        'application_start_date' => 'date',
        'application_end_date' => 'date',
        'result_date' => 'date',
        'status' => 'boolean'
    ];

    public function class()
    {
        return $this->belongsTo(Classes::class, 'class_id');
    }

    // Check if admissions are open
    public function isOpen()
    {
        $now = now();
        return $this->status && 
               $now >= $this->application_start_date && 
               $now <= $this->application_end_date;
    }

    // Check seats available
    public function hasSeats($gender = null)
    {
        if ($gender == 'male') {
            return $this->boy_seats > 0;
        } elseif ($gender == 'female') {
            return $this->girl_seats > 0;
        }
        return $this->available_seats > 0;
    }

    // Decrease available seats
    public function decreaseSeats($gender = null, $isMinority = false, $isDisabled = false)
    {
        if ($gender == 'male' && $this->boy_seats > 0) {
            $this->boy_seats--;
        } elseif ($gender == 'female' && $this->girl_seats > 0) {
            $this->girl_seats--;
        }

        if ($isMinority && $this->minority_quota > 0) {
            $this->minority_quota--;
        }

        if ($isDisabled && $this->disabled_quota > 0) {
            $this->disabled_quota--;
        }

        $this->available_seats--;
        $this->save();
    }
}