<?php ob_start();

require_once __DIR__ . '/../core/api.php';
global $pdo;

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

header('Content-Type: application/json');
$response_data = ['success' => false, 'data' => []];

try {
    
    // Mitigación XSS: Función de sanitización de salida para prevenir XSS
    function sanitize_output($value) {
        return $value !== null ? htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8') : null;
    }
    
    $stmt = $pdo->query("SELECT id, first_name, last_name, email, phone, mobile, street_address, city, state_province, zip_code FROM clients ORDER BY first_name ASC, last_name ASC");
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_clients = [];
    foreach ($clients as $client) {
        $full_name = trim($client['first_name'] . ' ' . $client['last_name']);
        
        if (empty($full_name)) {
            $full_name = $client['email'] ?? '[CLIENTE SIN NOMBRE]';
        }

        $address_parts = [];
        if (!empty($client['street_address'])) $address_parts[] = $client['street_address'];
        if (!empty($client['city'])) $address_parts[] = $client['city'];
        if (!empty($client['state_province'])) $address_parts[] = $client['state_province'];
        if (!empty($client['zip_code'])) $address_parts[] = $client['zip_code'];
        $full_address = implode(', ', $address_parts);

        // Aplicar sanitización a todos los campos que van al cliente (navegador)
        $formatted_clients[] = [
            'id' => (int)$client['id'],
            'name' => sanitize_output($full_name),
            'email' => sanitize_output($client['email']),
            'phone' => sanitize_output($client['phone']),
            'mobile' => sanitize_output($client['mobile']),
            'address' => sanitize_output($full_address),
            'type' => 'client'
        ];
    }

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

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

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response_data);
exit;