<?php
declare(strict_types=1);

namespace App\Modules\Facilities\Models;

use App\Core\Model;

class FacilityBlackoutDate extends Model
{
    protected static string $table = 'facility_blackout_dates';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'facility_id',
        'blackout_date',
        'start_time',
        'end_time',
        'reason',
        'created_by',
    ];

    /**
     * Get upcoming blackout dates for a facility (today and future), ordered by date.
     */
    public static function getForFacility(int $facilityId): array
    {
        return static::query()
            ->where('facility_id', '=', $facilityId)
            ->whereRaw('`blackout_date` >= CURDATE()')
            ->orderBy('blackout_date', 'ASC')
            ->orderBy('start_time', 'ASC')
            ->get();
    }

    /**
     * Check if a given date (and optionally time) is blocked for a facility.
     */
    public static function isBlackedOut(int $facilityId, string $date, ?string $time = null): bool
    {
        $query = static::query()
            ->where('facility_id', '=', $facilityId)
            ->where('blackout_date', '=', $date);

        $rows = $query->get();

        if (empty($rows)) {
            return false;
        }

        foreach ($rows as $row) {
            // If the blackout has no start/end time, it blocks the entire day
            if (empty($row['start_time']) && empty($row['end_time'])) {
                return true;
            }

            // If no specific time to check, any blackout on this date counts
            if ($time === null) {
                return true;
            }

            // Check if the requested time falls within the blackout window
            $start = $row['start_time'] ?? '00:00:00';
            $end   = $row['end_time']   ?? '23:59:59';
            if ($time >= $start && $time <= $end) {
                return true;
            }
        }

        return false;
    }
}
