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

// Stats
$worker_count = $conn->query("SELECT COUNT(*) as count FROM employee_login WHERE role='employee'")->fetch_assoc()['count'];
$employer_count = $conn->query("SELECT COUNT(*) as count FROM employer_login WHERE role='employer'")->fetch_assoc()['count'];
$job_count = $conn->query("SELECT COUNT(*) as count FROM jobs")->fetch_assoc()['count'];
$app_count = $conn->query("SELECT COUNT(*) as count FROM applications")->fetch_assoc()['count'];

$pending_approvals = $conn->query("SELECT COUNT(*) as count FROM employee_details WHERE status='Pending'")->fetch_assoc()['count'];
$pending_employers = $conn->query("SELECT COUNT(*) as count FROM employer_details WHERE status='Pending'")->fetch_assoc()['count'];
$pending_jobs = $conn->query("SELECT COUNT(*) as count FROM jobs WHERE status='Pending'")->fetch_assoc()['count'];

// Category distribution
$cats = $conn->query("SELECT job_category, COUNT(*) as count FROM employee_details GROUP BY job_category ORDER BY count DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | Work For Sri Lanka</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);
        }
        @keyframes pop {
            0% { transform: scale(0.95); opacity: 0; }
            70% { transform: scale(1.05); opacity: 1; }
            100% { transform: scale(1); opacity: 1; }
        }
        .brand-pop {
            transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
            display: inline-block;
        }
        .brand-pop:hover {
            transform: scale(1.15);
        }
    </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">
                <div class="flex-shrink-0 flex items-center gap-3">
                    <a href="<?= BASE_URL ?>/index.php" class="brand-pop block">
                        <img src="../assets/images/logo_banner.png" alt="Department of Manpower and Employment" class="h-10 md:h-12 object-contain">
                    </a>
                    <div class="h-8 w-px bg-slate-700 mx-2 hidden md:block"></div>
                    <a href="<?= BASE_URL ?>/index.php" class="text-xl md:text-2xl font-bold italic tracking-tighter text-white brand-pop block origin-left">
                        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">Admin Panel</span>
                    </a>
                </div>
                <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>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 py-8 pb-20">
        
        <div class="flex flex-col md:flex-row justify-between items-center mb-10 w-full">
            <div class="flex flex-wrap gap-3 mt-4 md:mt-0">
                <a href="manage_dme.php" class="bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-4 py-2.5 rounded-xl font-semibold transition flex items-center shadow-sm text-sm">
                    <i data-lucide="shield" class="w-4 h-4 mr-2 text-indigo-400"></i> Manage DMEs
                </a>
                <a href="manage_employees.php" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2.5 rounded-xl font-bold transition shadow-lg shadow-indigo-600/20 flex items-center text-sm">
                    <i data-lucide="users" class="w-4 h-4 mr-2"></i> Manage Workers
                </a>
                <a href="manage_employers.php" class="bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-4 py-2.5 rounded-xl font-semibold transition flex items-center shadow-sm text-sm">
                    <i data-lucide="building-2" class="w-4 h-4 mr-2 text-indigo-400"></i> Manage Employers
                </a>
                <a href="manage_jobs.php" class="bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-4 py-2.5 rounded-xl font-semibold transition flex items-center shadow-sm text-sm">
                    <i data-lucide="briefcase" class="w-4 h-4 mr-2 text-indigo-400"></i> Manage Jobs
                    <?php if($pending_jobs > 0): ?>
                        <span class="ml-2 bg-red-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full shadow-sm"><?=$pending_jobs?></span>
                    <?php endif; ?>
                </a>
                <div class="flex gap-3 w-full md:w-auto">
                    <a href="manage_locations.php" class="bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-4 py-2.5 rounded-xl font-semibold transition flex items-center shadow-sm text-sm flex-1 md:flex-none justify-center">
                        <i data-lucide="map-pin" class="w-4 h-4 mr-2 text-indigo-400"></i> Locations
                    </a>
                    <a href="manage_categories.php" class="bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-4 py-2.5 rounded-xl font-semibold transition flex items-center shadow-sm text-sm flex-1 md:flex-none justify-center">
                        <i data-lucide="list" class="w-4 h-4 mr-2 text-indigo-400"></i> Categories
                    </a>
                </div>
            </div>
            <div>
                <h1 class="text-3xl font-bold text-white">System Dashboard</h1>
                <p class="text-slate-400 mt-1">Real-time overview of platform activity.</p>
            </div>
        </div>

        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-6 mb-10">
            <!-- Stat Card 1 -->
            <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center">
                <div class="w-12 h-12 rounded-full bg-blue-500/10 flex items-center justify-center text-blue-400 mr-4 border border-blue-500/20">
                    <i data-lucide="briefcase" class="w-6 h-6"></i>
                </div>
                <div>
                    <div class="text-slate-400 text-xs font-bold uppercase tracking-wide">Workers</div>
                    <div class="text-2xl font-black text-white" id="stat_worker"><?=$worker_count?></div>
                </div>
            </div>
            
            <!-- Stat Card 2 -->
            <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center">
                <div class="w-12 h-12 rounded-full bg-purple-500/10 flex items-center justify-center text-purple-400 mr-4 border border-purple-500/20">
                    <i data-lucide="building-2" class="w-6 h-6"></i>
                </div>
                <div>
                    <div class="text-slate-400 text-xs font-bold uppercase tracking-wide">Employers</div>
                    <div class="text-2xl font-black text-white" id="stat_employer"><?=$employer_count?></div>
                </div>
            </div>

            <!-- Stat Card 3 -->
            <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center">
                <div class="w-12 h-12 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-400 mr-4 border border-emerald-500/20">
                    <i data-lucide="file-text" class="w-6 h-6"></i>
                </div>
                <div>
                    <div class="text-slate-400 text-xs font-bold uppercase tracking-wide">Job Posts</div>
                    <div class="text-2xl font-black text-white" id="stat_job"><?=$job_count?></div>
                </div>
            </div>
            
            <!-- Stat Card 4 (Pending Workers) -->
            <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center relative overflow-hidden group">
                <div class="absolute right-0 top-0 h-full w-1 bg-red-500/50"></div>
                <div class="w-12 h-12 rounded-full bg-red-500/10 flex items-center justify-center text-red-400 mr-4 border border-red-500/20 animate-pulse">
                    <i data-lucide="user-x" class="w-6 h-6"></i>
                </div>
                <div>
                    <div class="text-red-400 text-xs font-bold uppercase tracking-wide">Pending Users</div>
                    <div class="text-2xl font-black text-white" id="stat_pending"><?=$pending_approvals?></div>
                </div>
            </div>
            
            <!-- Stat Card 5 (Pending Employers) -->
            <a href="manage_employers.php?status=Pending" class="block col-span-1">
                <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center relative overflow-hidden group hover:bg-slate-800/50 transition">
                    <div class="absolute right-0 top-0 h-full w-1 bg-orange-500/50"></div>
                    <div class="w-12 h-12 rounded-full bg-orange-500/10 flex items-center justify-center text-orange-400 mr-4 border border-orange-500/20 animate-pulse">
                         <i data-lucide="building" class="w-6 h-6"></i>
                    </div>
                    <div>
                        <div class="text-orange-400 text-xs font-bold uppercase tracking-wide">Pending Comp.</div>
                        <div class="text-2xl font-black text-white" id="stat_pending_emp"><?=$pending_employers?></div>
                    </div>
                </div>
            </a>

            <!-- Stat Card 6 (Pending Jobs) -->
            <div class="glass-panel p-6 rounded-2xl shadow-lg border border-slate-700/50 flex items-center relative overflow-hidden group">
                <div class="absolute right-0 top-0 h-full w-1 bg-yellow-400/50"></div>
                <div class="w-12 h-12 rounded-full bg-yellow-500/10 flex items-center justify-center text-yellow-400 mr-4 border border-yellow-500/20 animate-pulse">
                     <i data-lucide="clock" class="w-6 h-6"></i>
                </div>
                <div>
                    <div class="text-yellow-400 text-xs font-bold uppercase tracking-wide">Pending Jobs</div>
                    <div class="text-2xl font-black text-white" id="stat_pending_jobs"><?=$pending_jobs?></div>
                </div>
            </div>
        </div>

        <!-- Worker Categories Table -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="lg:col-span-2 glass-panel rounded-3xl shadow-xl overflow-hidden">
                <div class="p-6 border-b border-slate-700/50 bg-slate-800/30 flex justify-between items-center">
                    <h2 class="text-lg font-bold text-white flex items-center">
                        <i data-lucide="bar-chart-2" class="w-5 h-5 mr-2 text-indigo-400"></i> Worker Distribution
                    </h2>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-sm text-slate-300">
                        <thead class="bg-slate-800/50 text-slate-400 uppercase font-semibold text-xs tracking-wider">
                            <tr>
                                <th class="px-6 py-4">Job Category</th>
                                <th class="px-6 py-4 text-right">Registered Workers</th>
                                <th class="px-6 py-4">Distribution</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700/50">
                            <?php 
                            $max_count = 0;
                            // Need to rewind logic or store in array to calculate max for bars
                            $cat_data = [];
                            while($c = $cats->fetch_assoc()) {
                                $cat_data[] = $c;
                                if($c['count'] > $max_count) $max_count = $c['count'];
                            }
                            
                            foreach($cat_data as $c): 
                                $percent = ($max_count > 0) ? ($c['count'] / $max_count) * 100 : 0;
                            ?>
                            <tr class="hover:bg-slate-800/30 transition">
                                <td class="px-6 py-4 font-medium text-slate-200"><?=$c['job_category']?></td>
                                <td class="px-6 py-4 text-right font-bold text-indigo-400"><?=$c['count']?></td>
                                <td class="px-6 py-4 w-1/3">
                                    <div class="w-full bg-slate-700 rounded-full h-1.5">
                                        <div class="bg-indigo-500 h-1.5 rounded-full shadow-[0_0_10px_rgba(99,102,241,0.5)]" style="width: <?=$percent?>%"></div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Quick Links / Info Panel -->
            <div class="space-y-6">
                <!-- System Status -->
                <div class="glass-panel rounded-3xl p-8 shadow-xl relative overflow-hidden bg-gradient-to-br from-indigo-900/40 to-slate-900/40 border border-indigo-500/20">
                    <div class="absolute top-0 right-0 -mt-4 -mr-4 w-32 h-32 bg-indigo-600 rounded-full opacity-20 blur-3xl"></div>
                    <h3 class="text-xl font-bold mb-4 text-white">System Status</h3>
                    <div class="space-y-4 relative z-10">
                        <div class="flex justify-between items-center border-b border-indigo-500/20 pb-3">
                            <span class="text-indigo-200">Database</span>
                            <span class="flex items-center text-emerald-400 font-bold text-sm"><i data-lucide="check" class="w-4 h-4 mr-1"></i> Connected</span>
                        </div>
                        <div class="flex justify-between items-center border-b border-indigo-500/20 pb-3">
                            <span class="text-indigo-200">Server Time</span>
                            <span class="text-sm font-mono text-slate-300"><?=date('H:i')?></span>
                        </div>
                        <div class="flex justify-between items-center pt-1">
                             <span class="text-indigo-200">Total Applications</span>
                             <span class="font-bold text-white text-lg"><?=$app_count?></span>
                        </div>
                    </div>
                </div>
                
                 <!-- Help / Actions -->
                <div class="glass-panel rounded-3xl p-6 shadow-xl">
                    <h3 class="text-lg font-bold text-white mb-4">Admin Actions</h3>
                    <div class="space-y-3">
                        <a href="manage_dme.php" class="block w-full p-3 bg-slate-800 hover:bg-indigo-600 hover:text-white rounded-xl transition text-sm font-medium border border-slate-700 text-slate-300">
                            Create New DME Account
                        </a>
                        <a href="<?= BASE_URL ?>/index.php" target="_blank" class="block w-full p-3 bg-slate-800 hover:bg-slate-700 hover:text-white rounded-xl transition text-sm font-medium border border-slate-700 text-slate-300">
                            View Live Site
                        </a>
                        <a href="change_password.php" class="block w-full p-3 bg-slate-800 hover:bg-slate-700 hover:text-white rounded-xl transition text-sm font-medium border border-slate-700 text-slate-300">
                             Change My Password
                        </a>
                    </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();

        function updateStats() {
            fetch('get_stats.php')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('stat_worker').innerText = data.worker_count;
                    document.getElementById('stat_employer').innerText = data.employer_count;
                    document.getElementById('stat_job').innerText = data.job_count;
                    document.getElementById('stat_pending').innerText = data.pending_approvals;
                    // Add check if element exists for pending employers to avoid console errors if API not updated yet
                    const pendingEmp = document.getElementById('stat_pending_emp');
                    if(pendingEmp && data.pending_employers !== undefined) {
                         pendingEmp.innerText = data.pending_employers;
                    }
                    const pendingJobs = document.getElementById('stat_pending_jobs');
                    if(pendingJobs && data.pending_jobs !== undefined) {
                         pendingJobs.innerText = data.pending_jobs;
                    }
                })
                .catch(err => console.error('Error fetching stats:', err));
        }
        
        // Update stats every 5 seconds
        setInterval(updateStats, 5000);
    </script>
</body>
</html>
