<?php
session_start();
include '../db_config.php';
include '../functions.php';

check_login();
check_role('admin');

$msg = '';
$error = '';

// Add Category
if(isset($_POST['add_cat'])) {
    $new_cat = sanitize_input($_POST['category_name']);
    if(!empty($new_cat)) {
        // Check duplicate
        $check = $conn->query("SELECT id FROM job_categories WHERE name='$new_cat'");
        if($check->num_rows > 0) {
            $error = "Category '$new_cat' already exists.";
        } else {
            if($conn->query("INSERT INTO job_categories (name) VALUES ('$new_cat')")) {
                $msg = "Category '$new_cat' added successfully.";
            } else {
                $error = "Error adding category: " . $conn->error;
            }
        }
    } else {
        $error = "Category name cannot be empty.";
    }
}

// Delete Category
if(isset($_POST['delete_cat'])) {
    $cat_id = intval($_POST['cat_id']);
    // Optional: Check if category is in use before deleting? For now, just delete.
    // If it's in use, existing records will keep the old string value unless we migrate to ID relations.
    // Since current system uses string names in other tables, deleting here won't break foreign keys but might leave orphan names.
    // Warning: existing records with this category will remain as is (strings).
    
    $stmt = $conn->prepare("DELETE FROM job_categories WHERE id=?");
    $stmt->bind_param("i", $cat_id);
    if($stmt->execute()) {
        $msg = "Category deleted.";
    } else {
        $error = "Error deleting category.";
    }
    $stmt->close();
}

$cats = $conn->query("SELECT * FROM job_categories ORDER BY name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Categories | Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
         /* Custom scrollbar for better look in dark mode */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #1e293b; 
        }
        ::-webkit-scrollbar-thumb {
            background: #475569; 
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #64748b; 
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">

    <!-- Navbar -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <a href="<?= BASE_URL ?>/index.php" class="text-2xl font-bold italic tracking-tighter text-white">
                    Work For <span class="text-indigo-400">Sri Lanka</span>
                    <span class="text-xs font-normal text-white bg-indigo-600 px-2 py-0.5 rounded ml-2 align-middle border border-indigo-500/50">Admin Panel</span>
                </a>
                <div class="flex items-center gap-6">
                    <span class="text-sm font-medium text-slate-400 hidden md:inline">Logged in as: <span class="text-indigo-400 font-mono"><?=$_SESSION['username']?></span></span>
                    <a href="../logout.php" class="text-slate-400 hover:text-red-400 font-medium transition text-sm flex items-center">
                        <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header Section -->
    <div class="relative bg-slate-900 py-10 px-4 border-b border-slate-800">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20 pointer-events-none"></div>
        
        <div class="max-w-5xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Job Categories</h1>
                <p class="text-slate-400">Add or remove job categories available on the platform.</p>
            </div>
             <a href="dashboard.php" class="bg-slate-800 hover:bg-slate-700 text-white px-5 py-2.5 rounded-xl font-bold transition flex items-center border border-slate-700 hover:border-indigo-500 hover:text-indigo-400 shadow-sm text-sm group">
                <i data-lucide="arrow-left" class="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-5xl mx-auto px-4 pb-20 pt-8">
        
        <?php if($msg): ?>
            <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-fade-in-down">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Success!</span> <?=$msg?>
            </div>
        <?php endif; ?>
        <?php if($error): ?>
             <div class="bg-red-500/10 border border-red-500/20 text-red-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-pulse">
                <i data-lucide="alert-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <div><?=$error?></div>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            
            <!-- List Categories -->
            <div class="glass-panel rounded-3xl shadow-xl overflow-hidden h-[600px] flex flex-col">
                <div class="p-6 border-b border-slate-700/50 bg-slate-800/30 flex justify-between items-center flex-shrink-0">
                    <h2 class="text-lg font-bold text-white flex items-center">
                        <i data-lucide="list" class="w-5 h-5 mr-2 text-indigo-400"></i> Existing Categories
                    </h2>
                    <span class="bg-indigo-500/10 text-indigo-400 text-xs font-bold px-3 py-1 rounded-full border border-indigo-500/20"><?=$cats->num_rows?> Total</span>
                </div>
                <div class="overflow-y-auto flex-grow p-0">
                    <table class="w-full text-left text-sm text-slate-300">
                        <tbody class="divide-y divide-slate-700/50">
                            <?php while($c = $cats->fetch_assoc()): ?>
                            <tr class="hover:bg-slate-800/30 transition group">
                                <td class="px-6 py-3 font-medium text-slate-200 flex items-center justify-between">
                                    <span><?=$c['name']?></span>
                                    
                                    <?php if($c['name'] !== 'Other'): ?>
                                    <form method="post" onsubmit="return confirm('Delete this category?');" class="opacity-0 group-hover:opacity-100 transition">
                                        <input type="hidden" name="cat_id" value="<?=$c['id']?>">
                                        <button type="submit" name="delete_cat" class="text-red-400 hover:text-red-300 p-2 rounded hover:bg-red-500/10 transition">
                                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Add New -->
            <div>
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden sticky top-24">
                     <div class="p-6 border-b border-slate-700/50 bg-slate-800/30">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="plus-circle" class="w-5 h-5 mr-2 text-emerald-400"></i> Add New Category
                        </h2>
                    </div>
                    <form method="post" class="p-6 space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Category Name</label>
                            <input type="text" name="category_name" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="e.g. Web Developer">
                        </div>
                        <button type="submit" name="add_cat" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center justify-center">
                            <i data-lucide="plus" class="w-5 h-5 mr-2"></i> Add Category
                        </button>
                    </form>
                    
                    <div class="p-6 bg-yellow-500/5 border-t border-yellow-500/10">
                        <div class="flex items-start text-yellow-500 text-sm">
                            <i data-lucide="info" class="w-5 h-5 mr-2 flex-shrink-0 mt-0.5"></i>
                            <p class="text-yellow-200/80">New categories will immediately appear in search filters and registration forms.</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-8 text-center text-slate-500 text-sm mt-12">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <script>
        lucide.createIcons();
    </script>
</body>
</html>
