<?php
// db/quote-read.php
ob_start();
error_reporting(E_ALL); // Mantengo los errores visibles para depuración
ini_set('display_errors', 1); // Mantengo los errores visibles para depuración

include_once 'db_connection.php';

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

try {
    // Preparar la consulta para obtener estimados y sus ítems
    $stmt = $pdo->query("
        SELECT
            e.id AS estimate_db_id,
            e.external_id,
            e.client_id,
            e.lead_id,
            e.estimate_date,
            e.status,
            e.tax_rate,
            e.subtotal,
            e.total_amount,
            e.created_at,
            ci.first_name AS client_first_name,
            ci.last_name AS client_last_name,
            ci.email AS client_email,
            ci.phone AS client_phone,
            ci.mobile AS client_mobile,
            ci.street_address AS client_street_address,
            ci.city AS client_city,
            ci.state_province AS client_state_province,
            ci.zip_code AS client_zip_code,
            l.first_name AS lead_first_name,
            l.last_name AS lead_last_name,
            l.email AS lead_email,
            l.phone AS lead_phone,
            l.mobile AS lead_mobile,
            l.company AS lead_company,
            l.street_address AS lead_street_address,
            l.city AS lead_city,
            l.state_province AS lead_state_province,
            l.zip_code AS lead_zip_code
        FROM
            estimates e
        LEFT JOIN
            clients ci ON e.client_id = ci.id
        LEFT JOIN
            leads l ON e.lead_id = l.id
        ORDER BY
            e.estimate_date DESC, e.created_at DESC
    ");
    $estimates_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $estimates_processed = [];
    $estimate_db_ids = []; // Para recolectar IDs de la DB para los ítems

    foreach ($estimates_raw as $row) {
        $estimate_db_id = $row['estimate_db_id'];
        $external_id = $row['external_id'];

        $contact_info = null;
        $contact_type = 'unknown';
        $contact_name_display = 'Desconocido';
        $contact_address_display = '';

        if (!is_null($row['client_id'])) {
            $contact_type = 'client';
            $contact_name_display = trim($row['client_first_name'] . ' ' . $row['client_last_name']);
            $contact_address_display = trim($row['client_street_address'] . ', ' . $row['client_city'] . ', ' . $row['client_state_province'] . ' ' . $row['client_zip_code']);
            $contact_info = [
                'id' => (int)$row['client_id'],
                'name' => $contact_name_display,
                'email' => $row['client_email'],
                'phone' => $row['client_phone'],
                'mobile' => $row['client_mobile'],
                'address' => $contact_address_display,
                'type' => 'client'
            ];
        } elseif (!is_null($row['lead_id'])) {
            $contact_type = 'prospect';
            $contact_name_display = trim($row['lead_first_name'] . ' ' . $row['lead_last_name']);
            $contact_address_display = !empty($row['lead_company']) ? $row['lead_company'] : trim($row['lead_street_address'] . ', ' . $row['lead_city'] . ', ' . $row['lead_state_province'] . ' ' . $row['lead_zip_code']);
            $contact_info = [
                'id' => $row['lead_id'], // Lead ID es VARCHAR
                'name' => $contact_name_display,
                'email' => $row['lead_email'],
                'phone' => $row['lead_phone'],
                'mobile' => $row['lead_mobile'],
                'address' => $contact_address_display,
                'company' => $row['lead_company'], // Incluir company para prospectos
                'type' => 'prospect'
            ];
        }

        // *** CORRECCIÓN CLAVE AQUÍ: Usar external_id como clave del array principal ***
        $estimates_processed[$external_id] = [
            'db_id' => (int)$estimate_db_id, // El ID numérico de la DB
            'id' => $external_id, // El ID 'est-XXXX' para compatibilidad frontend
            'fechaSolicitud' => $row['estimate_date'], // Nombre esperado en JS
            'estado' => $row['status'],
            'taxRate' => (float)$row['tax_rate'],
            'subtotal' => (float)$row['subtotal'],
            'montoEstimado' => (float)$row['total_amount'], // Nombre esperado en JS
            'created_at' => $row['created_at'],
            'contactType' => $contact_type, // Tipo de contacto (client/prospect)
            'cliente' => $contact_name_display, // Nombre del cliente/prospecto para la lista
            'contact' => $contact_info, // Objeto completo del contacto
            'servicio' => 'Sin Servicios', // Placeholder, se llenará con el primer ítem
            'items' => [], // Se llenará en un segundo paso
        ];

        $estimate_db_ids[] = $estimate_db_id; // Recolectar solo los db_id para la consulta de ítems
    }

    // Si hay estimados, obtener sus ítems
    if (!empty($estimate_db_ids)) {
        $placeholders = implode(',', array_fill(0, count($estimate_db_ids), '?'));
        $stmt_items = $pdo->prepare("SELECT estimate_id, description, unit_price, quantity FROM estimate_items WHERE estimate_id IN ($placeholders) ORDER BY id ASC");
        $stmt_items->execute($estimate_db_ids);
        $items_raw = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

        // Reorganizar los ítems por estimate_id para fácil acceso
        $items_by_estimate_id = [];
        foreach ($items_raw as $item_row) {
            $items_by_estimate_id[$item_row['estimate_id']][] = [
                $item_row['description'],
                (float)$item_row['unit_price'],
                (int)$item_row['quantity']
            ];
        }

        // Asignar los ítems a los estimados procesados usando el db_id
        foreach ($estimates_processed as $external_id => &$estimate_data) { // Usar & para modificar el array directamente
            $db_id = $estimate_data['db_id'];
            if (isset($items_by_estimate_id[$db_id])) {
                $estimate_data['items'] = $items_by_estimate_id[$db_id];
                // Asignar el "servicio principal" de cada estimado basado en el primer ítem
                $estimate_data['servicio'] = $estimate_data['items'][0][0];
            }
        }
        unset($estimate_data); // Romper la referencia al último elemento
    }

    // Solo necesitamos devolver los valores del array, ya que el JS los indexará por external_id
    $response_data = ['success' => true, 'data' => array_values($estimates_processed)]; 

} catch (PDOException $e) {
    error_log("Error PDO en quote-read.php: " . $e->getMessage());
    $response_data['message'] = 'Error de Base de Datos al cargar estimados: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("General Error en quote-read.php: " . $e->getMessage());
    $response_data['message'] = 'Error inesperado al cargar estimados: ' . $e->getMessage();
}

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