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

if(empty($_POST['stay_ids'])){
    die("<div class='alert alert-danger'>No records selected</div>");
}

$stay_ids = array_map('intval', $_POST['stay_ids']);
$ids = implode(",", $stay_ids);

/* ================= FETCH ================= */
$result = $conn->query("
    SELECT s.*, g.name AS guest_name, g.id as guest_id, g.phone,
           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)
");

$rows = [];
$total_room = 0;
$total_services = 0;
$total_paid = 0;
$guest_id = 0;
$guest_name = "";

/* ================= LOOP ================= */
while($row = $result->fetch_assoc()){

    $guest_id = $row['guest_id'];
    $guest_name = $row['guest_name'];

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

    $charges = $conn->query("SELECT * FROM charges WHERE guest_id={$row['guest_id']}");
    $service_total = 0;
    $service_rows = [];

    while($c = $charges->fetch_assoc()){
        $service_total += $c['amount'];
        $service_rows[] = $c;
    }

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

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

    $rows[] = [
        'room_number' => $row['room_number'],
        'room_type' => $row['room_type'],
        'checkin' => $row['checkin_date'],
        'checkout' => $row['checkout_date'],
        'room_cost' => $room_cost,
        'services' => $service_rows,
        'service_total' => $service_total
    ];
}

/* ================= TOTAL ================= */
$subtotal = $total_room + $total_services;

$vat_rate = 0.175;
$tourism_rate = 0.01;

$vat_due = $subtotal * $vat_rate;
$tourism_levy = $subtotal * $tourism_rate;

$total_bill = $subtotal;
$balance = $total_bill - $total_paid;

/* ================= GENERATE INVOICE ================= */
$last_inv = $conn->query("SELECT invoice_number FROM invoices ORDER BY id DESC LIMIT 1")->fetch_assoc();
$num = $last_inv ? intval(preg_replace('/[^0-9]/','',$last_inv['invoice_number'])) + 1 : 1001;
$invoice_number = "INV-BLK-".$num;

$status = ($total_paid <= 0) ? 'Unpaid' : (($total_paid < $total_bill) ? 'Partially Paid' : 'Paid');

$desc = "Bulk invoice for stays: ".$ids;

$stmt = $conn->prepare("
    INSERT INTO invoices (invoice_number, guest_id, stay_id, total_amount, status, description)
    VALUES (?,?,?,?,?,?)
");

$zero_stay = 0;
$stmt->bind_param("siidss", $invoice_number, $guest_id, $zero_stay, $total_bill, $status, $desc);
$stmt->execute();

/* ================= QR ================= */
$qr_data = urlencode("Invoice: ".$invoice_number." Guest: ".$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">INVOICE</div>
</div>

<table class="cert-table">
<tr><td><b>Name</b></td><td>: <?= $guest_name ?></td></tr>
<tr><td><b>Invoice #</b></td><td>: <?= $invoice_number ?></td></tr>
<tr><td><b>Total</b></td><td>: <?= number_format($total_bill,2) ?></td></tr>
</table>

<h5 class="mt-3">Charge Breakdown</h5>

<table class="table table-bordered">
<tr><th>Description</th><th>Amount (MWK)</th></tr>

<?php foreach($rows as $r): ?>
<tr>
<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><?= $srv['name'] ?></td>
<td><?= number_format($srv['amount'],2) ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>

<tr><td>VAT (17.5%)</td><td><?= number_format($vat_due,2) ?></td></tr>
<tr><td>Tourism Levy (1%)</td><td><?= number_format($tourism_levy,2) ?></td></tr>
<tr><td><b>Total</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="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
</div>

</div>