<?php
ob_start();
header('Content-Type: application/json');
$response = ['status' => 'ERROR', 'message' => 'ERROR DESCONOCIDO'];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    require_once __DIR__ . '/../core/api.php';

    if (!isset($_GET['date'])) {
         throw new Exception('FECHA NO PROPORCIONADA');
    }
    
    $date = $_GET['date'];

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        $response = ['status' => 'ERROR', 'message' => 'FORMATO DE FECHA INVALIDO'];
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt_config = $pdo->query("SELECT start_time, end_time, slot_duration, capacity, work_days FROM schedule_config WHERE id = 1 LIMIT 1");
    $config = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if (!$config) {
        throw new Exception("CONFIGURACION DE AGENDA NO ENCONTRADA");
    }

    $work_days = explode(',', $config['work_days']);
    $requested_day_of_week = date('N', strtotime($date)); 
    if (!in_array($requested_day_of_week, $work_days)) {
        $response = ['status' => 'OK', 'data' => []];
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt_booked = $pdo->prepare("
        SELECT appointment_time, COUNT(id) as booked_count 
        FROM unique_appointments 
        WHERE appointment_date = ? 
        GROUP BY appointment_time
    ");
    $stmt_booked->execute([$date]);
    $booked_slots = $stmt_booked->fetchAll(PDO::FETCH_KEY_PAIR);

    $available_slots = [];
    $start = new DateTime($config['start_time']);
    $end = new DateTime($config['end_time']);
    $interval = new DateInterval('PT' . $config['slot_duration'] . 'M');
    $capacity = (int)$config['capacity'];

    for ($time = $start; $time < $end; $time->add($interval)) {
        $slot_time_full = $time->format('H:i:s');
        $slot_time_short = $time->format('H:i');

        $booked_count = isset($booked_slots[$slot_time_full]) ? (int)$booked_slots[$slot_time_full] : 0;

        if (($capacity - $booked_count) > 0) {
            $available_slots[] = $slot_time_short;
        }
    }

    $response = ['status' => 'OK', 'data' => $available_slots];

} catch (PDOException $e) {
    error_log("Error PDO en get-slots.php: " . $e->getMessage());
    $response = ['status' => 'ERROR', 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("Error general en get-slots.php: " . $e->getMessage());
    $response = ['status' => 'ERROR', 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>