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

$stay_id = intval($_GET['stay_id'] ?? 0);

// Fetch stay and guest details
$stay = $conn->query("
    SELECT s.*, g.name AS guest_name, g.id AS guest_id, r.id AS room_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=$stay_id
")->fetch_assoc();

if(!$stay){
    echo "<div class='alert alert-danger'>Invalid stay selected.</div>";
    exit;
}

// =================== CALCULATE CHARGES ===================
$payments_res = $conn->query("SELECT type, SUM(amount) AS total_paid FROM payments WHERE guest_id=".$stay['guest_id']." GROUP BY type");
$payments = [];
while($p = $payments_res->fetch_assoc()){
    $payments[$p['type']] = $p['total_paid'];
}

// Example fixed rates (can be dynamic later)
$room_charge   = $stay['days'] * $stay['room_price'];
$laundry       = 50;
$room_service  = 100;
$restaurant    = 120;
$bar           = 80;

$total_charges = $room_charge + $laundry + $room_service + $restaurant + $bar;
$total_paid    = ($payments['Room'] ?? 0) + ($payments['Laundry'] ?? 0) + ($payments['Room Service'] ?? 0) 
                 + ($payments['Restaurant'] ?? 0) + ($payments['Bar'] ?? 0);
$balance       = $total_charges - $total_paid;

// =================== INSERT INVOICE IF NOT EXISTS ===================
$existing_invoice = $conn->query("SELECT id FROM invoices WHERE stay_id=$stay_id LIMIT 1")->fetch_assoc();

if(!$existing_invoice){
    // Generate unique invoice number
    $invoice_number = 'INV-' . str_pad($stay_id, 5, '0', STR_PAD_LEFT) . '-' . date('YmdHi');

    $stmt = $conn->prepare("
        INSERT INTO invoices (stay_id, guest_id, invoice_number, total_amount, created_at) 
        VALUES (?,?,?,?,NOW())
    ");
    $stmt->bind_param("iisd", $stay_id, $stay['guest_id'], $invoice_number, $total_charges);
    $stmt->execute();

    // Mark stay as checked out
    $conn->query("UPDATE stays SET checkout_date=NOW() WHERE id=$stay_id");

    // Make room available
    $conn->query("UPDATE rooms SET status='Available' WHERE id=".$stay['room_id']);
}

?>

<style>
.invoice-box{
    max-width:800px;
    margin:auto;
    padding:30px;
    border:1px solid #eee;
    box-shadow:0 0 10px rgba(0,0,0,0.15);
    font-size:14px;
    line-height:24px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color:#555;
}
.invoice-box table{
    width:100%;
    line-height:inherit;
    text-align:left;
}
.invoice-box table td{
    padding:5px;
    vertical-align:top;
}
.invoice-box table tr.heading td{
    background:#eee;
    border-bottom:1px solid #ddd;
    font-weight:bold;
}
.invoice-box table tr.total td{
    border-top:2px solid #333;
    font-weight:bold;
}
@media print{
    .no-print{display:none;}
}
</style>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<div class="invoice-box">
    <h3>Hotel Invoice</h3>
    <table>
        <tr>
            <td>
                <strong>Guest:</strong> <?= $stay['guest_name'] ?><br>
                <strong>Room:</strong> <?= $stay['room_number'].' ('.$stay['room_type'].')' ?><br>
                <strong>Check-In:</strong> <?= date('Y-m-d', strtotime($stay['checkin_date'])) ?><br>
                <strong>Check-Out:</strong> <?= date('Y-m-d H:i') ?><br>
            </td>
            <td style="text-align:right;">
                
                  <strong>TPIN:30798071 </strong><br>
                <strong>Invoice #: </strong><?= $stay_id ?><br>
                <strong>Date: </strong><?= date('Y-m-d H:i') ?>
            </td>
        </tr>
    </table>

    <hr>

    <table cellpadding="0" cellspacing="0">
        <tr class="heading">
            <td>Service</td>
            <td>Amount (MK)</td>
        </tr>
        <tr>
            <td>Room (<?= $stay['days'] ?> days @ <?= number_format($stay['room_price'],2) ?>)</td>
            <td><?= number_format($room_charge,2) ?></td>
        </tr>
        <tr>
            <td>Laundry</td>
            <td><?= number_format($laundry,2) ?></td>
        </tr>
        <tr>
            <td>Room Service</td>
            <td><?= number_format($room_service,2) ?></td>
        </tr>
        <tr>
            <td>Restaurant</td>
            <td><?= number_format($restaurant,2) ?></td>
        </tr>
        <tr>
            <td>Bar</td>
            <td><?= number_format($bar,2) ?></td>
        </tr>
        <tr class="total">
            <td>Total Charges</td>
            <td><?= number_format($total_charges,2) ?></td>
        </tr>
        <tr class="total">
            <td>Total Paid</td>
            <td><?= number_format($total_paid,2) ?></td>
        </tr>
        <tr class="total">
            <td>Balance</td>
            <td><?= number_format($balance,2) ?></td>
        </tr>
    </table>

    <p class="mt-3">Thank you for staying with us!</p>

    <button onclick="window.print()" class="btn btn-success no-print">
        <i class="fa fa-print"></i> Print Invoice
    </button>
    <a href="checkin.php" class="btn btn-secondary no-print">Back to Dashboard</a>
</div>
</div>

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