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

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

/* ================= FETCH STAY ================= */
$stay = $conn->query("
     SELECT s.*, g.name AS guest_name, 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=$stay_id
")->fetch_assoc();

if(!$stay){
    echo "<div class='alert alert-danger'>Stay not found</div>";
    exit;
}

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

/* ================= SERVICE COSTS ================= */
$charges = $conn->query("
    SELECT * FROM charges 
    WHERE guest_id={$stay['guest_id']}
    ORDER BY created_at ASC
");

$service_total = 0;
$service_rows = [];

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

$subtotal = $room_cost + $service_total;

/* ================= TAX ================= */
/* ================= TAX ================= */
$vat_rate = 0.175;          // 16.5% VAT
$tourism_rate = 0.01;      // 0.5% Tourism Levy

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

$total_bill = $subtotal;

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

$balance = $total_bill - $paid;





/* ================= INVOICE ================= */
$inv_check = $conn->query("SELECT * FROM invoices WHERE stay_id=$stay_id")->fetch_assoc();

if(!$inv_check){
    $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-".$num;

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

    $stmt = $conn->prepare("
        INSERT INTO invoices
        (invoice_number, guest_id, stay_id, total_amount, status, description)
        VALUES (?,?,?,?,?,?)
    ");
    $desc = "Auto generated from stay #".$stay_id;
    $stmt->bind_param("siidss",$invoice_number,$stay['guest_id'],$stay_id,$total_bill,$status,$desc);
    $stmt->execute();
}else{
    $invoice_number = $inv_check['invoice_number'];
    $new_status = ($paid <= 0) ? 'Unpaid' : (($paid < $total_bill) ? 'Partially Paid' : 'Paid');
    $conn->query("UPDATE invoices SET total_amount='$total_bill', status='$new_status' WHERE id=".$inv_check['id']);
}

/* ================= DATES ================= */
$checkin = strtotime($stay['checkin_date']);
$checkout = strtotime("+{$stay['days']} days", $checkin);

/* ================= QR ================= */
$qr_data = urlencode("Invoice: ".$invoice_number." Guest: ".$stay['guest_name']." Total: MWK ".$total_bill);
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=".$qr_data;

/* ================= LOGO ================= */
$logo = "assets/logo.png";
?>

<style>
.invoice-box{
    background:#fff;
    padding:35px;
    border-radius:12px;
    font-size:15px;
    border:4px solid #0a7f2e;
    position:relative;

    /* AUTO FIT WIDTH */
    width:100%;
    max-width:1200px;
    margin:auto;

    box-sizing:border-box;
    overflow-x:auto;
}

.cert-header{
    text-align:center;
}

.cert-title{
    font-size:30px;
    font-weight:bold;
    color:#0a7f2e;
}

.header-info{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    margin-top:10px;
    flex-wrap:wrap;
}

.header-left{
    text-align:left;
    font-size:14px;
}

.header-right{
    text-align:right;
    font-size:14px;
}

.cert-sub{
    margin-top:10px;
}

.cert-table{
    width:100%;
    margin-top:30px;
}

.cert-table td{
    padding:10px;
    border-bottom:1px dotted #999;
}

.cert-label{
    font-weight:bold;
    width:300px;
}

.signature-area{
    margin-top:70px;
}

.watermark{
    position:absolute;
    top:45%;
    left:20%;
    font-size:100px;
    color:rgba(0,128,0,0.08);
    transform:rotate(-30deg);
    font-weight:bold;
}

@media print{
    .no-print{display:none;}
}

/* ===== FORCE SINGLE PAGE PRINT ===== */
@page {
    size: A4 portrait;
    margin: 8mm;
}

html, body {
    height: auto;
}

/* Prevent content breaking */
.invoice-box {
    page-break-inside: avoid;
    break-inside: avoid;
}

/* Smart auto-fit scaling */
@media print {

    body {
        zoom: 0.88; /* 🔥 auto shrink to fit one page */
    }

    .invoice-box{
        padding: 25px !important;
        border-width: 3px;
    }

    .cert-title{
        font-size: 24px !important;
    }

    .cert-table td{
        padding: 6px !important;
        font-size: 13px !important;
    }

    .table td, .table th{
        padding: 6px !important;
        font-size: 13px !important;
    }

    .signature-area{
        margin-top: 30px !important;
    }

    .watermark{
        font-size: 80px;
    }

    .no-print{
        display:none !important;
    }

}
</style>

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

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

<!-- HEADER -->
<!-- HEADER -->
<div class="cert-header">

    <img src="<?= $logo ?>" style="height:100px;">

    <!-- ADDRESS + PHONE ROW -->
    <div class="header-info mt-2">

        <div class="header-left">
            <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 class="header-right">
            <strong>
            0993 899 382<br>
            0883 899 382<br/>
            https://ramslodgemw.com<br/>
            ramslodge@gmail.com</strong>
        </div>

    </div>

    <br>

    <div class="cert-title">INVOICE</div>

  

</div>

<!-- DETAILS -->
<table class="cert-table">
    <tr>
        <td class="cert-label">Name of Guest</td>
        <td>: <?= htmlspecialchars($stay['guest_name']) ?></td>
    </tr>
    <tr>
        <td class="cert-label">Room Number</td>
        <td>: <?= $stay['room_number'] ?> (<?= $stay['room_type'] ?>)</td>
    </tr>
    <tr>
        <td class="cert-label">Invoice Number</td>
        <td>: <?= htmlspecialchars($invoice_number) ?></td>
    </tr>
    <tr>
        <td class="cert-label">Tax Identification No</td>
        <td>: 30798071</td>
    </tr>
    <tr>
        <td class="cert-label">Stay Period</td>
        <td>: <?= date('d/m/Y',$checkin) ?> - <?= date('d/m/Y',$checkout) ?></td>
    </tr>
    <tr>
        <td class="cert-label">Total Amount (MWK)</td>
        <td>: <strong><?= number_format($total_bill,2) ?></strong></td>
    </tr>
  
</table>

<!-- BREAKDOWN -->
<!-- BREAKDOWN -->
<h5 class="mt-4">Charge Breakdown</h5>
<table class="table table-bordered">
    <thead class="table-dark">
        <tr>
            <th>Description</th>
            <th>Amount (MWK)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Room Accommodation</td>
            <td><?= number_format($room_cost,2) ?></td>
        </tr>
        <?php foreach($service_rows as $sr): ?>
        <tr>
            <td><?= htmlspecialchars($sr['name']) ?></td>
            <td><?= number_format($sr['amount'],2) ?></td>
        </tr>
        <?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><strong>Total Amount (MWK)</strong></td>
            <td><strong><?= number_format($total_bill,2) ?></strong></td>
        </tr>
    </tbody>
</table>

<!-- SIGNATURE + QR -->
<div class="row signature-area">
    <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 ?>"><br>
        <small>Verify by scanning this QR code.</small>
    </div>
</div>

<hr>



<!-- BUTTONS -->
<div class="no-print mt-4 text-center">
    <button class="btn btn-dark" onclick="window.print()">
        <i class="fa fa-print"></i> Print
    </button>

    <a href="receive_payment.php?guest_id=<?= $stay['guest_id'] ?>" class="btn btn-success">
        <i class="fa fa-money-bill-wave"></i> Receive Payment
    </a>

     <a href="invoices.php" class="btn btn-dark">
        Back
    </a>
</div>

</div>

</div>
</div>