<?php ob_start();
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);

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

try {
    include_once 'db_connection.php';

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

        $formatted_clients[] = [
            'id' => (int)$client['id'],
            'name' => $full_name,
            'email' => $client['email'],
            'phone' => $client['phone'],
            'mobile' => $client['mobile'],
            'address' => $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;
?>