<?php
include 'includes/auth.php';
include 'db.php';

// ===============================
// GET INVOICE ID (SAFE)
// ===============================
$invoice_id = isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0;
if ($invoice_id <= 0) die("Invalid Invoice ID");

// ===============================
// FETCH INVOICE AND BOOKING
// ===============================
$invoice = $conn->query("
    SELECT i.*, g.name AS guest_name, cb.client_name,g.phone, cb.id AS booking_id, cb.booking_date, cb.attendees, cb.room_price
    FROM invoices i
    LEFT JOIN conference_bookings cb ON i.stay_id = cb.id
    LEFT JOIN guests g ON i.guest_id = g.id
    WHERE i.id=$invoice_id
")->fetch_assoc();

if (!$invoice) die("Invoice not found");

// ===============================
// FETCH PAYMENTS
// ===============================
$payments = $conn->query("
    SELECT * FROM payments 
    WHERE guest_id=".$invoice['guest_id']." AND type='Conference' 
    ORDER BY payment_date ASC
");

// Calculate totals
$total_paid = 0;
$total_discount = 0;
$payment_rows = [];
while($p = $payments->fetch_assoc()){
    $payment_rows[] = $p;
    $total_paid += floatval($p['amount']);
    $total_discount += floatval($p['discount'] ?? 0);
}

$balance = floatval($invoice['total_amount']) - $total_paid - $total_discount;

// ================= TAX (INCLUSIVE) =================
$total_incl = floatval($invoice['total_amount']); // already inclusive

$total_tax_rate = 0.175 + 0.01; // 18.5%

$taxable_base = $total_incl / (1 + $total_tax_rate);

$vat = $taxable_base * 0.175;
$tourism = $taxable_base * 0.01;

// ===============================
// LOGO & QR CODE
// ===============================
$logo = "assets/logo.png";
$qr_data = urlencode("Invoice: ".$invoice['invoice_number']." Guest: ".$invoice['guest_name']);
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=".$qr_data;
?>

<!DOCTYPE html>
<html>
<head>
    <title>Conference Receipt - <?= htmlspecialchars($invoice['invoice_number']) ?></title>
    <style>
        body { font-family: monospace; font-size: 12px; width: 80mm; margin: 0 auto; }
        .receipt { border: 1px dashed #000; padding: 5px; position: relative; }
        h2, h4 { text-align: center; margin: 5px 0; }
        .line { border-top: 1px dashed #000; margin: 5px 0; }
        .total { font-weight: bold; }
        .watermark { position:absolute; top:40%; left:10%; font-size:50px; color: rgba(0,128,0,0.15); transform: rotate(-30deg); pointer-events:none; z-index:0; }
        table { width: 100%; border-collapse: collapse; }
        td { padding: 2px 0; }
        td.right { text-align: right; }
        .logo { width: 60px; display:block; margin: 0 auto; }
        @media print { button { display: none; } }
    </style>
</head>
<body onload="window.print()">

<div class="receipt">
    <?php if($balance <= 0): ?>
        <div class="watermark">PAID</div>
    <?php endif; ?>

    <img src="<?= $logo ?>" class="logo">
    <h2>🏨 Conference Receipt</h2>
    <h4><?= $invoice['client_name'] ?></h4>

    <p>
        Invoice #: <?= htmlspecialchars($invoice['invoice_number']) ?><br>
        Booking Date: <?= isset($invoice['booking_date']) ? date('d/m/Y', strtotime($invoice['booking_date'])) : '-' ?><br>
        Printed: <?= date('d/m/Y H:i') ?><br>
        Phone: <?= htmlspecialchars($invoice['phone'] ?? '-') ?>
    </p>

    <div class="line"></div>

    <!-- PAYMENTS -->
    <table>
        <thead>
            <tr>
                <th>Payment Method</th>
                <th class="right">Amount (MWK)</th>
                <th class="right">Discount (MWK)</th>
            </tr>
        </thead>
        <tbody>
            <?php if(count($payment_rows) > 0): 
                foreach($payment_rows as $p): ?>
                <tr>
                    <td><?= htmlspecialchars($p['method']) ?></td>
                    <td class="right"><?= number_format($p['amount'],2) ?></td>
                    <td class="right"><?= number_format($p['discount'] ?? 0,2) ?></td>
                </tr>
            <?php endforeach; else: ?>
                <tr><td colspan="3" class="right">No payments recorded yet.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>

    <div class="line"></div>

    <table>
        <tr>
            <td>Total (Incl)</td>
            <td class="right"><?= number_format($total_incl,2) ?> MWK</td>
        </tr>
        <tr>
            <td>VAT (17.5%)</td>
            <td class="right"><?= number_format($vat,2) ?> MWK</td>
        </tr>
        <tr>
            <td>Tourism Levy (1%)</td>
            <td class="right"><?= number_format($tourism,2) ?> MWK</td>
        </tr>
        <tr>
            <td>Total Discount</td>
            <td class="right"><?= number_format($total_discount,2) ?> MWK</td>
        </tr>
        <tr>
            <td><strong>Total Paid</strong></td>
            <td class="right"><?= number_format($total_paid,2) ?> MWK</td>
        </tr>
        <tr>
            <td><strong>Balance</strong></td>
            <td class="right"><?= number_format($balance,2) ?> MWK</td>
        </tr>
        <tr>
            <td><strong>Status</strong></td>
            <td class="right"><?= $balance<=0?'PAID':$invoice['status'] ?></td>
        </tr>
    </table>

    <p style="text-align:center;">* Prices are Tax Inclusive *</p>
    <p style="text-align:center;">Thank you for choosing our conference services!</p>

    <div class="line"></div>

    <div style="text-align:center;">
        <img src="<?= $qr_url ?>">
        <p>Scan QR to verify</p>
    </div>

    <button onclick="window.print()">🖨 Print Receipt</button>
</div>

</body>
</html>