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

// ================= FILTER INPUTS =================
$from = $_GET['from'] ?? '';
$to   = $_GET['to'] ?? '';
$guest_search = $_GET['guest'] ?? '';
$room_search  = $_GET['room'] ?? '';

// ================= BUILD WHERE CLAUSE =================
$where = [];
if($from) $where[] = "DATE(s.checkin_date) >= '".$conn->real_escape_string($from)."'";
if($to)   $where[] = "DATE(s.checkout_date) <= '".$conn->real_escape_string($to)."'";
if($guest_search) $where[] = "g.name LIKE '%".$conn->real_escape_string($guest_search)."%'";
if($room_search)  $where[] = "r.room_number LIKE '%".$conn->real_escape_string($room_search)."%'";
$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH STAYS WITH DETAILS =================
$history = $conn->query("
    SELECT 
        s.id AS stay_id,
        g.id AS guest_id,
        g.name AS guest_name,
        r.room_number,
        r.room_type,
        IFNULL(s.locked_room_price,0) AS room_price,
        s.checkin_date,
        s.checkout_date,
        IFNULL(s.days, DATEDIFF(s.checkout_date, s.checkin_date)) AS nights
    FROM stays s
    JOIN guests g ON s.guest_id = g.id
    JOIN rooms r ON s.room_id = r.id
    $where_sql
    ORDER BY s.checkin_date DESC
");

// ================= TAX RATES =================
$vat_rate = 0.175;      // 17.5%
$tourism_rate = 0.01;   // 1%
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4>Guest History & Payments</h4>
    <hr>

    <!-- ================= FILTER FORM ================= -->
    <form method="GET" class="row g-2 mb-4">
        <div class="col-md-2">
            <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from) ?>" placeholder="From Date">
        </div>
        <div class="col-md-2">
            <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to) ?>" placeholder="To Date">
        </div>
        <div class="col-md-3">
            <input type="text" name="guest" class="form-control" value="<?= htmlspecialchars($guest_search) ?>" placeholder="Guest Name">
        </div>
        <div class="col-md-2">
            <input type="text" name="room" class="form-control" value="<?= htmlspecialchars($room_search) ?>" placeholder="Room Number">
        </div>
        <div class="col-md-3">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- ================= GUEST HISTORY TABLE ================= -->
    <table class="table table-bordered table-striped table-sm">
        <thead class="table-dark">
            <tr>
                <th>Guest</th>
                <th>Room</th>
                <th>Room Type</th>
                <th>Check-In</th>
                <th>Check-Out</th>
                <th>Nights</th>
                <th>Room Cost (MK)</th>
                <th>Services/Bar/Restaurant (MK)</th>
                <th>VAT (17.5%)</th>
                <th>Tourism Levy (1%)</th>
                <th>Total (MK)</th>
                <th>Paid (MK)</th>
                <th>Balance (MK)</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while($h = $history->fetch_assoc()):
                $nights = intval($h['nights']);
                $room_cost = floatval($h['room_price']) * $nights;

                // ================= FETCH SERVICES =================
                $service_total = 0;
                $services = $conn->query("
                    SELECT name, amount, quantity
                    FROM charges
                    WHERE guest_id = ".$h['guest_id']."
                ");
                $service_details = '';
                while($s = $services->fetch_assoc()){
                    $service_details .= htmlspecialchars($s['name'])." (".number_format($s['amount'],2).") x ".$s['quantity']."<br>";
                    $service_total += $s['amount'] * $s['quantity'];
                }

                // ================= CALCULATE TAXES & TOTAL =================
                $subtotal = $room_cost + $service_total;
                $vat = $subtotal * $vat_rate;
                $tourism = $subtotal * $tourism_rate;
                $total = $subtotal + $vat + $tourism;

                // ================= FETCH PAYMENTS =================
                $paid_sum = $conn->query("
                    SELECT SUM(amount) AS total_paid
                    FROM payments
                    WHERE guest_id=".$h['guest_id']."
                ")->fetch_assoc()['total_paid'] ?? 0;
                $balance = $total - $paid_sum;
            ?>
            <tr class="<?= !$h['checkout_date'] ? 'table-success' : '' ?>">
                <td><?= htmlspecialchars($h['guest_name']) ?></td>
                <td><?= htmlspecialchars($h['room_number']) ?></td>
                <td><?= htmlspecialchars($h['room_type']) ?></td>
                <td><?= $h['checkin_date'] ? date('Y-m-d H:i', strtotime($h['checkin_date'])) : '-' ?></td>
                <td><?= $h['checkout_date'] ? date('Y-m-d H:i', strtotime($h['checkout_date'])) : 'Currently Checked In' ?></td>
                <td><?= $nights ?></td>
                <td><?= number_format($room_cost,2) ?></td>
                <td>
                    <a href="#" data-bs-toggle="tooltip" data-bs-html="true" title="<?= $service_details ?>">
                        <?= number_format($service_total,2) ?>
                    </a>
                </td>
                <td><?= number_format($vat,2) ?></td>
                <td><?= number_format($tourism,2) ?></td>
                <td><?= number_format($total,2) ?></td>
                <td><?= number_format($paid_sum,2) ?></td>
                <td><?= number_format($balance,2) ?></td>
                <td>
                    <?php if($balance > 0): ?>
                        <a href="create_invoice.php?guest_id=<?= $h['guest_id'] ?>&stay_id=<?= $h['stay_id'] ?>" class="btn btn-primary btn-sm mb-1">
                            <i class="fa fa-file-invoice"></i> Invoice
                        </a>
                        <a href="payments.php?guest_id=<?= $h['guest_id'] ?>" class="btn btn-success btn-sm mb-1">
                            <i class="fa fa-money-bill"></i> Receive Payment
                        </a>
                    <?php else: ?>
                        <a href="receipt_thermal.php?stay_id=<?= $h['stay_id'] ?>" target="_blank" class="btn btn-secondary btn-sm mb-1">
                            <i class="fa fa-receipt"></i> Receipt
                        </a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    })
});
</script>

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