<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure this path jumps up from public/admin/ to the root for config
require_once __DIR__ . '/../config/config.php';

// Auth Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

// =========================================================
// IMAGE PROCESSING ENGINE (Resize & Compress)
// =========================================================
function processAndSaveImage($fileArray, $uploadDir) {
    if (!isset($fileArray['error']) || $fileArray['error'] !== UPLOAD_ERR_OK) return false;

    $tmpName = $fileArray['tmp_name'];
    $fileType = mime_content_type($tmpName);
    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    
    if (!in_array($fileType, $allowedTypes)) return false;

    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    $fileName = 'article_' . time() . '_' . rand(100,999) . '.jpg';
    $destination = $uploadDir . '/' . $fileName;

    switch ($fileType) {
        case 'image/jpeg': $sourceImage = imagecreatefromjpeg($tmpName); break;
        case 'image/png':  $sourceImage = imagecreatefrompng($tmpName); break;
        case 'image/webp': $sourceImage = imagecreatefromwebp($tmpName); break;
        case 'image/gif':  $sourceImage = imagecreatefromgif($tmpName); break;
        default: return false;
    }

    list($origWidth, $origHeight) = getimagesize($tmpName);
    $targetWidth = 800;
    if ($origWidth > $targetWidth) {
        $ratio = $targetWidth / $origWidth;
        $targetHeight = round($origHeight * $ratio);
    } else {
        $targetWidth = $origWidth;
        $targetHeight = $origHeight;
    }

    $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
    $white = imagecolorallocate($targetImage, 255, 255, 255);
    imagefill($targetImage, 0, 0, $white);
    imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $origWidth, $origHeight);
    imagejpeg($targetImage, $destination, 80);

    imagedestroy($sourceImage);
    imagedestroy($targetImage);

    return 'uploads/news/' . $fileName;
}

$upload_directory = __DIR__ . '/../uploads/news';

// =========================================================
// WARNING-PROOF CRUD OPERATIONS (CREATE, UPDATE, DELETE)
// =========================================================

// 1. CREATE: Publish or Schedule New Article
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['publish_news'])) {
    $title         = trim($_POST['title'] ?? '');
    $category      = trim($_POST['category'] ?? 'General');
    $content       = trim($_POST['content'] ?? '');
    $publish_date  = trim($_POST['publish_date'] ?? '');
    $featured_img  = ''; 
    
    if(empty($publish_date)) $publish_date = date('Y-m-d H:i:s');

    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
        $processed_path = processAndSaveImage($_FILES['featured_image'], $upload_directory);
        if ($processed_path) $featured_img = $processed_path;
        else $error_msg = "Image upload failed. Invalid file type or corrupted image.";
    }

    if (!empty($title) && !empty($content) && empty($error_msg)) {
        $stmt = $pdo->prepare("INSERT INTO news (title, category, content, featured_image, publish_date) VALUES (?, ?, ?, ?, ?)");
        if ($stmt->execute([$title, $category, $content, $featured_img, $publish_date])) {
            $success_msg = "News article scheduled/published successfully!";
        } else {
            $error_msg = "Database error: Failed to publish article.";
        }
    } elseif (empty($title) || empty($content)) {
        $error_msg = "Action blocked: Both Title and Content are required.";
    }
}

// 2. UPDATE: Edit Existing Article
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_news'])) {
    $id            = intval($_POST['edit_id'] ?? 0);
    $title         = trim($_POST['title'] ?? '');
    $category      = trim($_POST['category'] ?? 'General');
    $content       = trim($_POST['content'] ?? '');
    $publish_date  = trim($_POST['publish_date'] ?? '');
    $featured_img  = trim($_POST['existing_image'] ?? ''); 

    if(empty($publish_date)) $publish_date = date('Y-m-d H:i:s');

    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
        $processed_path = processAndSaveImage($_FILES['featured_image'], $upload_directory);
        if ($processed_path) $featured_img = $processed_path; 
        else $error_msg = "Image upload failed. Invalid file type or corrupted image.";
    }

    if ($id > 0 && !empty($title) && !empty($content) && empty($error_msg)) {
        $stmt = $pdo->prepare("UPDATE news SET title=?, category=?, content=?, featured_image=?, publish_date=? WHERE id=?");
        if ($stmt->execute([$title, $category, $content, $featured_img, $publish_date, $id])) {
            $success_msg = "News article updated successfully!";
        } else {
            $error_msg = "Database error: Failed to update article.";
        }
    } elseif (empty($title) || empty($content)) {
        $error_msg = "Action blocked: Invalid data provided for update.";
    }
}

