<?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;
$status    = $_GET['status'] ?? '';
$guest_id  = $_GET['guest_id'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];
$where[] = "r.date_in >= '".$conn->real_escape_string($from_date)."'";
$where[] = "r.date_out <= '".$conn->real_escape_string($to_date)."'";

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

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

// ================= FETCH RESERVATIONS =================
$query = "
SELECT r.*, g.name AS guest_name, ro.room_number
FROM reservations r
LEFT JOIN guests g ON g.id = r.guest_id
LEFT JOIN rooms ro ON ro.id = r.room_id
$where_sql
ORDER BY r.date_in DESC
";

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

// ================= SUMMARY =================
$summary = $conn->query("
SELECT 
    COUNT(*) AS total_reservations,
    SUM(CASE WHEN status='Pending' THEN 1 ELSE 0 END) AS pending_count,
    SUM(CASE WHEN status='Confirmed' THEN 1 ELSE 0 END) AS confirmed_count,
    SUM(CASE WHEN status='Cancelled' THEN 1 ELSE 0 END) AS cancelled_count
FROM reservations r
$where_sql
")->fetch_assoc();

$total_reservations = $summary['total_reservations'] ?? 0;
$pending_count     = $summary['pending_count'] ?? 0;
$confirmed_count   = $summary['confirmed_count'] ?? 0;
$cancelled_count   = $summary['cancelled_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-calendar-check text-primary"></i> Reservations 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=='Pending'?'selected':'' ?>>Pending</option>
                <option <?= $status=='Confirmed'?'selected':'' ?>>Confirmed</option>
                <option <?= $status=='Cancelled'?'selected':'' ?>>Cancelled</option>
            </select>
        </div>
        <div class="col-md-3"><input type="text" name="search" class="form-control" placeholder="Guest / 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="reservations_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_reservations_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 Reservations</h6>
                    <h4 class="text-primary"><?= $total_reservations ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Pending</h6>
                    <h4 class="text-warning"><?= $pending_count ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Confirmed</h6>
                    <h4 class="text-success"><?= $confirmed_count ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Cancelled</h6>
                    <h4 class="text-danger"><?= $cancelled_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>Reservation ID</th>
                    <th>Guest</th>
                    <th>Room</th>
                    <th>Date In</th>
                    <th>Date Out</th>
                    <th>Days</th>
                    <th>Status</th>
                    <th>Payment Amount</th>
                    <th>Payment Status</th>
                    <th>Created At</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result && $result->num_rows): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['id'] ?></td>
                            <td><?= $row['guest_name'] ?? $row['guest_id'] ?></td>
                            <td><?= $row['room_number'] ?></td>
                            <td><?= $row['date_in'] ?></td>
                            <td><?= $row['date_out'] ?></td>
                            <td><?= $row['days'] ?></td>
                            <td><?= $row['status'] ?></td>
                            <td><?= $row['payment_amount'] ?></td>
                            <td><?= $row['payment_status'] ?></td>
                            <td><?= $row['created_at'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="10" class="text-center text-danger">No reservations found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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