<?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';

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

    $stmt_app = $pdo->query("
        SELECT
            ua.id, ua.client_id, ua.lead_id, ua.appointment_date, ua.appointment_time, ua.status, ua.notes,
            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
        ORDER BY ua.appointment_date, ua.appointment_time
    ");
    while ($row = $stmt_app->fetch(PDO::FETCH_ASSOC)) {
        $data_to_send['appointments'][] = [
            'id' => 'cita-unica-' . $row['id'],
            'db_id' => (int)$row['id'],
            'type' => 'unica',
            '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']
        ];
    }
    
    $stmt_clients = $pdo->query("SELECT id, first_name, last_name, email, mobile FROM clients");
    $data_to_send['clients'] = $stmt_clients->fetchAll(PDO::FETCH_ASSOC);

    $stmt_leads = $pdo->query("SELECT id, first_name, last_name, email, mobile FROM leads");
    $data_to_send['leads'] = $stmt_leads->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status' => 'success', 'data' => $data_to_send]);

} catch (Exception $e) {
    error_log("Error en agenda-read.php: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'ERROR AL CARGAR LOS DATOS DE LA AGENDA']);
}

ob_end_clean();
exit;