<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class WoffPattern extends Model
{
    use SoftDeletes;

    protected $table = 'woff_pattern';
    protected $primaryKey = 'WOP_id';

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const DELETED_AT = 'deleted_at';

    protected $fillable = [
        'WOP_code',
        'WOP_name',
        'description',
        'pattern_data',      // ✅ NEW FIELD
        'Is_Active'
    ];

    protected $casts = [
        'WOP_id' => 'integer',
        'pattern_data' => 'array',      // ✅ Auto convert JSON to array
        'Is_Active' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    // ✅ Helper method to get 42 days array
    public function getPatternDaysAttribute()
    {
        $data = $this->pattern_data;

        if (isset($data['days']) && is_array($data['days'])) {
            return $data['days'];
        }

        // Default: 42 days all working (0)
        return array_fill(0, 42, 0);
    }

    // ✅ Helper method to check if a specific day is week-off
    public function isWeekOff($date)
    {
        $days = $this->getPatternDaysAttribute();

        // Calculate position in 42-day cycle
        $firstDayOfYear = date('Y-m-d', strtotime($date . ' - ' . (date('z', strtotime($date))) . ' days'));
        $daysSinceStart = date('z', strtotime($date));
        $position = $daysSinceStart % 42;

        return isset($days[$position]) && $days[$position] == 1;
    }

    // ✅ Helper method to get week-off dates for a month
    public function getWeekOffDatesForMonth($year, $month)
    {
        $startDate = "$year-$month-01";
        $endDate = date('Y-m-t', strtotime($startDate));

        $weekOffDates = [];
        $currentDate = $startDate;

        while ($currentDate <= $endDate) {
            if ($this->isWeekOff($currentDate)) {
                $weekOffDates[] = $currentDate;
            }
            $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
        }

        return $weekOffDates;
    }

    public function getFormattedPattern()
    {
        $days = $this->getPatternDaysAttribute();

        // Group by weeks (7 days per week)
        $weeks = [];
        for ($i = 0; $i < 6; $i++) {
            $weeks[] = array_slice($days, $i * 7, 7);
        }

        return [
            'pattern_id' => $this->WOP_id,
            'pattern_code' => $this->WOP_code,
            'pattern_name' => $this->WOP_name,
            'description' => $this->description,
            'days_array' => $days,
            'weeks' => $weeks
        ];
    }
}
