<?php
include 'admin-header.php';
require_once '../includes/helpers.php';

// --- 1. 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;

// --- 2. BUILD DYNAMIC WHERE CLAUSE FOR FILTERING & SEARCHING ---
$where_clauses = [];
$params = [];
$types = '';

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

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

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

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// --- 3. DATABASE QUERIES (COUNT & FETCH) ---

// First, get the total number of records for pagination
$count_sql = "SELECT COUNT(b.id) as total FROM bookings b 
              JOIN users u ON b.user_id = u.id 
              JOIN tours t ON b.tour_id = t.id $where_sql";

$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();


// Now, fetch the records for the current page
$fetch_sql = "SELECT b.*, u.full_name, t.title as tour_title FROM bookings b 
              JOIN users u ON b.user_id = u.id 
              JOIN tours t ON b.tour_id = t.id 
              $where_sql 
              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();

?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Tour Bookings</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <a href="add-booking.php" class="btn btn-sm btn-outline-primary">
            <i class="bi bi-plus-circle-fill me-1"></i>
            Add New Booking
        </a>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-filter me-1"></i> Filter & Search Bookings
    </div>
    <div class="card-body">
        <form action="manage-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 Booking ID, Customer, or Tour..." value="<?php echo htmlspecialchars($search_term); ?>">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Booking Statuses</option>
                    <option value="Pending" <?php if($status_filter == 'Pending') echo 'selected'; ?>>Pending</option>
                    <option value="Confirmed" <?php if($status_filter == 'Confirmed') echo 'selected'; ?>>Confirmed</option>
                    <option value="Completed" <?php if($status_filter == 'Completed') echo 'selected'; ?>>Completed</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 Payment Statuses</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="manage-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">
            <tr>
                <th>Booking ID</th>
                <th>Customer</th>
                <th>Tour/Service</th>
                <th>Booking Date</th>
                <th>Amount</th>
                <th>Payment</th>
                <th>Status</th>
                <th>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['id']); ?></strong></td>
                        <td><?php echo htmlspecialchars($booking['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($booking['tour_title']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($booking['created_at'])); ?></td>
                        <td>₱<?php echo number_format($booking['total_price'], 2); ?></td>
                        <td>
                            <?php
                                $payment_badge = 'secondary';
                                if ($booking['payment_status'] == 'Paid') $payment_badge = 'success';
                                if ($booking['payment_status'] == 'Unpaid') $payment_badge = 'warning';
                            ?>
                            <span class="badge bg-<?php echo $payment_badge; ?>"><?php echo htmlspecialchars($booking['payment_status']); ?></span>
                        </td>
                        <td>
                             <?php
                                $status_badge = 'secondary';
                                if ($booking['status'] == 'Confirmed') $status_badge = 'primary';
                                if ($booking['status'] == 'Pending') $status_badge = 'warning';
                                if ($booking['status'] == 'Completed') $status_badge = 'success';
                                if ($booking['status'] == 'Cancelled') $status_badge = 'danger';
                            ?>
                            <span class="badge bg-<?php echo $status_badge; ?>"><?php echo htmlspecialchars($booking['status']); ?></span>
                        </td>
                        <td>
                            <a href="view-booking.php?id=<?php echo $booking['id']; ?>" 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 update-status-btn" 
                                    data-bs-toggle="modal" 
                                    data-bs-target="#updateStatusModal" 
                                    data-booking-id="<?php echo $booking['id']; ?>" 
                                    data-current-status="<?php echo $booking['status']; ?>"
                                    title="Update Status">
                                <i class="bi bi-pencil-fill"></i>
                            </button>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="8" class="text-center">No bookings found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav aria-label="Page navigation">
    <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; ?>


<div class="modal fade" id="updateStatusModal" tabindex="-1" aria-labelledby="updateStatusModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="updateStatusModalLabel">Update Booking Status</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="actions/update_booking_status.php" method="POST">
        <div class="modal-body">
            <p>Select the new status for Booking ID #<strong id="modalBookingId"></strong>.</p>
            <input type="hidden" name="booking_id" id="modalBookingIdInput">
            <div class="form-group">
                <label for="new_status">New Status</label>
                <select name="new_status" id="new_status" class="form-select" required>
                    <option value="Pending">Pending</option>
                    <option value="Confirmed">Confirmed</option>
                    <option value="Completed">Completed</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// JavaScript to pass booking ID and current status to the modal
document.addEventListener('DOMContentLoaded', function () {
    var updateStatusModal = document.getElementById('updateStatusModal');
    updateStatusModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var bookingId = button.getAttribute('data-booking-id');
        var currentStatus = button.getAttribute('data-current-status');

        var modalTitle = updateStatusModal.querySelector('.modal-title');
        var modalBookingId = updateStatusModal.querySelector('#modalBookingId');
        var modalBookingIdInput = updateStatusModal.querySelector('#modalBookingIdInput');
        var newStatusSelect = updateStatusModal.querySelector('#new_status');
        
        modalBookingId.textContent = bookingId;
        modalBookingIdInput.value = bookingId;
        newStatusSelect.value = currentStatus;
    });
});
</script>

<?php
$stmt_fetch->close();
include 'admin-footer.php';
?>
