<?php
// --- LOGIC BLOCK ---
require_once '../includes/db.php';
if (!isset($_SESSION['admin_logged_in'])) { header("Location: ../login.php"); exit(); }

$message = '';
// Handle POST actions to update booking status
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['booking_id'])) {
    $booking_id = intval($_POST['booking_id']);
    $new_status = $_POST['status'];

    if (in_array($new_status, ['Confirmed', 'Completed', 'Cancelled'])) {
        $stmt = $conn->prepare("UPDATE bookings SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $new_status, $booking_id);
        if ($stmt->execute()) {
            $message = '<div class="alert alert-success">Booking status updated successfully.</div>';
        } else {
            $message = '<div class="alert alert-danger">Error updating status.</div>';
        }
    }
}

// --- DATA FETCHING ---
$current_status_filter = $_GET['status'] ?? 'confirmed'; // Default to 'confirmed'
$where_clause = "";
switch ($current_status_filter) {
    case 'completed': $where_clause = "WHERE b.status = 'Completed'"; break;
    case 'cancelled': $where_clause = "WHERE b.status = 'Cancelled'"; break;
    default: $where_clause = "WHERE b.status = 'Confirmed'"; break;
}

// Counts for tab badges
$confirmed_count = $conn->query("SELECT COUNT(*) as total FROM bookings WHERE status = 'Confirmed'")->fetch_assoc()['total'];

$sql = "SELECT b.*, t.title as tour_title,
               (SELECT COUNT(*) FROM messages m WHERE m.booking_id = b.id AND m.booking_type = 'tour' AND m.is_read = 0 AND m.sender_id != 1) as unread_messages
        FROM bookings b
        JOIN tours t ON b.tour_id = t.id
        $where_clause
        ORDER BY b.booking_date ASC";

$bookings_result = $conn->query($sql);

// --- PRESENTATION BLOCK ---
include 'admin-header.php';
?>

<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 & Service Bookings</h1>
</div>
<?php echo $message; ?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link <?php if($current_status_filter == 'confirmed') echo 'active'; ?>" href="?status=confirmed">
            Upcoming & Confirmed <span class="badge bg-danger rounded-pill"><?php echo $confirmed_count; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php if($current_status_filter == 'completed') echo 'active'; ?>" href="?status=completed">Completed</a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php if($current_status_filter == 'cancelled') echo 'active'; ?>" href="?status=cancelled">Cancelled</a>
    </li>
</ul>

<div class="card shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>Customer</th>
                        <th>Tour / Service</th>
                        <th>Booking Date</th>
                        <th>Travelers</th>
                        <th>Payment</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($bookings_result && $bookings_result->num_rows > 0): ?>
                        <?php while($booking = $bookings_result->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($booking['customer_name']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($booking['customer_email']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($booking['tour_title']); ?></td>
                            <td><?php echo date('M d, Y', strtotime($booking['booking_date'])); ?></td>
                            <td><?php echo $booking['num_travelers']; ?></td>
                            <td>
                                <strong class="text-success">₱<?php echo number_format($booking['total_price'], 2); ?></strong><br>
                                <span class="badge bg-success"><?php echo htmlspecialchars($booking['payment_status']); ?></span>
                            </td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <a href="view-messages.php?type=tour&booking_id=<?php echo $booking['id']; ?>" class="btn btn-sm btn-outline-secondary position-relative">
                                        Messages
                                        <?php if($booking['unread_messages'] > 0): ?>
                                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"><?php echo $booking['unread_messages']; ?></span>
                                        <?php endif; ?>
                                    </a>
                                    <?php if ($booking['status'] == 'Confirmed'): ?>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Mark this booking as completed?');">
                                        <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>">
                                        <button type="submit" name="status" value="Completed" class="btn btn-sm btn-primary">Mark Completed</button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center text-muted p-4">No bookings found for this status.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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