<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Services;

use App\Core\App;

final class PoolHourPlanService
{
    private \App\Core\Database $db;

    public function __construct()
    {
        $this->db = App::getInstance()->db();
    }

    public function getHoursForDate(int $planId, string $date): array
    {
        return $this->db->select(
            "SELECT id, hour_slot, period, grid_snapshot_json, notes, updated_at
             FROM pool_hour_plans
             WHERE monthly_plan_id = ? AND plan_date = ?
             ORDER BY hour_slot",
            [$planId, $date]
        );
    }

    public function getHourPlan(int $planId, string $date, string $hour): ?array
    {
        return $this->db->selectOne(
            "SELECT * FROM pool_hour_plans WHERE monthly_plan_id = ? AND plan_date = ? AND hour_slot = ?",
            [$planId, $date, $hour]
        );
    }

    public function saveHourPlan(int $planId, string $date, string $hour, array $gridSnapshot, ?string $notes = null): int
    {
        $plan = $this->db->selectOne(
            "SELECT * FROM facility_monthly_plans WHERE id = ?",
            [$planId]
        );

        $period = 'day';
        if ($plan && $hour >= ($plan['night_hours_start'] ?? '18:00')) {
            $period = 'night';
        }

        $existing = $this->db->selectOne(
            "SELECT id FROM pool_hour_plans WHERE monthly_plan_id = ? AND plan_date = ? AND hour_slot = ?",
            [$planId, $date, $hour]
        );

        $snapshotJson = json_encode($gridSnapshot, JSON_UNESCAPED_UNICODE);

        if ($existing) {
            $this->db->update('pool_hour_plans', [
                'grid_snapshot_json' => $snapshotJson,
                'period' => $period,
                'notes' => $notes,
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $existing['id']]);
            return (int) $existing['id'];
        }

        $this->db->insert('pool_hour_plans', [
            'monthly_plan_id' => $planId,
            'plan_date' => $date,
            'hour_slot' => $hour,
            'period' => $period,
            'grid_snapshot_json' => $snapshotJson,
            'notes' => $notes,
        ]);

        return (int) $this->db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];
    }

    public function copyHourPlan(int $planId, string $fromDate, string $fromHour, string $toDate, string $toHour): bool
    {
        $source = $this->getHourPlan($planId, $fromDate, $fromHour);
        if (!$source) {
            return false;
        }

        $snapshot = json_decode($source['grid_snapshot_json'], true);
        $this->saveHourPlan($planId, $toDate, $toHour, $snapshot, $source['notes']);
        return true;
    }

    public function getWorkingHoursForDate(int $planId, string $date): array
    {
        $plan = $this->db->selectOne(
            "SELECT * FROM facility_monthly_plans WHERE id = ?",
            [$planId]
        );

        if (!$plan) {
            return [];
        }

        $dayStart = $plan['day_hours_start'] ?? '07:00';
        $dayEnd = $plan['day_hours_end'] ?? '14:00';
        $nightStart = $plan['night_hours_start'] ?? '14:00';
        $nightEnd = $plan['night_hours_end'] ?? '22:00';

        $hours = [];
        $current = strtotime($dayStart);
        $end = strtotime($nightEnd);

        while ($current < $end) {
            $timeStr = date('H:i', $current);
            $period = $current < strtotime($nightStart) ? 'day' : 'night';
            $hours[] = ['time' => $timeStr . ':00', 'period' => $period];
            $current += 3600;
        }

        return $hours;
    }
}
