<?php
// app/Models/SeasonalCalendar.php

namespace App\Models;

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

class SeasonalCalendar extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'start_date',
        'end_date',
        'price_increase_percentage',
        'session_type',
        'color_code',
        'recurring_yearly',
        'is_active',
        'priority'
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'price_increase_percentage' => 'decimal:2',
        'recurring_yearly' => 'boolean',
        'is_active' => 'boolean',
        'priority' => 'integer'
    ];

    // Scope for active sessions
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // Scope for regular sessions
    public function scopeRegular($query)
    {
        return $query->where('session_type', 'regular');
    }

    // Scope for special sessions
    public function scopeSpecial($query)
    {
        return $query->where('session_type', 'special');
    }

    // Check if session is applicable for a date
    public function isApplicableForDate(Carbon $date)
    {
        if (!$this->is_active) {
            return false;
        }

        if ($this->recurring_yearly) {
            // For recurring sessions, compare month and day only
            $startMonthDay = $this->start_date->format('m-d');
            $endMonthDay = $this->end_date->format('m-d');
            $checkMonthDay = $date->format('m-d');

            // Handle year boundary (e.g., Dec to Jan)
            if ($startMonthDay <= $endMonthDay) {
                return $checkMonthDay >= $startMonthDay && $checkMonthDay <= $endMonthDay;
            } else {
                // Session crosses year boundary
                return $checkMonthDay >= $startMonthDay || $checkMonthDay <= $endMonthDay;
            }
        } else {
            // For non-recurring sessions, exact date match
            return $date->between($this->start_date, $this->end_date);
        }
    }

    // Get display name with percentage
    public function getDisplayNameAttribute()
    {
        return "{$this->name} (+{$this->price_increase_percentage}%)";
    }

    // NEW: Convert to array format for API responses
    public function toArrayFormat()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'percentage' => (float) $this->price_increase_percentage,
            'type' => $this->session_type,
            'description' => $this->description,
            'color_code' => $this->color_code,
            'start_date' => $this->start_date->format('Y-m-d'),
            'end_date' => $this->end_date->format('Y-m-d'),
            'recurring_yearly' => $this->recurring_yearly
        ];
    }
}