<?php
include 'admin-header.php';

$message = '';
// --- ACTION HANDLING (CONFIRM/CANCEL BOOKING) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['booking_id'])) {
    $booking_id = intval($_POST['booking_id']);
    $action = $_POST['action'];

    if ($action == 'confirm') {
        // Fetch rate details to calculate the final price
        $stmt_price = $conn->prepare("
            SELECT b.check_in_date, b.check_out_date, r.price_per_night 
            FROM hotel_bookings b 
            JOIN hotel_room_rates r ON b.rate_id = r.id 
            WHERE b.id = ?");
        $stmt_price->bind_param("i", $booking_id);
        $stmt_price->execute();
        $booking_details = $stmt_price->get_result()->fetch_assoc();
        
        if($booking_details){
            $check_in = new DateTime($booking_details['check_in_date']);
            $check_out = new DateTime($booking_details['check_out_date']);
            $num_nights = max(1, $check_out->diff($check_in)->days);
            $total_price = $num_nights * $booking_details['price_per_night'];

            $stmt = $conn->prepare("UPDATE hotel_bookings SET status = 'Confirmed', total_price = ? WHERE id = ?");
            $stmt->bind_param("di", $total_price, $booking_id);
            $stmt->execute();
            $message = '<div class="alert alert-success">Booking #'.$booking_id.' confirmed. User can now proceed to payment.</div>';
        }
    } elseif ($action == 'cancel') {
        $stmt = $conn->prepare("UPDATE hotel_bookings SET status = 'Cancelled' WHERE id = ?");
        $stmt->bind_param("i", $booking_id);
        $stmt->execute();
        $message = '<div class="alert alert-warning">Booking #'.$booking_id.' has been cancelled.</div>';
    }
}

// --- DATA FETCHING ---
$current_status = $_GET['status'] ?? 'pending';

$where_clause = "";
switch ($current_status) {
    case 'confirmed': $where_clause = "WHERE hb.status = 'Confirmed'"; break;
    case 'archived': $where_clause = "WHERE hb.status IN ('Completed', 'Cancelled')"; break;
    default: $where_clause = "WHERE hb.status = 'Pending Confirmation'"; break;
}

$sql = "SELECT hb.*, u.full_name, h.name as hotel_name, hr.room_type_name, rra.rate_name
        FROM hotel_bookings hb 
        JOIN users u ON hb.user_id = u.id 
        JOIN hotels h ON hb.hotel_id = h.id 
        JOIN hotel_rooms hr ON hb.room_id = hr.id
        JOIN hotel_room_rates rra ON hb.rate_id = rra.id
        $where_clause 
        ORDER BY hb.created_at DESC";
$result = $conn->query($sql);

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

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

<ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link <?php echo $current_status == 'pending' ? 'active' : ''; ?>" href="?status=pending">
            Pending Confirmation <span class="badge bg-danger"><?php echo $pending_count; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $current_status == 'confirmed' ? 'active' : ''; ?>" href="?status=confirmed">
            Confirmed & Upcoming <span class="badge bg-success"><?php echo $confirmed_count; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $current_status == 'archived' ? 'active' : ''; ?>" href="?status=archived">Archived</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>Hotel & Room Details</th>
                        <th>Dates</th>
                        <th>Price / Status</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($result && $result->num_rows > 0): while($booking = $result->fetch_assoc()): 
                    $check_in = new DateTime($booking['check_in_date']);
                    $check_out = new DateTime($booking['check_out_date']);
                    $num_nights = $check_out->diff($check_in)->days;
                ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($booking['full_name']); ?></strong><br><small class="text-muted">ID: #<?php echo $booking['id']; ?></small></td>
                        <td>
                            <strong><?php echo htmlspecialchars($booking['hotel_name']); ?></strong><br>
                            <small class="text-muted"><?php echo htmlspecialchars($booking['room_type_name']); ?> (<?php echo htmlspecialchars($booking['rate_name']); ?>)</small>
                        </td>
                        <td>
                            <?php echo $check_in->format('M d, Y'); ?> - <?php echo $check_out->format('M d, Y'); ?><br>
                            <span class="badge bg-primary"><?php echo $num_nights; ?> night(s)</span>
                        </td>
                        <td>
                            <strong><?php echo $booking['total_price'] ? '₱'.number_format($booking['total_price'], 2) : 'N/A'; ?></strong><br>
                            <span class="badge bg-info text-dark"><?php echo $booking['status']; ?></span>
                            <?php if($booking['status'] == 'Confirmed'): ?>
                                <span class="badge <?php echo $booking['payment_status'] == 'Paid' ? 'bg-success' : 'bg-warning text-dark'; ?>"><?php echo $booking['payment_status']; ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <?php if($booking['status'] == 'Pending Confirmation'): ?>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Confirm this booking? Price will be calculated.');">
                                <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>"><button type="submit" name="action" value="confirm" class="btn btn-sm btn-success">Confirm</button>
                            </form>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Cancel this booking request?');">
                                <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>"><button type="submit" name="action" value="cancel" class="btn btn-sm btn-danger">Cancel</button>
                            </form>
                            <?php else: echo '—'; endif; ?>
                        </td>
                    </tr>
                <?php endwhile; else: ?>
                    <tr><td colspan="5" class="text-center text-muted p-4">No hotel bookings found for this status.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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