<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DeviceSchedule extends Model
{
    protected $fillable = [
        'device_id', 'enabled',
        'weekday_green_start_1', 'weekday_green_end_1',
        'weekday_green_start_2', 'weekday_green_end_2',
        'weekend_green_start',   'weekend_green_end',
        'repush_hours', 'last_auto_sent_at',
        'schedule_windows', 'use_public_holiday_mode', 'public_holiday_treat_as',
    ];

    protected $casts = [
        'enabled'                 => 'boolean',
        'use_public_holiday_mode' => 'boolean',
        'last_auto_sent_at'       => 'datetime',
    ];

    public function device(): BelongsTo
    {
        return $this->belongsTo(Device::class);
    }

    /** Returns the parsed windows array (with fallback to legacy columns). */
    public function getWindows(): array
    {
        if ($this->schedule_windows) {
            return json_decode($this->schedule_windows, true) ?? [];
        }

        // Backward compat: build from old fixed columns
        return [
            [
                'label' => 'Morning Peak',
                'days'  => [1, 2, 3, 4, 5],
                'start' => substr($this->weekday_green_start_1 ?? '06:00', 0, 5),
                'end'   => substr($this->weekday_green_end_1   ?? '10:00', 0, 5),
            ],
            [
                'label' => 'Evening Peak',
                'days'  => [1, 2, 3, 4, 5],
                'start' => substr($this->weekday_green_start_2 ?? '16:00', 0, 5),
                'end'   => substr($this->weekday_green_end_2   ?? '20:00', 0, 5),
            ],
            [
                'label' => 'Weekend',
                'days'  => [0, 6],
                'start' => substr($this->weekend_green_start ?? '10:00', 0, 5),
                'end'   => substr($this->weekend_green_end   ?? '22:00', 0, 5),
            ],
        ];
    }

    /** Returns 'buka' or 'tutup' for the current local time. */
    public function currentMode(): string
    {
        $windows   = $this->getWindows();
        $now       = now()->format('H:i');
        $dayOfWeek = (int) now()->format('w'); // 0=Sun, 6=Sat

        foreach ($windows as $win) {
            $days = $win['days'] ?? [];
            if (in_array($dayOfWeek, $days, true)) {
                $start = substr($win['start'] ?? '00:00', 0, 5);
                $end   = substr($win['end']   ?? '00:00', 0, 5);
                if ($now >= $start && $now <= $end) {
                    return 'buka';
                }
            }
        }

        return 'tutup';
    }

    /** Human-readable summary of all windows. */
    public function windowsSummary(): string
    {
        $names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        $parts = [];
        foreach ($this->getWindows() as $w) {
            $days = implode('/', array_map(fn($d) => $names[$d] ?? $d, $w['days'] ?? []));
            $parts[] = "{$w['label']} ({$days} {$w['start']}–{$w['end']})";
        }
        return implode(' | ', $parts);
    }
}
