<?php
// invoice_view.php
session_start();
require_once '../../config.php';

// 1. Validar parámetros
if (!isset($_GET['invoice_id'])) {
    die("❌ ID de factura no proporcionado.");
}
$invoice_id = intval($_GET['invoice_id']);

// 2. Consultar la factura con usuario y ticket (si aplica)
$sql = "SELECT i.*, u.firstname, u.lastname, t.name AS ticketname, t.expire_days, t.occasions
        FROM invoices i
        INNER JOIN users u ON i.userid = u.userid
        LEFT JOIN tickets t ON i.ticket_id = t.id
        WHERE i.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("❌ Factura no encontrada.");
}
$invoice = $result->fetch_assoc();
$stmt->close();

// 3. Si no es un ticket (es compra de productos), obtener items
$items = [];
if (empty($invoice['ticket_id'])) {
    $sql_items = "SELECT ii.quantity, ii.price, p.name 
                  FROM invoice_items ii
                  INNER JOIN products p ON ii.product_id = p.id
                  WHERE ii.invoice_id = ?";
    $stmt_items = $conn->prepare($sql_items);
    $stmt_items->bind_param("i", $invoice_id);
    $stmt_items->execute();
    $items = $stmt_items->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_items->close();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Factura #<?php echo htmlspecialchars($invoice['id']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container my-5">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0">Factura #<?php echo htmlspecialchars($invoice['id']); ?></h4>
        </div>
        <div class="card-body">
            <p><strong>Cliente:</strong> <?php echo htmlspecialchars($invoice['firstname'] . " " . $invoice['lastname']); ?></p>
            <p><strong>Fecha:</strong> <?php echo htmlspecialchars($invoice['created_at']); ?></p>
            <p><strong>Estado:</strong> <?php echo ucfirst(htmlspecialchars($invoice['status'])); ?></p>
            <p><strong>Método de Pago:</strong> <?php echo htmlspecialchars($invoice['route']); ?></p>

            <?php if (!empty($invoice['ticket_id'])): ?>
                <!-- 📌 Factura de Plan/Ticket -->
                <h5 class="mt-4">Detalle del Plan</h5>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Plan</th>
                            <th>Días de Expiración</th>
                            <th>Oportunidades</th>
                            <th>Precio</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><?php echo htmlspecialchars($invoice['ticketname']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['expire_days']); ?></td>
                            <td><?php echo ($invoice['occasions'] === null ? "Ilimitado" : htmlspecialchars($invoice['occasions'])); ?></td>
                            <td><?php echo htmlspecialchars($invoice['price']); ?> <?php echo htmlspecialchars($currency); ?></td>
                        </tr>
                    </tbody>
                </table>
            
            <?php else: ?>
                <!-- 📌 Factura de Productos -->
                <h5 class="mt-4">Detalle de Productos</h5>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Cantidad</th>
                            <th>Precio Unitario</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $grandTotal = 0;
                        foreach ($items as $item): 
                            $lineTotal = $item['quantity'] * $item['price'];
                            $grandTotal += $lineTotal;
                        ?>
                            <tr>
                                <td><?php echo htmlspecialchars($item['name']); ?></td>
                                <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                                <td><?php echo htmlspecialchars($item['price']); ?> <?php echo htmlspecialchars($currency); ?></td>
                                <td><?php echo number_format($lineTotal, 2); ?> <?php echo htmlspecialchars($currency); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <tr class="fw-bold">
                            <td colspan="3" class="text-end">TOTAL</td>
                            <td><?php echo number_format($grandTotal, 2); ?> <?php echo htmlspecialchars($currency); ?></td>
                        </tr>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
