<?php

namespace App\Models;

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

class Routine extends Model
{
    use HasFactory;

    protected $table = 'routines';
    
    protected $fillable = [
        'class_id',
        'section',
        'day_of_week',
        'period',
        'start_time',
        'end_time',
        'subject',
        'teacher_id',
        'room_number',
        'is_break',
        'break_name',
        'effective_from',
        'effective_to',
        'status'
    ];

    protected $casts = [
        'start_time' => 'datetime:H:i',
        'end_time' => 'datetime:H:i',
        'effective_from' => 'date',
        'effective_to' => 'date',
        'is_break' => 'boolean',
        'status' => 'boolean'
    ];

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

    public function teacher()
    {
        return $this->belongsTo(Teacher::class);
    }

    // Days of week
    public static function getDays()
    {
        return [
            'saturday' => 'শনিবার',
            'sunday' => 'রবিবার',
            'monday' => 'সোমবার',
            'tuesday' => 'মঙ্গলবার',
            'wednesday' => 'বুধবার',
            'thursday' => 'বৃহস্পতিবার',
            'friday' => 'শুক্রবার'
        ];
    }

    // Periods
    public static function getPeriods()
    {
        return [
            1 => '১ম পিরিয়ড',
            2 => '২য় পিরিয়ড',
            3 => '৩য় পিরিয়ড',
            4 => '৪র্থ পিরিয়ড',
            5 => '৫ম পিরিয়ড',
            6 => '৬ষ্ঠ পিরিয়ড',
            7 => '৭ম পিরিয়ড',
            8 => '৮ম পিরিয়ড'
        ];
    }

    // Get routine by class and day
    public static function getRoutine($classId, $section, $day)
    {
        return self::where('class_id', $classId)
                   ->where('section', $section)
                   ->where('day_of_week', $day)
                   ->orderBy('period')
                   ->get();
    }

    // Check teacher availability
    public static function checkTeacherAvailability($teacherId, $day, $startTime, $endTime, $excludeId = null)
    {
        $query = self::where('teacher_id', $teacherId)
                     ->where('day_of_week', $day)
                     ->where(function($q) use ($startTime, $endTime) {
                         $q->whereBetween('start_time', [$startTime, $endTime])
                           ->orWhereBetween('end_time', [$startTime, $endTime])
                           ->orWhere(function($q2) use ($startTime, $endTime) {
                               $q2->where('start_time', '<=', $startTime)
                                  ->where('end_time', '>=', $endTime);
                           });
                     });
        
        if ($excludeId) {
            $query->where('id', '!=', $excludeId);
        }
        
        return !$query->exists();
    }
}