<?php
// db/agenda-read.php
ob_start();
error_reporting(0); // Cambiar a E_ALL; ini_set('display_errors', 1); para depuración
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response_data = ['status' => 'error', 'message' => 'Error desconocido.', 'data' => []];

try {
    $appointments = [];

    // --- Citas Únicas ---
    $stmt_unica = $pdo->query("
        SELECT
            ua.id,
            ua.client_id,
            ua.service_id,
            ua.appointment_date,
            ua.appointment_time,
            ua.status,
            ua.notes,
            c.first_name,
            c.last_name,
            s.name AS service_name
        FROM
            unique_appointments ua
        LEFT JOIN
            clients c ON ua.client_id = c.id
        LEFT JOIN
            services s ON ua.service_id = s.id
        ORDER BY ua.appointment_date ASC, ua.appointment_time ASC
    ");
    while ($row = $stmt_unica->fetch(PDO::FETCH_ASSOC)) {
        $client_name = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
        $appointments[] = [
            'id' => 'unica-' . $row['id'], // Prefijo para identificar tipo en JS
            'db_id' => (int)$row['id'],
            'type' => 'unica',
            'client_id' => (int)$row['client_id'],
            'client_name' => $client_name,
            'service_id' => (int)$row['service_id'],
            'service_name' => $row['service_name'],
            'date' => $row['appointment_date'],
            'time' => $row['appointment_time'],
            'status' => $row['status'],
            'notes' => $row['notes']
        ];
    }

    // --- Citas Recurrentes ---
    // Nota: Las citas recurrentes pueden necesitar lógica para generar sus "instancias" futuras si tu calendario las muestra.
    // Aquí solo listamos la cita recurrente principal y su próxima fecha.
    $stmt_recurrente = $pdo->query("
        SELECT
            ra.id,
            ra.client_id,
            ra.service_id,
            ra.frequency,
            ra.next_appointment_date,
            ra.notes,
            c.first_name,
            c.last_name,
            s.name AS service_name
        FROM
            recurring_appointments ra
        LEFT JOIN
            clients c ON ra.client_id = c.id
        LEFT JOIN
            services s ON ra.service_id = s.id
        ORDER BY ra.next_appointment_date ASC
    ");
    while ($row = $stmt_recurrente->fetch(PDO::FETCH_ASSOC)) {
        $client_name = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
        $appointments[] = [
            'id' => 'recurrente-' . $row['id'], // Prefijo para identificar tipo en JS
            'db_id' => (int)$row['id'],
            'type' => 'recurrente',
            'client_id' => (int)$row['client_id'],
            'client_name' => $client_name,
            'service_id' => (int)$row['service_id'],
            'service_name' => $row['service_name'],
            'frequency' => $row['frequency'],
            'date' => $row['next_appointment_date'], // Usamos next_appointment_date como la fecha principal
            'time' => 'N/A', // Las recurrentes no tienen hora específica en este esquema
            'status' => 'activa', // Las recurrentes no tienen 'status' per se, asumimos 'activa'
            'notes' => $row['notes']
        ];
    }

    $response_data = ['status' => 'success', 'message' => 'Citas cargadas con éxito.', 'data' => $appointments];

} catch (PDOException $e) {
    error_log("Error PDO en agenda-read.php: " . $e->getMessage());
    $response_data['message'] = 'Error de Base de Datos al cargar citas: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("Error general en agenda-read.php: " . $e->getMessage());
    $response_data['message'] = 'Error inesperado al cargar citas: ' . $e->getMessage();
}

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response_data);
exit;
?>