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

$username = $_SESSION['username'] ?? 'Guest';
$today = date('Y-m-d');

// ================= FILTERS =================
// Default to today
$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$guest_id  = $_GET['guest_id'] ?? '';
$status    = $_GET['status'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];
$where[] = "DATE(s.checkout_date) >= '".$conn->real_escape_string($from_date)."'";
$where[] = "DATE(s.checkout_date) <= '".$conn->real_escape_string($to_date)."'";

if($guest_id){
    $where[] = "s.guest_id = '".$conn->real_escape_string($guest_id)."'";
}
if($status){
    $where[] = "s.status = '".$conn->real_escape_string($status)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(g.name LIKE '%$s%' OR r.room_number LIKE '%$s%')";
}

$where_sql = "WHERE ".implode(" AND ", $where);

// ================= FETCH STAYS =================
$query = "
SELECT s.*, g.name AS guest_name, r.room_number
FROM stays s
LEFT JOIN guests g ON g.id = s.guest_id
LEFT JOIN rooms r ON r.id = s.room_id
$where_sql
ORDER BY s.checkout_date DESC
";

$result = $conn->query($query);

// ================= SUMMARY =================
$summary = $conn->query("
SELECT 
    COUNT(*) AS total_stays,
    IFNULL(SUM(locked_room_price),0) AS total_amount,
    SUM(CASE WHEN status=1 THEN 1 ELSE 0 END) AS active_count,
    SUM(CASE WHEN status=7 THEN 1 ELSE 0 END) AS completed_count
FROM stays s
$where_sql
")->fetch_assoc();

$total_stays      = $summary['total_stays'] ?? 0;
$total_amount     = $summary['total_amount'] ?? 0;
$active_count     = $summary['active_count'] ?? 0;
$completed_count  = $summary['completed_count'] ?? 0;
?>

<style>
.report-card{border-radius:12px;}
.table thead th{white-space:nowrap;}
.welcome-msg{background:#f8f9fa;padding:8px 12px;border-radius:8px;margin-bottom:10px;}
@media print{.no-print{display:none!important;}}
</style>

<div class="container-fluid mt-4">
    <button class="btn btn-secondary no-print" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>

    <div class="welcome-msg no-print">
        <i class="fa fa-user-circle"></i>
        Welcome, <strong><?= htmlspecialchars($username) ?></strong>
    </div>

    <h3 class="mb-2"><i class="fa fa-bed text-primary"></i> Stays Report</h3>
    <hr>

    <!-- ================= FILTERS ================= -->
    <form method="GET" class="row g-2 mb-3 no-print">
        <div class="col-md-2"><input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>"></div>
        <div class="col-md-2"><input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>"></div>
        <div class="col-md-2">
            <select name="status" class="form-control">
                <option value="">All Statuses</option>
                <option <?= $status=='1'?'selected':'' ?>>Active</option>
                <option <?= $status=='7'?'selected':'' ?>>Completed</option>
            </select>
        </div>
        <div class="col-md-3"><input type="text" name="search" class="form-control" placeholder="Guest name / Room" value="<?= htmlspecialchars($search) ?>"></div>
        <div class="col-md-3 d-flex gap-1">
            <button class="btn btn-primary w-100"><i class="fa fa-filter"></i> Filter</button>
            <a href="stays_report.php" class="btn btn-secondary w-100">Reset</a>
        </div>
    </form>

    <!-- ================= ACTION BUTTONS ================= -->
    <div class="mb-3 no-print d-flex gap-2">
        <a href="export_stays_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>" class="btn btn-success">
            <i class="fa fa-file-excel"></i> Export Excel
        </a>
        <button onclick="window.print()" class="btn btn-info"><i class="fa fa-print"></i> Print / PDF</button>
    </div>

    <!-- ================= SUMMARY CARDS ================= -->
    <div class="row mb-3 text-center">
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Stays</h6>
                    <h4 class="text-primary"><?= $total_stays ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Amount (MK)</h6>
                    <h4 class="text-dark"><?= number_format($total_amount,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Active</h6>
                    <h4 class="text-success"><?= $active_count ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Completed</h6>
                    <h4 class="text-warning"><?= $completed_count ?></h4>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= TABLE ================= -->
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Stay ID</th>
                    <th>Guest</th>
                    <th>Room</th>
                    <th>Locked Price (MK)</th>
                    <th>Checkin Date</th>
                    <th>Checkout Date</th>
                    <th>Days</th>
                    <th>Status</th>
                    <th>Created By</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result && $result->num_rows): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['id'] ?></td>
                            <td><?= htmlspecialchars($row['guest_name'] ?? $row['guest_id']) ?></td>
                            <td><?= htmlspecialchars($row['room_number']) ?></td>
                            <td><?= number_format($row['locked_room_price'],2) ?></td>
                            <td><?= $row['checkin_date'] ?></td>
                            <td><?= $row['checkout_date'] ?></td>
                            <td><?= $row['days'] ?></td>
                            <td><?= $row['status']==7?'Completed':'Active' ?></td>
                            <td><?= $row['created_by'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="9" class="text-center text-danger">No stays found</td></tr>
                <?php endif; ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="3">TOTAL</th>
                    <th><?= number_format($total_amount,2) ?></th>
                    <th colspan="5"></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

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