<?php
// db/clients-read-contact-data.php
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response_data = ['success' => false, 'data' => []];

try {
    $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']);
        $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 al cargar datos de clientes para quotes: " . $e->getMessage());
    $response_data['message'] = 'Error de Base de Datos al cargar clientes: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("Error general al cargar datos de clientes para quotes: " . $e->getMessage());
    $response_data['message'] = 'Error inesperado al cargar clientes: ' . $e->getMessage();
}

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