<?php
ob_start();
require_once '../files/guardiankey.php';
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once 'db_connection.php';

$response = ['status' => 'error', 'message' => 'ERROR AL CARGAR DATOS', 'data' => []];

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

    $stmt_hours = $pdo->query("SELECT day, is_open, open_time, close_time FROM cms_weekly_hours WHERE schedule_id = 1");
    $weekly_hours = $stmt_hours->fetchAll(PDO::FETCH_ASSOC);
    
    $formatted_weekly_hours = [];
    foreach ($weekly_hours as $row) {
        $formatted_weekly_hours[$row['day']] = [
            'is_open' => (bool)$row['is_open'],
            'open_time' => substr($row['open_time'], 0, 5), 
            'close_time' => substr($row['close_time'], 0, 5)
        ];
    }

    $stmt_blocked = $pdo->query("SELECT id, blocked_date FROM cms_blocked_dates ORDER BY blocked_date ASC");
    $blocked_dates = $stmt_blocked->fetchAll(PDO::FETCH_ASSOC);
    
    $response['data'] = [
        'schedule_config' => $schedule_config ?: ['slot_duration' => 60, 'capacity' => 1],
        'weekly_hours' => $formatted_weekly_hours,
        'blocked_dates' => $blocked_dates
    ];
    $response['status'] = 'success';
    unset($response['message']); 

} catch (PDOException $e) {
    error_log("Error en agenda-config-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS AL LEER DATOS';
}

ob_end_clean();
echo json_encode($response);
exit;