<?php
include "include/db.php";
include "include/header.php";
$success = ''; // For any flash messages
$errors = []; // Not used here
// Handle Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $delete_id = (int)$_POST['delete_id'];
    if ($delete_id > 0) {
        $delete_sql = "DELETE FROM manage_landing WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param('i', $delete_id);
        if ($delete_stmt->execute()) {
            $success = "Landing page deleted successfully!";
        } else {
            $errors[] = "Delete Error: " . $delete_stmt->error;
        }
        $delete_stmt->close();
    }
}
// Pagination settings
$items_per_page = 10;
$current_page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($current_page - 1) * $items_per_page;
// Fetch total count
$count_sql = "SELECT COUNT(*) as total FROM manage_landing";
$count_result = $conn->query($count_sql);
$total_items = $count_result ? $count_result->fetch_assoc()['total'] : 0;
$total_pages = ceil($total_items / $items_per_page);
// Fetch paginated landing pages
$sql = "SELECT * FROM manage_landing ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ii', $items_per_page, $offset);
$stmt->execute();
$result = $stmt->get_result();
if (!$result) {
    $errors[] = "DB Query Error: " . $conn->error;
}
$landings = []; // Array for JS filtering (but pagination is server-side, so limited to current page)
if ($result) {
    while ($row = $result->fetch_assoc()) {
        // Simulate created date based on ID (adjust multiplier as needed; e.g., older IDs = older dates)
        $row['created'] = date('M j, Y', time() - ($row['id'] * 86400 * 5)); // 5 days per ID for variety
        $landings[] = $row;
    }
}
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Landing Pages List</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background: #f8fafc; }
        .content { transition: margin-left 0.3s; }
        .top-nav { background: #1f2937; }
        .table-container { overflow-x: auto; border-radius: 8px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); }
        .table { min-width: 800px; background: white; border-collapse: collapse; }
        .table th { background: #f1f5f9; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 2px solid #e2e8f0; }
        .table td { transition: background-color 0.2s ease; border-bottom: 1px solid #f1f5f9; }
        .table tbody tr:nth-child(even) { background: #fdfdfd; }
        .table tbody tr:hover { background: #f0f9ff; }
        .error { background: #fee2e2; color: #dc2626; padding: 1rem; border-radius: 8px; border-left: 4px solid #ef4444; }
        .success { background: #ecfdf5; color: #059669; padding: 1rem; border-radius: 8px; border-left: 4px solid #10b981; text-align: center; font-weight: 500; }
        .btn { padding: 0.5rem 0.75rem; border-radius: 6px; font-weight: 500; text-decoration: none; display: inline-block; font-size: 0.875rem; transition: all 0.2s; border: none; cursor: pointer; }
        .btn-primary { background: #3b82f6; color: white; }
        .btn-success { background: #10b981; color: white; }
        .btn-danger { background: #ef4444; color: white; }
        .btn:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
        .search-input { background: #f8fafc; border: 1px solid #d1d5db; }
        .search-input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
        .no-results { @apply px-4 py-8 text-center text-gray-500; }
        .pagination {
            @apply flex justify-center items-center space-x-2 mt-6 p-4 rounded-lg bg-white shadow-sm border border-gray-200;
        }
        .btn-pagination {
            @apply inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-gray-700 bg-white rounded-md border border-gray-300 hover:bg-gray-50 transition-colors;
            min-width: 40px; height: 40px;
        }
        .btn-pagination.active {
            @apply bg-blue-500 text-white border-blue-500 hover:bg-blue-600;
        }
        .btn-pagination:disabled {
            @apply opacity-50 cursor-not-allowed bg-gray-100 text-gray-400;
        }
        .ellipsis { @apply mx-2 text-gray-400; }
        .page-info { @apply text-sm text-gray-600 bg-white px-4 py-2 rounded-md border border-gray-200; }
        .delete-form { display: inline; }
        .search-group { @apply flex gap-2; }
        .apply-btn { @apply bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md font-medium transition-colors; }
        @media (max-width: 768px) {
            .table { font-size: 0.875rem; }
            .btn { padding: 0.375rem 0.625rem; font-size: 0.75rem; }
            .pagination { @apply flex-wrap space-x-2 space-y-2 justify-center; }
            .btn-pagination { @apply px-2 py-2 text-xs; }
            .search-group { @apply flex-col w-full; }
            .search-input { @apply w-full; }
        }
        @media (min-width: 769px) { .content { margin-left: 250px; } }
    </style>
</head>
<body>
<div id="content" class="content p-6 min-h-screen">
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-md z-50">
        <div class="logo text-xl font-semibold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-sm mx-4">
            <input type="text" placeholder="Quick search..." class="w-full p-2 rounded-md bg-gray-800 text-white placeholder-gray-400" id="globalSearch">
        </div>
        <div class="right-nav flex items-center gap-3">
            <button class="p-2 rounded-full hover:bg-gray-700 transition-colors"><i class="fas fa-bell text-lg"></i></button>
            <div class="profile flex items-center gap-2 p-2 rounded-full hover:bg-gray-700 transition-colors">
                <img src="https://via.placeholder.com/32" class="w-8 h-8 rounded-full">
                <span class="text-sm">Admin</span>
            </div>
        </div>
    </nav>
    <div class="max-w-7xl mx-auto my-6">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="p-6 border-b border-gray-200">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <h2 class="text-2xl font-bold text-gray-900">Landing Pages</h2>
                    <a href="landingcreation.php" class="btn btn-primary">
                        <i class="fas fa-plus mr-1"></i>Add New
                    </a>
                </div>
            </div>
            <div class="p-6">
                <?php if ($success): ?>
                    <div class="success mb-6"><?php echo htmlspecialchars($success); ?></div>
                <?php endif; ?>
                <?php if (!empty($errors)): ?>
                    <div class="error mb-6">
                        <ul class="list-disc pl-6 space-y-1">
                            <?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
                <?php if (!empty($landings)): ?>
                    <div class="table-container mb-6">
                        <table class="table w-full">
                            <thead>
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500">ID</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500">Landing Name</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500">Created</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-500">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="tableBody">
                                <?php foreach ($landings as $row): ?>
                                    <tr>
                                        <td class="px-4 py-3 text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['id'] ?? 'N/A'); ?></td>
                                        <td class="px-4 py-3 text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['landing_name']); ?></td>
                                        <td class="px-4 py-3 text-sm text-gray-500"><?php echo htmlspecialchars($row['created']); ?></td>
                                        <td class="px-4 py-3 text-center">
                                            <div class="flex justify-center space-x-2">
                                                <a href="../landing.php?landing_name=<?php echo urlencode($row['landing_name']); ?>" class="btn btn-primary" target="_blank" title="Visit">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="manage_landing.php?id=<?php echo $row['id']; ?>" class="btn btn-success" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form method="POST" class="delete-form" onsubmit="return confirm('Are you sure you want to delete this landing page?');">
                                                    <input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
                                                    <button type="submit" class="btn btn-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="page-info flex flex-col sm:flex-row justify-between items-center px-4 py-3 bg-gray-50 rounded-b-lg">
                        <span class="text-sm text-gray-600">Showing <?php echo (($current_page - 1) * $items_per_page + 1); ?> to <?php echo min($current_page * $items_per_page, $total_items); ?> of <?php echo $total_items; ?> landing pages.</span>
                        <span class="text-sm text-gray-600 mt-2 sm:mt-0" id="searchInfo">Page <?php echo $current_page; ?> of <?php echo $total_pages; ?></span>
                    </div>
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Pagination" class="pagination">
                            <?php if ($current_page > 1): ?>
                                <a href="?page=<?php echo $current_page - 1; ?>" class="btn-pagination" title="Previous Page">
                                    <i class="fas fa-chevron-left"></i> Prev
                                </a>
                            <?php else: ?>
                                <span class="btn-pagination disabled" title="Previous Page">
                                    <i class="fas fa-chevron-left"></i> Prev
                                </span>
                            <?php endif; ?>
                            <?php
                            $start_page = max(1, $current_page - 2);
                            $end_page = min($total_pages, $current_page + 2);
                            if ($start_page > 1): ?>
                                <a href="?page=1" class="btn-pagination" title="Go to Page 1">1</a>
                                <?php if ($start_page > 2): ?><span class="ellipsis">...</span><?php endif; ?>
                            <?php endif;
                            for ($i = $start_page; $i <= $end_page; $i++): ?>
                                <a href="?page=<?php echo $i; ?>" class="btn-pagination <?php echo $i === $current_page ? 'active' : ''; ?>" title="Go to Page <?php echo $i; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php endfor;
                            if ($end_page < $total_pages): ?>
                                <?php if ($end_page < $total_pages - 1): ?><span class="ellipsis">...</span><?php endif; ?>
                                <a href="?page=<?php echo $total_pages; ?>" class="btn-pagination" title="Go to Page <?php echo $total_pages; ?>"><?php echo $total_pages; ?></a>
                            <?php endif; ?>
                            <?php if ($current_page < $total_pages): ?>
                                <a href="?page=<?php echo $current_page + 1; ?>" class="btn-pagination" title="Next Page">
                                    Next <i class="fas fa-chevron-right"></i>
                                </a>
                            <?php else: ?>
                                <span class="btn-pagination disabled" title="Next Page">
                                    Next <i class="fas fa-chevron-right"></i>
                                </span>
                            <?php endif; ?>
                        </nav>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="text-center py-12">
                        <i class="fas fa-file-alt text-6xl text-gray-300 mb-4"></i>
                        <p class="text-lg text-gray-500">No landing pages yet. <a href="landingcreation.php" class="text-blue-600 hover:underline font-medium">Create your first one!</a></p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<script>
const landings = <?php echo json_encode($landings); ?>;
const tableBody = document.getElementById('tableBody');
const globalSearch = document.getElementById('globalSearch');
const searchInfo = document.getElementById('searchInfo');
let timeout; // For debounce
function filterTable(query) {
    if (!landings || landings.length === 0) return;
    const filtered = landings.filter(row =>
        (row.landing_name || '').toLowerCase().includes(query.toLowerCase().trim())
    );
    const rowHtml = filtered.length > 0
        ? filtered.map(row => `
            <tr>
                <td class="px-4 py-3 text-sm font-medium text-gray-900">${row.id || 'N/A'}</td>
                <td class="px-4 py-3 text-sm font-medium text-gray-900">${(row.landing_name || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
                <td class="px-4 py-3 text-sm text-gray-500">${row.created || 'N/A'}</td>
                <td class="px-4 py-3 text-center">
                    <div class="flex justify-center space-x-2">
                        <a href="landing.php?landing_name=${encodeURIComponent(row.landing_name || '')}" class="btn btn-primary" target="_blank" title="Visit"><i class="fas fa-eye"></i></a>
                        <a href="manage_landing.php?id=${row.id}" class="btn btn-success" title="Edit"><i class="fas fa-edit"></i></a>
                        <form method="POST" class="delete-form" onsubmit="return confirm('Are you sure you want to delete this landing page?');">
                            <input type="hidden" name="delete_id" value="${row.id}">
                            <button type="submit" class="btn btn-danger" title="Delete"><i class="fas fa-trash"></i></button>
                        </form>
                    </div>
                </td>
            </tr>
        `).join('')
        : '<tr class="no-results"><td colspan="4" class="py-8">No results found for "<strong>' + query + '</strong>". Try another search.</td></tr>';
    tableBody.innerHTML = rowHtml;
    searchInfo.textContent = `Showing ${filtered.length} results on this page`;
}
// Debounce function for better performance (for global search)
function debounceSearch(input, delay = 300) {
    clearTimeout(timeout);
    timeout = setTimeout(() => filterTable(input.value), delay);
}
// Attach to global search only
globalSearch.addEventListener('input', (e) => debounceSearch(e.target));
</script>
<?php include "include/footer.php"; $conn->close(); ?>
</body>
</html>