<?php
// db/invoice-read.php
header('Content-Type: application/json');
include_once 'db_connection.php'; // Asegúrate de que esta ruta sea correcta

$response = ['success' => false, 'message' => '', 'data' => []];

try {
    // 1. Obtener todas las facturas principales, uniendo tanto a clientes como a leads
    $stmt = $pdo->query("
        SELECT
            i.id AS db_id,
            i.external_id AS id,
            i.invoice_date AS fechaSolicitud,
            i.total_amount AS montoFacturado,
            i.status AS estado,
            i.tax_rate AS taxRate,
            i.client_id,
            i.lead_id,
            -- Seleccionar datos del cliente si existe, de lo contrario, del lead
            COALESCE(c.first_name, l.first_name) AS first_name,
            COALESCE(c.last_name, l.last_name) AS last_name,
            COALESCE(c.email, l.email) AS contact_email,
            COALESCE(c.phone, l.phone) AS contact_phone,
            COALESCE(c.street_address, l.street_address) AS contact_address,
            -- Determinar el tipo de contacto para el frontend
            CASE
                WHEN i.client_id IS NOT NULL THEN 'client'
                WHEN i.lead_id IS NOT NULL THEN 'prospect'
                ELSE 'unknown'
            END AS contactType
        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.id DESC
    ");
    $invoices_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_invoices = [];
    foreach ($invoices_data as $invoice) {
        $external_id = $invoice['id']; // El external_id es la clave principal en el frontend

        // Formatear el nombre completo del cliente/prospecto
        $invoice['cliente'] = trim($invoice['first_name'] . ' ' . $invoice['last_name']);
        unset($invoice['first_name'], $invoice['last_name']); // Eliminar campos individuales

        // Obtener los ítems para cada factura
        $stmt_items = $pdo->prepare("
            SELECT description, unit_price, quantity
            FROM invoice_items
            WHERE invoice_id = ?
            ORDER BY id ASC
        ");
        $stmt_items->execute([$invoice['db_id']]);
        $items = $stmt_items->fetchAll(PDO::FETCH_NUM); // Obtener como array numérico [desc, price, qty]

        $invoice['items'] = $items;

        // Determinar el "servicio" principal para la vista de lista
        if (!empty($items)) {
            $invoice['servicio'] = $items[0][0]; // Descripción del primer ítem
        } else {
            $invoice['servicio'] = 'Sin servicios';
        }

        // Estructurar el objeto de contacto para el frontend
        // Usar client_id o lead_id según cuál sea el asociado (el que no es NULL)
        $associated_id = $invoice['client_id'] ?? $invoice['lead_id'];
        
        $invoice['contact'] = [
            'id' => $associated_id,
            'name' => $invoice['cliente'],
            'email' => $invoice['contact_email'],
            'phone' => $invoice['contact_phone'],
            'address' => $invoice['contact_address'],
            'type' => $invoice['contactType']
        ];
        // Eliminar campos duplicados que ahora están en 'contact' o se usan para cálculo
        unset($invoice['client_id'], $invoice['lead_id'], $invoice['contact_email'], $invoice['contact_phone'], $invoice['contact_address'], $invoice['contactType']);


        $formatted_invoices[$external_id] = $invoice;
    }

    $response['success'] = true;
    $response['data'] = array_values($formatted_invoices); // Devolver como un array indexado numéricamente

} catch (PDOException $e) {
    error_log("Error PDO al leer facturas: " . $e->getMessage());
    $response['message'] = "Error de base de datos al cargar las facturas.";
} catch (Exception $e) {
    error_log("Error general al leer facturas: " . $e->getMessage());
    $response['message'] = "Error inesperado al cargar las facturas.";
}

echo json_encode($response);
exit;
?>