<?php
declare(strict_types=1);

namespace App\Modules\FacilityDashboards\Services;

use App\Core\App;

final class MirrorDisplayService
{
    public static function getFacilityStates(?string $facilityType = null, ?int $disciplineId = null): array
    {
        $db = App::getInstance()->db();
        $now = date('H:i:s');
        $today = date('Y-m-d');

        $sql = "SELECT f.id, f.name_ar, f.name_en, f.facility_type, f.capacity, f.location,
                       f.linked_discipline_id, f.is_active
                FROM facilities f
                WHERE f.is_active = 1 AND f.is_archived = 0";
        $params = [];

        if ($facilityType) {
            $sql .= " AND f.facility_type = ?";
            $params[] = $facilityType;
        }
        if ($disciplineId) {
            $sql .= " AND f.linked_discipline_id = ?";
            $params[] = $disciplineId;
        }

        $sql .= " ORDER BY f.facility_type ASC, f.name_ar ASC";
        $facilities = $db->select($sql, $params);

        $states = [];
        foreach ($facilities as $f) {
            $facilityId = (int) $f['id'];

            $currentBooking = $db->selectOne(
                "SELECT id, member_id, purpose, start_time, end_time, status
                 FROM reservations
                 WHERE facility_id = ? AND reservation_date = ? AND status IN ('confirmed', 'checked_in')
                 AND start_time <= ? AND end_time > ?
                 ORDER BY start_time ASC LIMIT 1",
                [$facilityId, $today, $now, $now]
            );

            $nextBooking = $db->selectOne(
                "SELECT id, purpose, start_time, end_time
                 FROM reservations
                 WHERE facility_id = ? AND reservation_date = ? AND status = 'confirmed'
                 AND start_time > ?
                 ORDER BY start_time ASC LIMIT 1",
                [$facilityId, $today, $now]
            );

            $todayBookings = $db->selectOne(
                "SELECT COUNT(*) AS cnt FROM reservations
                 WHERE facility_id = ? AND reservation_date = ? AND status NOT IN ('cancelled')
                 ",
                [$facilityId, $today]
            );

            if ($currentBooking) {
                $status = $currentBooking['status'] === 'checked_in' ? 'in_progress' : 'booked';
            } else {
                $status = 'available';
            }

            $timeUntilNext = null;
            if ($nextBooking) {
                $diff = strtotime($nextBooking['start_time']) - strtotime($now);
                if ($diff > 0) {
                    $mins = (int) ($diff / 60);
                    if ($mins < 60) {
                        $timeUntilNext = $mins . ' دقيقة';
                    } else {
                        $hours = (int) ($mins / 60);
                        $remaining = $mins % 60;
                        $timeUntilNext = $hours . ' ساعة' . ($remaining > 0 ? ' و ' . $remaining . ' دقيقة' : '');
                    }
                }
            }

            $states[] = [
                'facility_id'     => $facilityId,
                'name_ar'         => $f['name_ar'],
                'type'            => $f['facility_type'],
                'location'        => $f['location'] ?? '',
                'capacity'        => (int) ($f['capacity'] ?? 0),
                'current_status'  => $status,
                'current_booking' => $currentBooking ? [
                    'purpose'    => $currentBooking['purpose'] ?? '',
                    'start_time' => $currentBooking['start_time'],
                    'end_time'   => $currentBooking['end_time'],
                ] : null,
                'next_booking'    => $nextBooking ? [
                    'purpose'    => $nextBooking['purpose'] ?? '',
                    'start_time' => $nextBooking['start_time'],
                    'end_time'   => $nextBooking['end_time'],
                ] : null,
                'time_until_next' => $timeUntilNext,
                'today_count'     => (int) ($todayBookings['cnt'] ?? 0),
            ];
        }

        return $states;
    }
}
