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

try {
    include_once 'db_connection.php'; 
    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);

    $stmt = $pdo->query("SELECT id, first_name, last_name, company, email, phone, mobile, source, status, priority, street_address, city, state_province, zip_code, created_at FROM leads ORDER BY created_at DESC, first_name ASC");
    $db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_prospects = [];
    foreach ($db_prospects_rows as $row) {
        $formatted_prospects[$row['id']] = [
            'id' => $row['id'],
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'nombre_completo' => $row['first_name'] . ' ' . $row['last_name'],
            'empresa' => $row['company'] ?? '',
            'email' => $row['email'],
            'phone' => $row['phone'],
            'mobile' => $row['mobile'] ?? '',
            'fuente' => $row['source'],
            'estado' => $row['status'],
            'prioridad' => $row['priority'] ?? 'Media',
            'direccion_calle' => $row['street_address'],
            'ciudad' => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code' => $row['zip_code'],
            'created_at' => $row['created_at']
        ];
    }

    $response['success'] = true;
    $response['data'] = $formatted_prospects;
    
} catch (PDOException $e) {
    error_log("Error PDO al cargar prospectos desde la DB en leads-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general al cargar prospectos en leads-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR INESPERADO';
}

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