<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO', 'notes' => []];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    $lead_id = isset($_GET['lead_id']) ? filter_var($_GET['lead_id'], FILTER_VALIDATE_INT) : 0;

    if ($lead_id === false || $lead_id === 0) {
        throw new Exception('ID INVALIDO');
    }

    $stmt = $pdo->prepare("SELECT id, content, created_at FROM lead_notes WHERE lead_id = ? ORDER BY created_at DESC");
    $stmt->execute([$lead_id]);
    $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // No se incluye mensaje de éxito en operaciones de lectura (UX)
    $response = ['success' => true, 'notes' => $notes];

} catch (PDOException $e) {
    error_log("Error PDO en leads-get-notes.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en leads-get-notes.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>