<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
// This connects to DB, starts session, checks security, and sets up menu variables.
require_once 'admin-logic.php';


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

// 2. HANDLE DELETE ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_hotel') {
    $hotel_id = filter_input(INPUT_POST, 'hotel_id', FILTER_VALIDATE_INT);
    if ($hotel_id) {
        // For a real-world app, you should also delete associated rooms, gallery images, etc.
        // This can be done here with more queries or by setting up cascading deletes in your database.
        $stmt = $conn->prepare("DELETE FROM hotels WHERE id = ?");
        $stmt->bind_param("i", $hotel_id);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Hotel deleted successfully.";
        } else {
            $_SESSION['error_message'] = "Error deleting hotel. It might have associated bookings.";
        }
        $stmt->close();
    }
    header("Location: manage-hotels.php");
    exit();
}

// 3. FETCH HOTELS FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = []; $params = []; $types = '';

// Search by name or location
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(h.name LIKE ? OR h.location LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}

// Filter by status
$status_filter = $_GET['status'] ?? '';
if ($status_filter === 'published') { $where_clauses[] = "h.is_published = 1"; } 
elseif ($status_filter === 'draft') { $where_clauses[] = "h.is_published = 0"; }

// Filter by star rating
$rating_filter = filter_input(INPUT_GET, 'rating', FILTER_VALIDATE_INT);
if ($rating_filter) {
    $where_clauses[] = "h.star_rating = ?";
    $params[] = $rating_filter;
    $types .= 'i';
}

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

// Count for pagination
$count_sql = "SELECT COUNT(h.id) as total FROM hotels h $where_sql";
$stmt_count = $conn->prepare($count_sql); // This is the line that was causing the error
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 hotels for display, joining with users to get partner name
$fetch_sql = "SELECT h.id, h.name, h.location, h.star_rating, h.is_published, u.full_name as partner_name 
              FROM hotels h
              LEFT JOIN users u ON h.partner_id = u.id
              $where_sql 
              ORDER BY h.name ASC 
              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();
$hotels_result = $stmt_fetch->get_result();


// 4. 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="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 Hotels</h1>
    <a href="edit-hotel.php" class="btn btn-primary">
        <i class="bi bi-plus-circle-fill me-1"></i> Add New Hotel
    </a>
</div>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Hotels</div>
    <div class="card-body">
        <form action="manage-hotels.php" method="GET" class="row g-3">
            <div class="col-md-5"><input type="text" name="search" class="form-control" placeholder="Search by Hotel Name or Location..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="published" <?php if($status_filter == 'published') echo 'selected'; ?>>Published</option>
                    <option value="draft" <?php if($status_filter == 'draft') echo 'selected'; ?>>Draft</option>
                </select>
            </div>
            <div class="col-md-2">
                <select name="rating" class="form-select">
                    <option value="">All Ratings</option>
                    <?php for($i=5; $i>=1; $i--): ?>
                    <option value="<?php echo $i; ?>" <?php if($rating_filter == $i) echo 'selected'; ?>><?php echo $i; ?> Star<?php echo $i > 1 ? 's' : ''; ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="manage-hotels.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>Hotel Name</th>
                <th>Partner</th>
                <th>Location</th>
                <th class="text-center">Rating</th>
                <th class="text-center">Status</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($hotels_result->num_rows > 0): while ($hotel = $hotels_result->fetch_assoc()): ?>
            <tr>
                <td class="fw-bold"><?php echo htmlspecialchars($hotel['name']); ?></td>
                <td><?php echo htmlspecialchars($hotel['partner_name'] ?? 'Admin'); ?></td>
                <td><?php echo htmlspecialchars($hotel['location']); ?></td>
                <td class="text-center text-warning">
                    <?php for($i=0; $i < $hotel['star_rating']; $i++) { echo '<i class="bi bi-star-fill"></i>'; } ?>
                </td>
                <td class="text-center">
                    <span class="badge bg-<?php echo ($hotel['is_published']) ? 'success' : 'secondary'; ?>">
                        <?php echo ($hotel['is_published']) ? 'Published' : 'Draft'; ?>
                    </span>
                </td>
                <td class="text-end">
                    <div class="d-inline-flex gap-1">
                        <a href="../hotel-details.php?id=<?php echo $hotel['id']; ?>" class="btn btn-sm btn-outline-primary" title="View Live Page" target="_blank"><i class="bi bi-box-arrow-up-right"></i></a>
                        <a href="manage-rooms.php?hotel_id=<?php echo $hotel['id']; ?>" class="btn btn-sm btn-info" title="Manage Rooms"><i class="bi bi-door-open-fill"></i></a>
                        <a href="edit-hotel.php?id=<?php echo $hotel['id']; ?>" class="btn btn-sm btn-warning" title="Edit Hotel"><i class="bi bi-pencil-fill"></i></a>
                        <form method="POST" action="manage-hotels.php" onsubmit="return confirm('Are you sure you want to delete this hotel and all its associated data?');">
                            <input type="hidden" name="action" value="delete_hotel">
                            <input type="hidden" name="hotel_id" value="<?php echo $hotel['id']; ?>">
                            <button type="submit" class="btn btn-sm btn-danger" title="Delete Hotel"><i class="bi bi-trash-fill"></i></button>
                        </form>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="6" class="text-center p-4">No hotels 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'; ?>
