<?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 = [
        'recurring_masters' => []
    ];

    $stmt_master_app = $pdo->prepare("
        SELECT
            ra.id, ra.client_id, ra.lead_id, ra.frequency, 
            IFNULL(ra.first_appointment_date, CURDATE()) AS first_appointment_date, 
            IFNULL(ra.appointment_time, '00:00:00') AS appointment_time, 
            ra.notes, 
            IFNULL(ra.next_appointment_date, CURDATE()) AS next_appointment_date,
            CONCAT(c.first_name, ' ', c.last_name) AS client_name,
            CONCAT(l.first_name, ' ', l.last_name) AS lead_name
        FROM recurring_appointments ra
        LEFT JOIN clients c ON ra.client_id = c.id
        LEFT JOIN leads l ON ra.lead_id = l.id
        ORDER BY ra.id DESC
    ");
    $stmt_master_app->execute();

    while ($row = $stmt_master_app->fetch(PDO::FETCH_ASSOC)) {
        $contact_name = trim($row['client_name'] ?: $row['lead_name']);

        $sql_children = "
            SELECT COUNT(id) FROM unique_appointments 
            WHERE recurring_parent_id = ? AND appointment_date >= CURDATE()
        ";
        $stmt_child_count = $pdo->prepare($sql_children);
        $stmt_child_count->execute([$row['id']]);
        $remaining_appointments = (int)$stmt_child_count->fetchColumn();


        $data_to_send['recurring_masters'][] = [
            'id' => 'cita-recurrente-' . $row['id'], 
            'db_id' => (int)$row['id'],
            'type' => 'recurrente', 
            'client_id' => $row['client_id'] ? (int)$row['client_id'] : null,
            'lead_id' => $row['lead_id'] ? (int)$row['lead_id'] : null,
            'contact_name' => $contact_name,
            'frequency' => $row['frequency'],
            'first_appointment_date' => $row['first_appointment_date'],
            'next_appointment_date' => $row['next_appointment_date'],
            'appointment_time' => substr($row['appointment_time'], 0, 5), 
            'notes' => $row['notes'],
            'remaining_appointments' => $remaining_appointments 
        ];
    }
    
    echo json_encode(['status' => 'success', 'data' => $data_to_send]);

} catch (PDOException $e) {
    error_log("Error PDO en agenda-recurring-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-recurring-read.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'ERROR GENERAL']);
}

ob_end_clean();
exit;