<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
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_item') {
    $item_id = filter_input(INPUT_POST, 'item_id', FILTER_VALIDATE_INT);
    if ($item_id) {
        $stmt = $conn->prepare("DELETE FROM tours WHERE id = ? AND category = 'Tour'");
        $stmt->bind_param("i", $item_id);
        if ($stmt->execute()) { $_SESSION['success_message'] = "Tour deleted successfully."; } 
        else { $_SESSION['error_message'] = "Error deleting tour."; }
        $stmt->close();
    }
    header("Location: manage-tours.php");
    exit();
}

// 3. FETCH TOURS 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 = ["category = 'Tour'"]; 
$params = []; $types = '';
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(title LIKE ? OR location LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}
$status_filter = $_GET['status'] ?? '';
if (!empty($status_filter)) {
    $where_clauses[] = "status = ?";
    $params[] = $status_filter;
    $types .= 's';
}
$where_sql = "WHERE " . implode(' AND ', $where_clauses);

$count_sql = "SELECT COUNT(id) as total FROM tours $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();

$fetch_sql = "SELECT id, title, location, price, status FROM tours $where_sql ORDER BY 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();
$items_result = $stmt_fetch->get_result();

$current_page = 'manage-tours.php';
$page_title = 'Manage Tours';

// 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; ?>

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

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Tours</div>
    <div class="card-body">
        <form action="manage-tours.php" method="GET" class="row g-3">
            <div class="col-md-6"><input type="text" name="search" class="form-control" placeholder="Search by Title or Location..." 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="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-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="manage-tours.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>Title</th><th>Location</th><th>Price</th><th class="text-center">Status</th><th class="text-end">Actions</th></tr>
        </thead>
        <tbody>
            <?php if ($items_result->num_rows > 0): while ($item = $items_result->fetch_assoc()): ?>
            <tr>
                <td class="fw-bold"><?php echo htmlspecialchars($item['title']); ?></td>
                <td><?php echo htmlspecialchars($item['location']); ?></td>
                <td>₱<?php echo number_format($item['price'], 2); ?></td>
                <td class="text-center"><span class="badge bg-<?php echo ($item['status'] == 'published') ? 'success' : 'secondary'; ?>"><?php echo htmlspecialchars(ucfirst($item['status'])); ?></span></td>
                <td class="text-end">
                    <div class="d-inline-flex gap-1">
                        <a href="manage-tour-availability.php?tour_id=<?php echo $item['id']; ?>" class="btn btn-sm btn-info" title="Manage Availability"><i class="bi bi-calendar-check-fill"></i></a>
                        <a href="../tour-details.php?id=<?php echo $item['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="edit-tour.php?id=<?php echo $item['id']; ?>" class="btn btn-sm btn-warning" title="Edit"><i class="bi bi-pencil-fill"></i></a>
                        <form method="POST" action="manage-tours.php" onsubmit="return confirm('Are you sure?');"><input type="hidden" name="action" value="delete_item"><input type="hidden" name="item_id" value="<?php echo $item['id']; ?>"><button type="submit" class="btn btn-sm btn-danger" title="Delete"><i class="bi bi-trash-fill"></i></button></form>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="5" class="text-center p-4">No tours 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'; ?>
