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

$invoice_id = intval($_GET['invoice_id'] ?? 0);
if(!$invoice_id) die("<div class='alert alert-danger'>Invalid invoice ID</div>");

// Fetch invoice
$invoice = $conn->query("SELECT * FROM invoices WHERE id=$invoice_id")->fetch_assoc();
if(!$invoice) die("<div class='alert alert-danger'>Invoice not found</div>");

// Check if bulk invoice
if($invoice['stay_id'] == 0){
    // Extract stay IDs from description
    preg_match('/stays:\s*(.+)/', $invoice['description'], $matches);
    $stay_ids = isset($matches[1]) ? explode(",", $matches[1]) : [];
    if(empty($stay_ids)) die("<div class='alert alert-danger'>No stays found for this invoice</div>");

    $ids_str = implode(",", array_map('intval', $stay_ids));

    // Fetch all stays
    $result = $conn->query("
        SELECT s.*, g.name AS guest_name, g.id AS guest_id, r.room_number, r.room_type, r.price AS room_price
        FROM stays s
        JOIN guests g ON s.guest_id=g.id
        JOIN rooms r ON s.room_id=r.id
        WHERE s.id IN ($ids_str)
        ORDER BY s.id ASC
    ");

    $rows = [];
    $guest_names = [];
    $total_room = 0;
    $total_services = 0;
    $total_paid = 0;

    while($stay = $result->fetch_assoc()){
        $guest_names[] = $stay['guest_name'];

        $room_cost = $stay['room_price'] * $stay['days'];

        // Fetch services
        $charges_result = $conn->query("SELECT * FROM charges WHERE guest_id={$stay['guest_id']} ORDER BY created_at ASC");
        $service_rows = [];
        $service_total = 0;
        while($c = $charges_result->fetch_assoc()){
            $service_rows[] = $c;
            $service_total += $c['amount'];
        }

        // Fetch payments
        $paid = $conn->query("
            SELECT COALESCE(SUM(amount),0) AS total
            FROM payments
            WHERE guest_id={$stay['guest_id']} AND status='Paid'
        ")->fetch_assoc()['total'] ?? 0;

        $total_room += $room_cost;
        $total_services += $service_total;
        $total_paid += $paid;

        $rows[] = [
            'guest_name' => $stay['guest_name'],
            'room_number' => $stay['room_number'],
            'room_type' => $stay['room_type'],
            'days' => $stay['days'],
            'checkin' => $stay['checkin_date'],
            'checkout' => date('Y-m-d', strtotime("+{$stay['days']} days", strtotime($stay['checkin_date']))),
            'room_cost' => $room_cost,
            'services' => $service_rows,
            'service_total' => $service_total,
            'paid' => $paid
        ];
    }

    // Totals
 /* ================= TOTALS ================= */
$subtotal = $total_room + $total_services;

$vat_rate = 0.175;
$tourism_rate = 0.01;

// Show VAT & Tourism Levy for info only, do NOT add to total
$vat_due = $subtotal * $vat_rate;
$tourism_levy = $subtotal * $tourism_rate;

// Total bill is just the subtotal (already includes taxes)
$total_bill = $subtotal;  

$balance = $total_bill - $total_paid;

    $display_guest_name = implode(", ", $guest_names);

} else {
    // Single stay invoice fallback
    $stay = $conn->query("
        SELECT s.*, g.name AS guest_name, r.room_number, r.room_type, r.price AS room_price
        FROM stays s
        JOIN guests g ON s.guest_id=g.id
        JOIN rooms r ON s.room_id=r.id
        WHERE s.id={$invoice['stay_id']}
    ")->fetch_assoc();
    $rows = [$stay];
    $display_guest_name = $stay['guest_name'];
    $total_bill = $invoice['total_amount'];
    $balance = ($invoice['status'] === 'Paid') ? 0 : $total_bill;
    $vat_due = $total_bill * 0.175;
    $tourism_levy = $total_bill * 0.01;
}

// QR & Logo
$qr_data = urlencode("Invoice: ".$invoice['invoice_number']." Guests: ".$display_guest_name." Total: MWK ".$total_bill);
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=".$qr_data;
$logo = "assets/logo.png";
?>

<style>
.invoice-box{
    background:#fff;
    padding:25px;
    border-radius:12px;
    font-size:14px;
    border:4px solid #0a7f2e;
    position:relative;
    page-break-inside: avoid;
    break-inside: avoid;
}
.cert-header{text-align:center;}
.cert-title{font-size:26px;font-weight:bold;color:#0a7f2e;}
.header-info{display:flex;justify-content:space-between;margin-top:10px;flex-wrap:wrap;}
.cert-table td{padding:8px;border-bottom:1px dotted #999;}
.table td, .table th{padding:6px;font-size:13px;}
.watermark{
    position:absolute;
    top:40%;
    left:20%;
    font-size:90px;
    color:rgba(0,128,0,0.08);
    transform:rotate(-30deg);
    font-weight:bold;
}
@media print{
    body{zoom:0.85;}
    .no-print{display:none;}
    .invoice-box{padding:20px;border-width:3px;}
    .cert-title{font-size:22px;}
}
</style>

<div class="container mt-4 invoice-box">

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

<div class="cert-header">
<img src="<?= $logo ?>" style="height:90px;">
<div class="header-info">
<div>
  <strong>Mponela Trading Centre.<br/>
100 Meters from Mount Meru Filling Station<br/>
Along M1 Road Next to St Peters Secondary School</strong><br/>
<strong>TPIN:30798071</strong>
</div>
<div>
<strong>
0993 899 382<br>
0883 899 382<br/>
https://ramslodgemw.com<br/>
ramslodge@gmail.com
</strong>
</div>
</div>
<div class="cert-title">BULK INVOICE</div>
</div>

<table class="cert-table">
<tr><td><b>Guests</b></td><td>: <?= $display_guest_name ?></td></tr>
<tr><td><b>Invoice #</b></td><td>: <?= htmlspecialchars($invoice['invoice_number']) ?></td></tr>
<tr><td><b>Total</b></td><td>: <b><?= number_format($total_bill,2) ?></b></td></tr>
</table>


<h5 class="mt-3">Charge Breakdown</h5>
<table class="table table-bordered">
<tr><th>Guest</th><th>Description</th><th>Amount (MWK)</th></tr>

<?php foreach($rows as $r): ?>
<tr>
<td rowspan="<?= count($r['services']) + 1 ?>"><?= $r['guest_name'] ?></td>
<td>Room <?= $r['room_number'] ?> (<?= $r['room_type'] ?>)</td>
<td><?= number_format($r['room_cost'],2) ?></td>
</tr>
<?php foreach($r['services'] as $srv): ?>
<tr>
<td><?= htmlspecialchars($srv['name']) ?></td>
<td><?= number_format($srv['amount'],2) ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>

<!-- VAT and Tourism Levy displayed BEFORE Total -->
<tr><td colspan="2">VAT (17.5%)</td><td><?= number_format($vat_due,2) ?></td></tr>
<tr><td colspan="2">Tourism Levy (1%)</td><td><?= number_format($tourism_levy,2) ?></td></tr>
<tr><td colspan="2"><b>Total Amount</b></td><td><b><?= number_format($total_bill,2) ?></b></td></tr>
</table>

<div class="row mt-3">
<div class="col-md-6">
<strong>OUR BANKING DETAILS</strong><br>
ACCOUNT NAME: RAMS EXECUTIVE LODGE<br>
ACCOUNT NUMBER: 9100007723188<br>
BANK NAME: STANDARD BANK<br>
</div>
<div class="col-md-6 text-end">
<img src="<?= $qr_url ?>" style="height:120px;">
</div>
</div>

<div class="text-center mt-3 no-print">
<button onclick="window.print()" class="btn btn-dark">Print</button>
<button class="btn btn-secondary" onclick="window.location.href='combined_invoices.php'">
    <i class="fa fa-arrow-left"></i> Back
</button>
</div>