<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['success' => false, 'data' => [], 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    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);

    $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 = []; 

    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'], 
                'name' => $contact_name_display,
                'email' => $row['lead_email'],
                'phone' => $row['lead_phone'],
                'mobile' => $row['lead_mobile'],
                'address' => $contact_address_display,
                'company' => $row['lead_company'], 
                'type' => 'prospect'
            ];
        }

        $estimates_processed[$external_id] = [
            'db_id' => (int)$estimate_db_id, 
            'id' => $external_id, 
            'fechaSolicitud' => $row['estimate_date'], 
            'estado' => $row['status'],
            'taxRate' => (float)$row['tax_rate'],
            'subtotal' => (float)$row['subtotal'],
            'montoEstimado' => (float)$row['total_amount'], 
            'created_at' => $row['created_at'],
            'contactType' => $contact_type, 
            'cliente' => $contact_name_display, 
            'contact' => $contact_info, 
            'servicio' => 'SIN SERVICIOS', 
            'items' => [], 
        ];

        $estimate_db_ids[] = $estimate_db_id; 
    }

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

        $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']
            ];
        }

        foreach ($estimates_processed as $external_id => &$estimate_data) {
            $db_id = $estimate_data['db_id'];
            if (isset($items_by_estimate_id[$db_id])) {
                $estimate_data['items'] = $items_by_estimate_id[$db_id];
                $estimate_data['servicio'] = $estimate_data['items'][0][0];
            }
        }
        unset($estimate_data); 
    }

    $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';
} catch (Exception $e) {
    error_log("General Error en quote-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO';
}

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