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

$invoice_id = intval($_GET['invoice_id'] ?? 0);
if(!$invoice_id){
    echo "<div class='alert alert-danger'>Invalid Invoice</div>";
    exit;
}

// ================= FETCH INVOICE =================
$invoice = $conn->query("
    SELECT i.*, g.name AS guest_name, g.phone, cb.booking_date
    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){
    echo "<div class='alert alert-danger'>Invoice not found</div>";
    exit;
}

// ================= PAYMENTS =================
$payments = $conn->query("SELECT * FROM payments WHERE guest_id=".$invoice['guest_id']." AND type='Conference' ORDER BY payment_date ASC");
$total_paid = 0;
$payment_rows = [];
while($p = $payments->fetch_assoc()){
    $payment_rows[] = $p;
    $total_paid += $p['amount'];
}

$balance = $invoice['total_amount'] - $total_paid;

// ================= LOGO & QR =================
$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;
?>

<style>
.invoice-box{
    background:#fff;
    padding:25px;
    border-radius:10px;
    font-size:14px;
    position:relative;
}
.header-flex{
    display:flex;
    justify-content:space-between;
    align-items:center;
}
.watermark{
    position:absolute;
    top:40%;
    left:25%;
    font-size:80px;
    color:rgba(0,128,0,0.15);
    transform:rotate(-30deg);
    pointer-events:none;
}
.table td, .table th { vertical-align: middle; }
@media print{
    .no-print{display:none;}
}
</style>

<div class="container mt-3 invoice-box">
<?php if($balance <= 0): ?>
<div class="watermark">PAID</div>
<?php endif; ?>

<!-- HEADER -->
<div class="header-flex mb-3">
    <div><img src="<?= $logo ?>" style="height:80px;"></div>
    <div class="text-center">
        <h3 style="margin:0;">INVOICE</h3>
        <strong><?= htmlspecialchars($invoice['conference_name'] ?? 'Conference Booking') ?></strong><br>
        Phone: <?= htmlspecialchars($invoice['phone'] ?? '-') ?><br>
           <strong>TPIN:30798071</strong>
    </div>
    <div class="text-end"><img src="<?= $qr_url ?>"></div>
</div>

<hr>

<!-- META INFO -->
<div class="row mb-3">
    <div class="col-md-6">
        <strong>Customer:</strong> <?= htmlspecialchars($invoice['guest_name']) ?><br>
        <strong>Invoice #:</strong> <?= htmlspecialchars($invoice['invoice_number']) ?><br>
        <strong>Function Date:</strong> <?= isset($invoice['booking_date']) ? date('d/m/Y', strtotime($invoice['booking_date'])) : '-' ?>
    </div>
    <div class="col-md-6 text-end">
        <strong>Date:</strong> <?= date('d/m/Y') ?><br>
        <strong>Status:</strong> <?= $invoice['status'] ?>
    </div>
</div>

<!-- PAYMENTS TABLE -->
<table class="table table-bordered">
    <thead class="table-dark">
        <tr>
            <th>#</th>
            <th>Amount (MWK)</th>
            <th>Method</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        <?php if(count($payment_rows) > 0):
            $count = 1;
            foreach($payment_rows as $p): ?>
            <tr>
                <td><?= $count++ ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
                <td><?= htmlspecialchars($p['method']) ?></td>
                <td><?= date('d/m/Y H:i', strtotime($p['payment_date'])) ?></td>
            </tr>
        <?php endforeach; else: ?>
            <tr><td colspan="4" class="text-center text-muted">No payments recorded yet.</td></tr>
        <?php endif; ?>
    </tbody>
</table>

<!-- TOTALS -->
<div class="row">
    <div class="col-md-6">
        <strong>Comments:</strong><br>
        Thank you for choosing our conference services.
    </div>
    <div class="col-md-6">
        <table class="table table-sm">
            <tr><th>Total Amount</th><td class="text-end"><?= number_format($invoice['total_amount'],2) ?></td></tr>
            <tr class="table-success"><th>Total Paid</th><td class="text-end"><?= number_format($total_paid,2) ?></td></tr>
            <tr class="<?= $balance>0?'table-danger':'table-primary' ?>"><th>Balance</th><td class="text-end"><?= number_format($balance,2) ?></td></tr>
        </table>
    </div>
</div>

<hr>

<div>
<strong>OUR BANKING DETAILS</strong><br>
ACCOUNT NAME: CONFERENCE CENTER<br>
ACCOUNT NUMBER: 1003010771<br>
BANK: NATIONAL BANK OF MALAWI<br>
Capital City Branch
</div>

<div class="no-print mt-3">
    <?php if($balance > 0): ?>
    <a href="receive_pay.php?guest_id=<?= $invoice['guest_id'] ?>" class="btn btn-success"><i class="fa fa-money-bill-wave"></i> Receive Payment</a>
    <?php endif; ?>
    <button class="btn btn-dark" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
    <button class="btn btn-secondary" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
</div>

</div>

<?php include 'includes/footer.php'; ?>
