<?php
session_start();

// 1. VERIFICACIÓN DE SESIÓN
if (!isset($_SESSION['userid'])) {
    // Redirige al login si el usuario no está autenticado.
    header("Location: ../../login/");
    exit();
}


// 2. INCLUIR CONFIGURACIÓN Y ESTABLECER VARIABLES DE PÁGINA
require_once '../../config.php';
use Dompdf\Dompdf;
use Dompdf\Options;

$invoice_id = intval($_GET['id']);

// 🔹 Consulta factura, usuario y ticket
$sql = "SELECT i.id, i.name AS plan_name, i.price, i.status, i.created_at,
               u.firstname, u.lastname, u.email, u.userid, u.city, u.street, u.house_number,
               t.name AS ticket_name, t.expire_days, t.occasions
        FROM invoices i
        INNER JOIN users u ON i.userid = u.userid
        INNER 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();

// 🔹 Opciones Dompdf
$options = new Options();
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);

// 🔹 HTML del PDF con estilo
$html = '
<html>
<head>
    <style>
        body { font-family: DejaVu Sans, sans-serif; font-size: 12px; color: #333; }
        .header { background: #003366; color: #fff; padding: 20px; text-align: center; }
        .header img { max-height: 60px; margin-bottom: 10px; }
        .header h1 { margin: 0; font-size: 22px; }
        .invoice-info { margin: 20px 0; }
        .invoice-info table { width: 100%; }
        .invoice-info td { padding: 5px; }
        .customer, .company { width: 48%; vertical-align: top; }
        .invoice-title { background: #f4f4f4; padding: 10px; font-weight: bold; margin-bottom: 5px; }
        table.details { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table.details th, table.details td { border: 1px solid #ccc; padding: 8px; text-align: center; }
        table.details th { background: #003366; color: #fff; }
        .total { text-align: right; margin-top: 15px; font-size: 14px; font-weight: bold; }
        .footer { position: fixed; bottom: 20px; left: 0; right: 0; text-align: center; font-size: 11px; color: #666; }
        .signature { margin-top: 50px; text-align: right; font-size: 12px; }
    </style>
</head>
<body>
    <div class="header">
        <img src="../../assets/logo.png" alt="Logo Empresa">
        <h1>FACTURA</h1>
        <p>No. '.$invoice['id'].' | Fecha: '.date("d/m/Y", strtotime($invoice['created_at'])).'</p>
    </div>

    <div class="invoice-info">
        <table>
            <tr>
                <td class="customer">
                    <div class="invoice-title">Cliente</div>
                    <strong>'.$invoice['firstname'].' '.$invoice['lastname'].'</strong><br>
                    Email: '.$invoice['email'].'<br>
                    Dirección: '.$invoice['street'].' '.$invoice['house_number'].', '.$invoice['city'].'<br>
                    ID Usuario: '.$invoice['userid'].'
                </td>
                <td class="company">
                    <div class="invoice-title">Empresa</div>
                    <strong>Gimnasio XYZ</strong><br>
                    NIT: 123.456.789-0<br>
                    Dirección: Calle 123 #45-67, Bogotá<br>
                    Tel: (601) 555 1234<br>
                    Email: info@gimnasioxyz.com
                </td>
            </tr>
        </table>
    </div>

    <table class="details">
        <thead>
            <tr>
                <th>Descripción</th>
                <th>Duración (días)</th>
                <th>Oportunidades</th>
                <th>Estado</th>
                <th>Valor</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>'.$invoice['ticket_name'].'</td>
                <td>'.$invoice['expire_days'].'</td>
                <td>'.$invoice['occasions'].'</td>
                <td>'.ucfirst($invoice['status']).'</td>
                <td>$'.number_format($invoice['price'], 2, ',', '.').'</td>
            </tr>
        </tbody>
    </table>

    <div class="total">
        Total a pagar: $'.number_format($invoice['price'], 2, ',', '.').'
    </div>

    <div class="signature">
        ___________________________<br>
        Firma Autorizada
    </div>

    <div class="footer">
        Factura generada automáticamente - Gimnasio XYZ © '.date("Y").'
    </div>
</body>
</html>
';

// 🔹 Generar PDF
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("factura_".$invoice['id'].".pdf", ["Attachment" => true]);
