<?php
// invoice_download.php
session_start();

if (!isset($_SESSION['userid'])) {
    header("Location: ../../login/");
    exit();
}
// 2. INCLUIR CONFIGURACIÓN Y ESTABLECER VARIABLES DE PÁGINA
require_once '../../config.php'; // tu conexión mysqli

// Dompdf
require_once("../../vendor/autoload.php");
use Dompdf\Dompdf;
use Dompdf\Options;

// Validar parámetro
if (!isset($_GET['invoice_id'])) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'ID de factura no proporcionado.'];
    header("Location: index.php");
    exit();
}

$invoice_id = intval($_GET['invoice_id']);
// --- util: moneda ---
$currencySymbol = isset($currency) ? $currency : '$';
$fmt = fn($n) => number_format((float)$n, 2) . " " . $currencySymbol;

// 1) Factura
$sql = "SELECT * FROM invoices WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$invoice) {
    die("Factura no encontrada.");
}

// 2) Cliente
$customerName = "Usuario #".$invoice['userid'];
$sql = "SELECT firstname, lastname FROM users WHERE userid = ? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice['userid']);
$stmt->execute();
$userRow = $stmt->get_result()->fetch_assoc();
$stmt->close();
if ($userRow) {
    $customerName = trim(($userRow['firstname'] ?? '') . ' ' . ($userRow['lastname'] ?? ''));
    if ($customerName === '') {
        $customerName = "Usuario #".$invoice['userid'];
    }
}

// 3) Base HTML
$html = '
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: DejaVu Sans, sans-serif; font-size: 12px; color: #111; }
    .header { background: #0d6efd; color: #fff; padding: 14px 16px; font-size: 22px; font-weight: 700; }
    .block { margin: 16px 0; }
    .muted { color: #444; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #000; padding: 8px; }
    th { background: #f2f2f2; text-align: left; }
    .right { text-align: right; }
    .center { text-align: center; }
    .total-row td { font-weight: bold; }
    .meta p { margin: 4px 0; }
    .label { font-weight: 700; }
  </style>
</head>
<body>
  <div class="header">Factura #'.$invoice['id'].'</div>

  <div class="meta block">
    <p><span class="label">Cliente:</span> '.htmlspecialchars($customerName).'</p>
    <p><span class="label">Fecha:</span> '.htmlspecialchars($invoice['created_at']).'</p>
    <p><span class="label">Estado:</span> '.htmlspecialchars($invoice['status']).'</p>
    <p><span class="label">Método de Pago:</span> '.htmlspecialchars($invoice['route'] ?? '—').'</p>
  </div>
';

// 4) Plan vs Productos
if (!is_null($invoice['ticket_id'])) {
    // -------- PLAN ----------
    $sql = "SELECT name, expire_days, occasions, price FROM tickets WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $invoice['ticket_id']);
    $stmt->execute();
    $ticket = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $planName   = $ticket ? $ticket['name'] : ($invoice['name'] ?? 'Plan');
    $planDays   = $ticket ? (int)$ticket['expire_days'] : 0;
    $planOcc    = $ticket ? (int)$ticket['occasions'] : 0;
    $planPrice  = $ticket ? (float)$ticket['price'] : (float)$invoice['price'];

    $html .= '
      <div class="block">
        <h3>Detalle del Plan</h3>
        <table>
          <tr><th>Plan</th><td>'.htmlspecialchars($planName).'</td></tr>
          <tr><th>Vigencia</th><td>'.$planDays.' días</td></tr>
          <tr><th>Ocasiones</th><td>'.$planOcc.'</td></tr>
          <tr><th>Precio</th><td class="right">'.$fmt($planPrice).'</td></tr>
        </table>
      </div>
    ';

} else {
    // -------- PRODUCTOS ----------
    $sql = "SELECT ii.quantity, ii.price, p.name
            FROM invoice_items ii
            INNER JOIN products p ON p.id = ii.product_id
            WHERE ii.invoice_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $itemsRes = $stmt->get_result();
    $stmt->close();

    $html .= '
      <div class="block">
        <h3>Detalle de Productos</h3>
        <table>
          <tr>
            <th>Producto</th>
            <th class="center">Cantidad</th>
            <th class="right">Precio Unitario</th>
            <th class="right">Total</th>
          </tr>
    ';

    $grand = 0.0;
    while ($row = $itemsRes->fetch_assoc()) {
        $qty      = (int)$row['quantity'];
        $unit     = (float)$row['price'];
        $subtotal = $qty * $unit;
        $grand   += $subtotal;

        $html .= '
          <tr>
            <td>'.htmlspecialchars($row['name']).'</td>
            <td class="center">'.$qty.'</td>
            <td class="right">'.$fmt($unit).'</td>
            <td class="right">'.$fmt($subtotal).'</td>
          </tr>
        ';
    }

    // Por si la suma difiere del precio guardado en invoices, se muestra el acumulado calculado.
    $html .= '
          <tr class="total-row">
            <td colspan="3" class="right">TOTAL</td>
            <td class="right">'.$fmt($grand).'</td>
          </tr>
        </table>
      </div>
    ';
}

$html .= '
</body>
</html>';

// 5) Render PDF
$options = new Options();
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);

$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("Factura_".$invoice_id.".pdf", ["Attachment" => false]);
exit;