<?php
ob_start();

require_once __DIR__ . '/../core/api.php';
global $pdo;

ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

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

try {
    // Lectura de la configuración centralizada (id = 1, asumiendo el usuario principal)
    $stmt_config = $pdo->query("SELECT slot_duration, capacity, daily_hours, blocked_dates FROM schedule_config WHERE user_id = 1 LIMIT 1");
    $schedule_data = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if (!$schedule_data) {
        // Inicialización de valores por defecto si no se encuentra el registro
        $schedule_config = ['slot_duration' => 60, 'capacity' => 1];
        $weekly_hours_json = '{}';
        $blocked_dates_json = '[]';
    } else {
        $schedule_config = [
            'slot_duration' => (int)$schedule_data['slot_duration'],
            'capacity' => (int)$schedule_data['capacity']
        ];
        $weekly_hours_json = $schedule_data['daily_hours'];
        $blocked_dates_json = $schedule_data['blocked_dates'];
    }
    
    // Parseo de daily_hours
    $daily_hours = json_decode($weekly_hours_json, true) ?? [];
    $formatted_weekly_hours = [];
    foreach ($daily_hours as $day => $data) {
        // El campo 'active' en el JSON del SQL se mapea a 'is_open' en el frontend PHP original
        $formatted_weekly_hours[$day] = [
            'is_open' => $data['active'] ?? false,
            'open_time' => $data['start'] ?? '09:00', 
            'close_time' => $data['end'] ?? '18:00'
        ];
    }

    // Parseo de blocked_dates
    $blocked_dates = json_decode($blocked_dates_json, true) ?? [];
    
    // El formato original esperaba ['id' => X, 'blocked_date' => Y]. Recreamos la estructura.
    $formatted_blocked_dates = [];
    foreach ($blocked_dates as $index => $row) {
        $formatted_blocked_dates[] = [
            'id' => $index + 1, // Usamos un índice temporal
            'blocked_date' => $row['date'] ?? '' // Asumiendo que el campo es 'date' en el JSON
        ];
    }
    
    $response['data'] = [
        'schedule_config' => $schedule_config,
        'weekly_hours' => $formatted_weekly_hours,
        'blocked_dates' => $formatted_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;