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

try {
    require_once __DIR__ . '/../core/api.php';

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

    $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";

    $stmt = $pdo->query($query);
    $db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_prospects = [];
    foreach ($db_prospects_rows as $row) {
        $formatted_prospects[] = [
            'id' => $row['id'],
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'nombre_completo' => trim($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 en leads-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general en leads-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR INESPERADO';
}

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