<?php

declare(strict_types=1);

namespace App\Core;

use App\Core\Database as DB;

/**
 * Guest-house nightly availability engine, per unit. A stay occupies whole
 * nights from check-in (inclusive) to check-out (exclusive); a night is
 * unavailable if it falls inside another live stay for that unit, a blackout
 * covering that unit (or all units), or in the past. Used by both the public
 * /api/guesthouse/units/{id}/availability endpoint and the server-side
 * booking guard in PaymentController, so the two never disagree.
 */
final class Stay
{
    /** Bookings in these states no longer hold their nights. */
    private const FREED_STATES = ['cancelled', 'failed'];

    /**
     * Unavailable nights within [$from, $to) for one unit — booked,
     * blacked-out (for this unit or every unit), or past.
     *
     * @return list<string> sorted, de-duplicated "YYYY-MM-DD"
     */
    public static function unavailableDates(int $unitId, string $from, string $to): array
    {
        Schema::heal();
        if (!self::isDate($from) || !self::isDate($to) || $from >= $to) {
            return [];
        }
        $today = date('Y-m-d');
        $occupied = self::occupiedSet($unitId);
        $out = [];
        foreach (self::eachNight($from, $to) as $d) {
            if ($d < $today || isset($occupied[$d])) {
                $out[] = $d;
            }
        }
        return $out;
    }

    /** True only if every night in [$checkIn, $checkOut) is genuinely bookable now for this unit. */
    public static function isRangeOpen(int $unitId, string $checkIn, string $checkOut, int $minNights = 1): bool
    {
        Schema::heal();
        if (!self::isDate($checkIn) || !self::isDate($checkOut) || $checkIn < date('Y-m-d')) {
            return false;
        }
        $nights = self::nights($checkIn, $checkOut);
        if ($nights < 1 || $nights < max(1, $minNights)) {
            return false;
        }
        $occupied = self::occupiedSet($unitId);
        foreach (self::eachNight($checkIn, $checkOut) as $d) {
            if (isset($occupied[$d])) {
                return false;
            }
        }
        return true;
    }

    /** Number of nights between two dates (0 if invalid or non-positive). */
    public static function nights(string $checkIn, string $checkOut): int
    {
        if (!self::isDate($checkIn) || !self::isDate($checkOut)) {
            return 0;
        }
        $a = strtotime($checkIn);
        $b = strtotime($checkOut);
        if ($a === false || $b === false || $b <= $a) {
            return 0;
        }
        return (int) round(($b - $a) / 86400);
    }

    /** @return array<string,true> every night blocked by a live booking or a blackout, for one unit */
    private static function occupiedSet(int $unitId): array
    {
        $set = [];
        foreach (DB::select(
            'SELECT date FROM stay_blackouts WHERE unit_id IS NULL OR unit_id = ?',
            [$unitId],
        ) as $r) {
            $set[(string) $r['date']] = true;
        }
        $placeholders = implode(',', array_fill(0, count(self::FREED_STATES), '?'));
        foreach (DB::select(
            "SELECT check_in, check_out FROM bookings
             WHERE item_type = 'stay' AND unit_id = ? AND status NOT IN ($placeholders)
               AND check_in <> '' AND check_out <> ''",
            [$unitId, ...self::FREED_STATES],
        ) as $b) {
            foreach (self::eachNight((string) $b['check_in'], (string) $b['check_out']) as $d) {
                $set[$d] = true;
            }
        }
        return $set;
    }

    /**
     * Nights from $from (inclusive) to $to (exclusive).
     *
     * @return list<string>
     */
    private static function eachNight(string $from, string $to): array
    {
        if (!self::isDate($from) || !self::isDate($to)) {
            return [];
        }
        $t = strtotime($from);
        $end = strtotime($to);
        if ($t === false || $end === false) {
            return [];
        }
        $out = [];
        $guard = 0;
        while ($t < $end && $guard++ < 800) { // guard caps runaway ranges (~2 years)
            $out[] = date('Y-m-d', $t);
            $t = strtotime('+1 day', $t);
        }
        return $out;
    }

    private static function isDate(string $d): bool
    {
        return preg_match('/^\d{4}-\d{2}-\d{2}$/', $d) === 1
            && checkdate((int) substr($d, 5, 2), (int) substr($d, 8, 2), (int) substr($d, 0, 4));
    }
}
