<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

// INITIAL SETUP & PAGINATION
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// BUILD DYNAMIC WHERE CLAUSE
// The crucial part: we only select bookings for 'Tour' items.
$where_clauses = ["t.category = 'Tour'"];
$params = [];
$types = '';

// Search term
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(b.booking_ref LIKE ? OR u.full_name LIKE ? OR t.title LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term, $like_term);
    $types .= 'sss';
}

// Filters
$status_filter = $_GET['status'] ?? '';
if (!empty($status_filter)) { $where_clauses[] = "b.status = ?"; $params[] = $status_filter; $types .= 's'; }
$payment_filter = $_GET['payment_status'] ?? '';
if (!empty($payment_filter)) { $where_clauses[] = "b.payment_status = ?"; $params[] = $payment_filter; $types .= 's'; }

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

// DATABASE QUERIES
$base_query = "FROM bookings b
               JOIN users u ON b.user_id = u.id
               JOIN tours t ON b.tour_id = t.id
               $where_sql";

$count_sql = "SELECT COUNT(b.id) as total $base_query";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

$fetch_sql = "SELECT b.*, u.full_name, t.title as item_title
              $base_query
              ORDER BY b.created_at DESC
              LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$bookings_result = $stmt_fetch->get_result();

// 3. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Tour Bookings</div>
    <div class="card-body">
         <form action="tour-bookings.php" method="GET" class="row g-3 align-items-center">
            <div class="col-md-5"><input type="text" name="search" class="form-control" placeholder="Search by Ref #, Customer, or Tour..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="Confirmed" <?php if($status_filter == 'Confirmed') echo 'selected'; ?>>Confirmed</option>
                    <option value="Pending" <?php if($status_filter == 'Pending') echo 'selected'; ?>>Pending</option>
                    <option value="Cancelled" <?php if($status_filter == 'Cancelled') echo 'selected'; ?>>Cancelled</option>
                </select>
            </div>
            <div class="col-md-2"><select name="payment_status" class="form-select"><option value="">All Payments</option><option value="Paid" <?php if($payment_filter == 'Paid') echo 'selected'; ?>>Paid</option><option value="Unpaid" <?php if($payment_filter == 'Unpaid') echo 'selected'; ?>>Unpaid</option></select></div>
            <div class="col-md-2 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="tour-bookings.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>Reference #</th>
                <th>Customer</th>
                <th>Tour</th>
                <th>Booking Date</th>
                <th>Travelers</th>
                <th>Payment</th>
                <th>Status</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($bookings_result->num_rows > 0): ?>
                <?php while ($booking = $bookings_result->fetch_assoc()): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($booking['booking_ref']); ?></strong></td>
                        <td><?php echo htmlspecialchars($booking['customer_name']); ?></td>
                        <td><?php echo htmlspecialchars($booking['item_title']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($booking['booking_date'])); ?></td>
                        <td><?php echo htmlspecialchars($booking['num_travelers']); ?></td>
                        <td><span class="badge bg-<?php echo ($booking['payment_status'] == 'Paid') ? 'success' : 'warning'; ?>"><?php echo htmlspecialchars($booking['payment_status']); ?></span></td>
                        <td>
                            <?php $status_badge = ['Pending' => 'warning', 'Confirmed' => 'primary', 'Cancelled' => 'danger']; ?>
                            <span class="badge bg-<?php echo $status_badge[$booking['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars($booking['status']); ?></span>
                        </td>
                        <td class="text-end">
                             <a href="#" class="btn btn-sm btn-info" title="View Details"><i class="bi bi-eye-fill"></i></a>
                            <button type="button" class="btn btn-sm btn-warning" title="Update Status"><i class="bi bi-pencil-fill"></i></button>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="8" class="text-center p-4">No tour bookings found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<?php include 'admin-footer.php'; ?>
