<?php
ob_start();
ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';
global $pdo;

try {
    $data_to_send = [
        'appointments' => [],
        'clients' => [],
        'leads' => []
    ];

    $stmt_app = $pdo->prepare("
        SELECT
            ua.id, ua.client_id, ua.lead_id, ua.appointment_date, ua.appointment_time, ua.status, ua.notes,
            ua.public_token,
            ua.recurring_parent_id,
            CONCAT(c.first_name, ' ', c.last_name) AS client_name,
            CONCAT(l.first_name, ' ', l.last_name) AS lead_name
        FROM unique_appointments ua
        LEFT JOIN clients c ON ua.client_id = c.id
        LEFT JOIN leads l ON ua.lead_id = l.id
        WHERE 
            ua.appointment_date >= DATE_SUB(CURDATE(), INTERVAL 2 MONTH) 
        ORDER BY ua.appointment_date ASC, ua.appointment_time ASC
    ");
    
    $stmt_app->execute();

    while ($row = $stmt_app->fetch(PDO::FETCH_ASSOC)) {
        $data_to_send['appointments'][] = [
            'id' => 'cita-unica-' . (int)$row['id'],
            'db_id' => (int)$row['id'],
            'type' => $row['recurring_parent_id'] ? 'child_recurrente' : 'unica',
            'recurring_parent_id' => $row['recurring_parent_id'] ? (int)$row['recurring_parent_id'] : null,
            'client_id' => $row['client_id'] ? (int)$row['client_id'] : null,
            'lead_id' => $row['lead_id'] ? (int)$row['lead_id'] : null,
            'contact_name' => trim($row['client_name'] ?: $row['lead_name']),
            'date' => $row['appointment_date'],
            'time' => substr($row['appointment_time'], 0, 5), 
            'status' => $row['status'],
            'notes' => $row['notes'],
            'public_token' => $row['public_token']
        ];
    }
    
    $stmt_clients = $pdo->prepare("SELECT id, first_name, last_name, email, mobile, CONCAT(first_name, ' ', last_name) as full_name FROM clients");
    $stmt_clients->execute();
    while($row = $stmt_clients->fetch(PDO::FETCH_ASSOC)) {
        $row['name'] = $row['full_name']; 
        $data_to_send['clients']['client-' . $row['id']] = $row;
    }

    $stmt_leads = $pdo->prepare("SELECT id, first_name, last_name, email, phone, CONCAT(first_name, ' ', last_name) as full_name FROM leads");
    $stmt_leads->execute();
    while($row = $stmt_leads->fetch(PDO::FETCH_ASSOC)) {
        $row['name'] = $row['full_name'];
        $data_to_send['leads']['lead-' . $row['id']] = $row;
    }
    
    echo json_encode(['status' => 'success', 'data' => $data_to_send]);

} catch (PDOException $e) {
    error_log("Error PDO en agenda-read.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'ERROR DE BASE DE DATOS']);
} catch (Exception $e) {
    error_log("Error general en agenda-read.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'ERROR GENERAL']);
}

ob_end_clean();
exit;