<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/availability.php';

$tenant = resolve_tenant_from_host();
if (!$tenant) {
    json_response(['ok' => false, 'error' => 'Shop not found'], 404);
}
$tenantId = (int) $tenant['id'];
$action = $_GET['action'] ?? 'slots';

try {
    $serviceId = (int) ($_GET['service_id'] ?? 0);
    $staffId = ($_GET['staff_id'] ?? '') !== '' ? (int) $_GET['staff_id'] : null;

    if ($serviceId <= 0) {
        json_response(['ok' => false, 'error' => 'service_id required'], 400);
    }

    if ($action === 'first') {
        json_response(availability_first_available($tenantId, $serviceId, $staffId, 14));
    }

    $date = trim((string) ($_GET['date'] ?? date('Y-m-d')));
    $exclude = isset($_GET['exclude_booking']) ? (int) $_GET['exclude_booking'] : null;
    $collapse = !isset($_GET['collapse']) || (string) $_GET['collapse'] !== '0';
    json_response(availability_get_slots($tenantId, $serviceId, $date, $staffId, $collapse, $exclude ?: null));
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => $e->getMessage()], 400);
}
