<?php
ob_start();

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

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

try {
    require_once __DIR__ . '/../core/api.php';

    $stmt = $pdo->query("
        SELECT
            i.id AS invoice_db_id,
            i.external_id,
            i.client_id,
            i.lead_id,
            i.invoice_date,
            i.status,
            i.tax_rate,
            i.subtotal,
            i.total_amount,
            i.created_at,
            c.first_name AS client_first_name,
            c.last_name AS client_last_name,
            c.email AS client_email,
            c.phone AS client_phone,
            c.mobile AS client_mobile,
            c.street_address AS client_street_address,
            c.city AS client_city,
            c.state_province AS client_state_province,
            c.zip_code AS client_zip_code,
            l.first_name AS lead_first_name,
            l.last_name AS lead_last_name
        FROM
            invoices i
        LEFT JOIN
            clients c ON i.client_id = c.id
        LEFT JOIN
            leads l ON i.lead_id = l.id
        ORDER BY
            i.invoice_date DESC, i.created_at DESC
    ");
    $invoices_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $invoices_processed = [];
    $invoice_db_ids = [];

    foreach ($invoices_raw as $row) {
        $invoice_db_id = $row['invoice_db_id'];
        $external_id = $row['external_id'];
        $contact_info = null;
        $contact_name_display = 'CONTACTO NO ASIGNADO';
        $contact_address_display = '';
        $contact_type = 'none';

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

        $invoices_processed[$external_id] = [
            'db_id' => (int)$invoice_db_id,
            'id' => $external_id,
            'fechaSolicitud' => $row['invoice_date'],
            'estado' => $row['status'],
            'taxRate' => (float)$row['tax_rate'],
            'subtotal' => (float)$row['subtotal'],
            'montoFacturado' => (float)$row['total_amount'],
            'created_at' => $row['created_at'],
            'contactType' => $contact_type,
            'cliente' => $contact_name_display,
            'contact' => $contact_info,
            'servicio' => 'CARGANDO...', 
            'items' => [],
        ];
        $invoice_db_ids[] = $invoice_db_id;
    }

    if (!empty($invoice_db_ids)) {
        $placeholders = implode(',', array_fill(0, count($invoice_db_ids), '?'));
        
        $stmt_items = $pdo->prepare("
            SELECT ii.invoice_id, ii.description, ii.unit_price, ii.quantity
            FROM invoice_items ii
            WHERE ii.invoice_id IN ($placeholders) ORDER BY ii.id ASC
        ");
        $stmt_items->execute($invoice_db_ids);
        $items_raw = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

        $items_by_invoice_id = [];
        foreach ($items_raw as $item_row) {
            $items_by_invoice_id[$item_row['invoice_id']][] = [
                $item_row['description'],
                (float)$item_row['unit_price'],
                (int)$item_row['quantity']
            ];
        }

        foreach ($invoices_processed as $external_id => &$invoice_data) {
            $db_id = $invoice_data['db_id'];
            if (isset($items_by_invoice_id[$db_id]) && !empty($items_by_invoice_id[$db_id])) {
                $invoice_data['items'] = $items_by_invoice_id[$db_id];
                $invoice_data['servicio'] = $invoice_data['items'][0][0];
            } else {
                $invoice_data['servicio'] = 'SIN SERVICIOS DETALLADOS';
            }
        }
        unset($invoice_data);
    }

    $response_data = ['success' => true, 'data' => array_values($invoices_processed)];

} catch (PDOException $e) {
    error_log("Error PDO en invoice-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("General Error en invoice-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO: ' . strtoupper($e->getMessage());
}

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