// 3. DELETE: Remove Article Permanently
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_news'])) {
    $article_id = intval($_POST['delete_id'] ?? 0);
    if ($article_id > 0) {
        $delete_stmt = $pdo->prepare("DELETE FROM news WHERE id = ?");
        if ($delete_stmt->execute([$article_id])) {
            $success_msg = "Article permanently deleted from the archive.";
        } else {
            $error_msg = "Database error: Could not delete article.";
        }
    }
}

// =========================================================
// DATA FETCHING, PAGINATION & EDIT MODE LOGIC
// =========================================================

$edit_mode = false;
$edit_data = [];
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $stmt = $pdo->prepare("SELECT * FROM news WHERE id = ?");
    $stmt->execute([intval($_GET['edit'])]);
    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$edit_data) {
        $edit_mode = false;
        $error_msg = "The requested article could not be found.";
    }
}

// PAGINATION SETUP
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$total_records = $pdo->query("SELECT COUNT(*) FROM news")->fetchColumn();
$total_pages = ceil($total_records / $limit) ?: 1;

$stmt = $pdo->prepare("SELECT * FROM news ORDER BY COALESCE(publish_date, created_at) DESC, id DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);

$current_time = strtotime(date('Y-m-d H:i:s'));

// Count scheduled vs live
$live_count = 0;
$scheduled_count = 0;
foreach ($articles as $art) {
    $art_time = strtotime($art['publish_date'] ?? $art['created_at']);
    if ($art_time > $current_time) $scheduled_count++;
    else $live_count++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Content CMS</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .line-clamp-2 {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;  
            overflow: hidden;
        }
        .line-clamp-1 {
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Content CMS</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Publish, schedule, and manage articles.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-4 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Total Articles</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total_records; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Live</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $live_count; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Scheduled</span>
                <span class="text-2xl font-extrabold text-amber-600 dark:text-amber-500 mt-1 block"><?php echo $scheduled_count; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">With Images</span>
                <?php 
                    $with_images = 0;
                    foreach ($articles as $art) { if (!empty($art['featured_image'])) $with_images++; }
                ?>
                <span class="text-2xl font-extrabold text-cyan-600 dark:text-cyan-400 mt-1 block"><?php echo $with_images; ?></span>
            </div>
        </div>

        <!-- ========== MAIN CONTENT ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- FORM CARD -->
            <div class="lg:col-span-1">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300 sticky top-6">
                    <div class="flex items-center justify-between border-b border-slate-200 dark:border-slate-800 pb-3 mb-5">
                        <h3 class="font-bold text-lg text-slate-900 dark:text-white">
                            <?php echo $edit_mode ? '✏️ Edit Article' : '📝 Draft New Article'; ?>
                        </h3>
                        <?php if($edit_mode): ?>
                            <a href="news-cms.php" class="text-[10px] bg-slate-200 text-slate-600 dark:bg-slate-800 dark:text-gray-400 px-3 py-1.5 rounded-lg font-bold uppercase tracking-wider hover:bg-slate-300 dark:hover:bg-slate-700 transition">Cancel</a>
                        <?php endif; ?>
                    </div>

                    <form action="news-cms.php" method="POST" enctype="multipart/form-data" class="space-y-5">
                        <?php if($edit_mode): ?>
                            <input type="hidden" name="edit_id" value="<?php echo $edit_data['id']; ?>">
                            <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($edit_data['featured_image'] ?? ''); ?>">
                        <?php endif; ?>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Article Headline</label>
                            <input type="text" name="title" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['title'] ?? '') : ''; ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Category</label>
                            <select name="category" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                                <option value="Platform News" <?php echo ($edit_mode && ($edit_data['category'] ?? '') === 'Platform News') ? 'selected' : ''; ?>>Platform News</option>
                                <option value="AI Predictions" <?php echo ($edit_mode && ($edit_data['category'] ?? '') === 'AI Predictions') ? 'selected' : ''; ?>>AI Predictions</option>
                                <option value="Bet of the Day" <?php echo ($edit_mode && ($edit_data['category'] ?? '') === 'Bet of the Day') ? 'selected' : ''; ?>>Bet of the Day</option>
                                <option value="Betting Predictions" <?php echo ($edit_mode && ($edit_data['category'] ?? '') === 'Betting Predictions') ? 'selected' : ''; ?>>Betting Predictions</option>
                                <option value="General" <?php echo ($edit_mode && ($edit_data['category'] ?? '') === 'General') ? 'selected' : ''; ?>>General</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold flex justify-between">
                                <span>Featured Image</span>
                                <?php if($edit_mode && !empty($edit_data['featured_image'])): ?>
                                    <span class="text-emerald-500 text-[9px]">Uploaded</span>
                                <?php endif; ?>
                            </label>
                            <div class="relative w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-sm transition-all">
                                <input type="file" name="featured_image" accept="image/png, image/jpeg, image/webp" class="text-slate-500 w-full cursor-pointer file:cursor-pointer file:mr-4 file:py-1.5 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-emerald-50 file:text-emerald-700 dark:file:bg-emerald-500/10 dark:file:text-emerald-400 hover:file:bg-emerald-100 transition">
                            </div>
                            <p class="text-[8px] text-slate-400 dark:text-gray-500 mt-1">Max width 800px, auto-compressed</p>
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Publish Date</label>
                            <?php 
                                $schedule_val = '';
                                if($edit_mode && !empty($edit_data['publish_date'])) {
                                    $schedule_val = date('Y-m-d\TH:i', strtotime($edit_data['publish_date']));
                                }
                            ?>
                            <input type="datetime-local" name="publish_date" value="<?php echo $schedule_val; ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1.5 tracking-wider uppercase font-bold">Content</label>
                            <textarea name="content" rows="8" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all resize-y"><?php echo $edit_mode ? htmlspecialchars($edit_data['content'] ?? '') : ''; ?></textarea>
                        </div>

                        <?php if($edit_mode): ?>
                            <button type="submit" name="update_news" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-blue-500/20 text-xs tracking-wider uppercase">💾 Update Article</button>
                        <?php else: ?>
                            <button type="submit" name="publish_news" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-emerald-500/20 text-xs tracking-wider uppercase">📤 Publish Article</button>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <!-- TABLE CARD -->
            <div class="lg:col-span-2">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-4 sm:p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-5 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Published & Scheduled Content</h3>
                    
                    <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                        <table class="w-full text-left text-sm border-collapse min-w-[700px]">
                            <thead>
                                <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-[10px] tracking-wider uppercase font-black">
                                    <th class="py-3 px-2">Headline & Category</th>
                                    <th class="py-3 px-2 text-center">Status / Date</th>
                                    <th class="py-3 px-2 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300 text-xs">
                                <?php foreach($articles as $art): 
                                    $art_time = strtotime($art['publish_date'] ?? $art['created_at']);
                                    $is_scheduled = $art_time > $current_time;
                                    $display_date = date("d M Y H:i", $art_time);
                                    $has_image = !empty($art['featured_image']);
                                ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition group">
                                    
                                    <td class="py-3 px-2">
                                        <div class="flex items-start gap-3">
                                            <?php if($has_image): ?>
                                                <div class="w-12 h-12 flex-shrink-0 bg-slate-200 dark:bg-slate-800 rounded-lg overflow-hidden border border-slate-300 dark:border-slate-700 mt-0.5">
                                                    <img src="<?php echo SITE_URL . '/' . htmlspecialchars($art['featured_image'] ?? ''); ?>" class="w-full h-full object-cover" alt="Preview">
                                                </div>
                                            <?php else: ?>
                                                <div class="w-12 h-12 flex-shrink-0 bg-slate-100 dark:bg-slate-800/50 rounded-lg flex items-center justify-center border border-slate-200 dark:border-slate-800 text-slate-400 mt-0.5">
                                                    📄
                                                </div>
                                            <?php endif; ?>
                                            <div class="flex-1 min-w-0">
                                                <div class="font-bold text-slate-900 dark:text-white text-sm leading-tight line-clamp-2"><?php echo htmlspecialchars($art['title'] ?? ''); ?></div>
                                                <span class="inline-block bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-gray-400 text-[9px] px-2 py-0.5 rounded uppercase tracking-wider font-bold mt-0.5">
                                                    <?php echo htmlspecialchars($art['category'] ?? 'General'); ?>
                                                </span>
                                                <div class="text-[9px] text-slate-400 dark:text-gray-500 line-clamp-1 leading-tight mt-0.5">
                                                    <?php echo htmlspecialchars(strip_tags($art['content'] ?? '')); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="py-3 px-2 text-center">
                                        <div class="flex flex-col items-center gap-1">
                                            <?php if($is_scheduled): ?>
                                                <span class="bg-amber-50 text-amber-600 border border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/30 text-[9px] px-2.5 py-0.5 rounded-full font-black uppercase tracking-wider">Scheduled</span>
                                            <?php else: ?>
                                                <span class="bg-emerald-50 text-emerald-600 border border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/30 text-[9px] px-2.5 py-0.5 rounded-full font-black uppercase tracking-wider">Live</span>
                                            <?php endif; ?>
                                            <span class="text-[9px] text-slate-500 dark:text-gray-400 font-mono"><?php echo $display_date; ?></span>
                                        </div>
                                    </td>

                                    <td class="py-3 px-2 text-right">
                                        <div class="flex items-center justify-end gap-1.5">
                                            <a href="news-cms.php?edit=<?php echo $art['id']; ?>" class="bg-blue-50 text-blue-600 border border-blue-200 hover:bg-blue-100 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/30 dark:hover:bg-blue-500/20 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition">✏️</a>
                                            
                                            <form action="news-cms.php" method="POST" onsubmit="return confirm('Delete this article?');" class="inline">
                                                <input type="hidden" name="delete_id" value="<?php echo $art['id']; ?>">
                                                <button type="submit" name="delete_news" class="bg-rose-50 text-rose-600 border border-rose-200 hover:bg-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/30 dark:hover:bg-rose-500/20 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition">🗑️</button>
                                            </form>
                                        </div>
                                    </td>

                                </tr>
                                <?php endforeach; ?>
                                
                                <?php if(empty($articles)): ?>
                                <tr>
                                    <td colspan="3" class="py-12 text-center text-slate-400 dark:text-gray-500 text-xs font-medium uppercase tracking-widest">
                                        No articles found.
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($total_pages > 1): ?>
                        <div class="flex items-center justify-center pt-5 mt-4 border-t border-slate-200 dark:border-slate-800">
                            <div class="flex space-x-1">
                                <?php if ($page > 1): ?>
                                    <a href="?page=<?php echo $page - 1; ?>" class="px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 hover:text-slate-900 dark:hover:text-white transition bg-slate-100 dark:bg-slate-800 rounded-lg">Prev</a>
                                <?php endif; ?>
                                
                                <span class="px-4 py-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-gray-500"><?php echo $page; ?> / <?php echo $total_pages; ?></span>
                                
                                <?php if ($page < $total_pages): ?>
                                    <a href="?page=<?php echo $page + 1; ?>" class="px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 hover:text-slate-900 dark:hover:text-white transition bg-slate-100 dark:bg-slate-800 rounded-lg">Next</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </main>
</body>
</html>