<?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',
    ];

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

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

    /** Returns 'buka' or 'tutup' for the current local time */
    public function currentMode(): string
    {
        $now  = now()->format('H:i');
        $day  = now()->dayOfWeek;
        $isWe = in_array($day, [0, 6]); // 0=Sun, 6=Sat

        if ($isWe) {
            $green = $now >= $this->weekend_green_start && $now <= $this->weekend_green_end;
        } else {
            $green = ($now >= $this->weekday_green_start_1 && $now <= $this->weekday_green_end_1)
                  || ($now >= $this->weekday_green_start_2 && $now <= $this->weekday_green_end_2);
        }

        return $green ? 'buka' : 'tutup';
    }
}
