<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['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);

    $sql = "SELECT id, first_name, last_name, email, phone, mobile, company, 
            street_address, city, state_province, zip_code 
            FROM leads 
            ORDER BY first_name ASC, last_name ASC";

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

    $formatted_leads = [];
    foreach ($leads as $lead) {
        $full_name = trim($lead['first_name'] . ' ' . $lead['last_name']);
        
        $address_parts = [];
        if (!empty($lead['street_address'])) $address_parts[] = $lead['street_address'];
        if (!empty($lead['city'])) $address_parts[] = $lead['city'];
        if (!empty($lead['state_province'])) $address_parts[] = $lead['state_province'];
        if (!empty($lead['zip_code'])) $address_parts[] = $lead['zip_code'];
        
        $full_address = implode(', ', $address_parts);

        $formatted_leads[] = [
            'id' => $lead['id'],
            'name' => $full_name,
            'email' => $lead['email'],
            'phone' => $lead['phone'],
            'mobile' => $lead['mobile'],
            'address' => $full_address,
            'company' => $lead['company'],
            'type' => 'prospect'
        ];
    }

    $response_data = ['success' => true, 'data' => $formatted_leads];

} catch (PDOException $e) {
    error_log("Error PDO en leads-read-contact-data.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general en leads-read-contact-data.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO';
}

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