<?php
require_once '../config/config.php';

// Require admin login
requireRole('admin');

$pageTitle = 'Admin Dashboard - PSAU GAD';
$userId = getCurrentUserId();

// Get database connection
$db = getDB();

// Get statistics
// Total employees
$stmt = $db->query("SELECT COUNT(*) as count FROM users WHERE role = 'employee'");
$totalEmployees = $stmt->fetch()['count'];

// Gender breakdown
$stmt = $db->query("
    SELECT 
        ep.gender,
        COUNT(*) as count
    FROM employee_profiles ep
    JOIN users u ON ep.user_id = u.user_id
    WHERE u.role = 'employee'
    GROUP BY ep.gender
");
$genderStats = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$maleCount = $genderStats['Male'] ?? 0;
$femaleCount = $genderStats['Female'] ?? 0;

// Category breakdown
$stmt = $db->query("
    SELECT 
        ep.category,
        ep.gender,
        COUNT(*) as count
    FROM employee_profiles ep
    JOIN users u ON ep.user_id = u.user_id
    WHERE u.role = 'employee'
    GROUP BY ep.category, ep.gender
");
$categoryStats = $stmt->fetchAll();

// Upcoming activities
$stmt = $db->query("
    SELECT COUNT(*) as count 
    FROM activities 
    WHERE activity_date >= CURDATE() AND is_active = 1
");
$upcomingActivities = $stmt->fetch()['count'];

// Pending account approvals
$stmt = $db->query("
    SELECT COUNT(*) as count 
    FROM users 
    WHERE is_approved = 0 AND is_active = 1
");
$pendingAccounts = $stmt->fetch()['count'];

// Pending registration approvals
$stmt = $db->query("
    SELECT COUNT(*) as count 
    FROM activity_registrations 
    WHERE status = 'pending'
");
$pendingRegistrations = $stmt->fetch()['count'];

// Total activities
$stmt = $db->query("SELECT COUNT(*) as count FROM activities");
$totalActivities = $stmt->fetch()['count'];

// Get upcoming activities list
$stmt = $db->query("
    SELECT 
        a.*,
        COUNT(ar.registration_id) as registration_count
    FROM activities a
    LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
    WHERE a.activity_date >= CURDATE() AND a.is_active = 1
    GROUP BY a.activity_id
    ORDER BY a.activity_date ASC
    LIMIT 5
");
$upcomingActivitiesList = $stmt->fetchAll();

// Get recent registrations
$stmt = $db->query("
    SELECT 
        ar.*,
        a.title as activity_title,
        ep.first_name,
        ep.last_name
    FROM activity_registrations ar
    JOIN activities a ON ar.activity_id = a.activity_id
    JOIN employee_profiles ep ON ar.user_id = ep.user_id
    ORDER BY ar.registration_date DESC
    LIMIT 5
");
$recentRegistrations = $stmt->fetchAll();

// Prepare data for charts
$categoryData = [];
foreach ($categoryStats as $stat) {
    if (!isset($categoryData[$stat['category']])) {
        $categoryData[$stat['category']] = ['Male' => 0, 'Female' => 0, 'Other' => 0];
    }
    $categoryData[$stat['category']][$stat['gender']] = $stat['count'];
}

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">
                <i class="fas fa-tachometer-alt text-admin mr-3"></i>
                Admin Dashboard
            </h1>
            <p class="text-gray-600">Welcome to the GAD Information System administration panel</p>
        </div>

        <!-- Quick Action Buttons -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
            <a href="activities.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition text-center group">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:bg-blue-200 transition">
                    <i class="fas fa-calendar-alt text-blue-500 text-2xl"></i>
                </div>
                <h3 class="font-semibold text-gray-900 mb-1">Upcoming Activities</h3>
                <p class="text-3xl font-bold text-blue-500"><?php echo $upcomingActivities; ?></p>
            </a>

            <a href="reports.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition text-center group">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:bg-green-200 transition">
                    <i class="fas fa-file-alt text-green-500 text-2xl"></i>
                </div>
                <h3 class="font-semibold text-gray-900 mb-1">GAD Reports</h3>
                <p class="text-sm text-gray-600">Generate Reports</p>
            </a>

            <a href="attendance.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition text-center group">
                <div class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:bg-purple-200 transition">
                    <i class="fas fa-qrcode text-purple-500 text-2xl"></i>
                </div>
                <h3 class="font-semibold text-gray-900 mb-1">GAD Attendance</h3>
                <p class="text-sm text-gray-600">Scan QR Codes</p>
            </a>

            <a href="employees.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition text-center group">
                <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:bg-yellow-200 transition">
                    <i class="fas fa-users text-yellow-500 text-2xl"></i>
                </div>
                <h3 class="font-semibold text-gray-900 mb-1">Employee List</h3>
                <p class="text-3xl font-bold text-yellow-500"><?php echo $totalEmployees; ?></p>
            </a>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <!-- Total Employees -->
            <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-blue-100 text-sm mb-1">Total Employees</p>
                        <h3 class="text-4xl font-bold"><?php echo $totalEmployees; ?></h3>
                    </div>
                    <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                        <i class="fas fa-users text-3xl"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm">
                    <i class="fas fa-male mr-2"></i> <?php echo $maleCount; ?> Male
                    <span class="mx-2">•</span>
                    <i class="fas fa-female mr-2"></i> <?php echo $femaleCount; ?> Female
                </div>
            </div>

            <!-- Pending Approvals -->
            <div class="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-yellow-100 text-sm mb-1">Pending Accounts</p>
                        <h3 class="text-4xl font-bold"><?php echo $pendingAccounts; ?></h3>
                    </div>
                    <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                        <i class="fas fa-user-clock text-3xl"></i>
                    </div>
                </div>
                <a href="account-approvals.php" class="text-sm hover:underline">
                    <i class="fas fa-arrow-right mr-1"></i> Review Accounts
                </a>
            </div>

            <!-- Pending Registrations -->
            <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-purple-100 text-sm mb-1">Pending Registrations</p>
                        <h3 class="text-4xl font-bold"><?php echo $pendingRegistrations; ?></h3>
                    </div>
                    <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                        <i class="fas fa-clipboard-list text-3xl"></i>
                    </div>
                </div>
                <a href="registration-approvals.php" class="text-sm hover:underline">
                    <i class="fas fa-arrow-right mr-1"></i> Review Registrations
                </a>
            </div>

            <!-- Total Activities -->
            <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-green-100 text-sm mb-1">Total Activities</p>
                        <h3 class="text-4xl font-bold"><?php echo $totalActivities; ?></h3>
                    </div>
                    <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                        <i class="fas fa-calendar-check text-3xl"></i>
                    </div>
                </div>
                <a href="activities.php" class="text-sm hover:underline">
                    <i class="fas fa-arrow-right mr-1"></i> Manage Activities
                </a>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Main Content - Charts -->
            <div class="lg:col-span-2 space-y-8">
                <!-- Employee Distribution by Category -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h2 class="text-xl font-bold text-gray-900 mb-6">
                        <i class="fas fa-chart-bar text-admin mr-2"></i>
                        Employee Distribution by Category & Gender
                    </h2>
                    <canvas id="categoryChart" height="100"></canvas>
                </div>

                <!-- Gender Distribution Pie Chart -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h2 class="text-xl font-bold text-gray-900 mb-6">
                        <i class="fas fa-chart-pie text-admin mr-2"></i>
                        Gender Distribution
                    </h2>
                    <div class="flex justify-center">
                        <canvas id="genderChart" width="300" height="300"></canvas>
                    </div>
                </div>

                <!-- Upcoming Activities -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-gray-900">
                            <i class="fas fa-calendar-alt text-admin mr-2"></i>
                            Upcoming Activities
                        </h2>
                        <a href="activities.php" class="text-admin hover:text-admin-dark font-semibold text-sm">
                            View All <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>

                    <?php if (empty($upcomingActivitiesList)): ?>
                        <div class="text-center py-8 text-gray-500">
                            <i class="fas fa-calendar-times text-4xl mb-4"></i>
                            <p>No upcoming activities</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-3">
                            <?php foreach ($upcomingActivitiesList as $activity): ?>
                                <div class="border border-gray-200 rounded-lg p-4 hover:border-admin transition">
                                    <div class="flex items-start justify-between">
                                        <div class="flex-1">
                                            <h3 class="font-semibold text-gray-900 mb-2">
                                                <?php echo htmlspecialchars($activity['title']); ?>
                                            </h3>
                                            <div class="space-y-1 text-sm text-gray-600">
                                                <p>
                                                    <i class="fas fa-calendar mr-2 text-admin"></i>
                                                    <?php echo formatDate($activity['activity_date']); ?>
                                                </p>
                                                <p>
                                                    <i class="fas fa-users mr-2 text-admin"></i>
                                                    <?php echo $activity['registration_count']; ?> registered
                                                </p>
                                            </div>
                                        </div>
                                        <a href="activity-details.php?id=<?php echo $activity['activity_id']; ?>" 
                                           class="ml-4 text-admin hover:text-admin-dark">
                                            <i class="fas fa-arrow-right"></i>
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="space-y-8">
                <!-- Activity Calendar Widget -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-calendar text-admin mr-2"></i>
                        Activity Calendar
                    </h3>
                    <div id="calendar-widget" class="text-center text-gray-500">
                        <p class="text-sm">Full calendar view coming soon...</p>
                        <a href="calendar.php" class="inline-block mt-4 text-admin hover:text-admin-dark font-semibold text-sm">
                            View Full Calendar <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>

                <!-- Recent Registrations -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-clipboard-list text-admin mr-2"></i>
                        Recent Registrations
                    </h3>
                    <?php if (empty($recentRegistrations)): ?>
                        <p class="text-center text-gray-500 text-sm py-4">No recent registrations</p>
                    <?php else: ?>
                        <div class="space-y-3">
                            <?php
                            $regCount = count($recentRegistrations);
                            $regIndex = 0;
                            foreach ($recentRegistrations as $reg):
                                $regIndex++;
                            ?>
                                <div class="text-sm">
                                    <p class="font-semibold text-gray-900">
                                        <?php echo htmlspecialchars($reg['first_name'] . ' ' . $reg['last_name']); ?>
                                    </p>
                                    <p class="text-gray-600 text-xs">
                                        <?php echo htmlspecialchars($reg['activity_title']); ?>
                                    </p>
                                    <span class="inline-block mt-1 px-2 py-1 rounded-full text-xs font-semibold
                                        <?php
                                        echo $reg['status'] === 'approved' ? 'bg-green-100 text-green-700' :
                                             ($reg['status'] === 'pending' ? 'bg-yellow-100 text-yellow-700' :
                                             'bg-red-100 text-red-700');
                                        ?>">
                                        <?php echo ucfirst($reg['status']); ?>
                                    </span>
                                </div>
                                <?php if ($regIndex < $regCount): ?>
                                    <hr class="my-2">
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Quick Links -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-link text-admin mr-2"></i>
                        Quick Links
                    </h3>
                    <div class="space-y-2">
                        <a href="activity-form.php" class="block w-full bg-admin text-white py-2 px-4 rounded-lg text-center hover:bg-admin-dark transition text-sm">
                            <i class="fas fa-plus mr-2"></i> Create Activity
                        </a>
                        <a href="account-approvals.php" class="block w-full bg-yellow-500 text-white py-2 px-4 rounded-lg text-center hover:bg-yellow-600 transition text-sm">
                            <i class="fas fa-user-check mr-2"></i> Approve Accounts
                        </a>
                        <a href="gpb-form.php" class="block w-full bg-green-500 text-white py-2 px-4 rounded-lg text-center hover:bg-green-600 transition text-sm">
                            <i class="fas fa-file-invoice-dollar mr-2"></i> GPB Form
                        </a>
                        <a href="settings.php" class="block w-full bg-gray-500 text-white py-2 px-4 rounded-lg text-center hover:bg-gray-600 transition text-sm">
                            <i class="fas fa-cog mr-2"></i> Settings
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$additionalJS = "
<script>
// Category Chart Data
const categoryData = " . json_encode($categoryData) . ";
const categories = Object.keys(categoryData);
const maleData = categories.map(cat => categoryData[cat].Male || 0);
const femaleData = categories.map(cat => categoryData[cat].Female || 0);

// Bar Chart - Employee Distribution by Category
const ctxCategory = document.getElementById('categoryChart').getContext('2d');
new Chart(ctxCategory, {
    type: 'bar',
    data: {
        labels: categories,
        datasets: [
            {
                label: 'Male',
                data: maleData,
                backgroundColor: '#3b82f6',
                borderColor: '#2563eb',
                borderWidth: 1
            },
            {
                label: 'Female',
                data: femaleData,
                backgroundColor: '#ec4899',
                borderColor: '#db2777',
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    stepSize: 1
                }
            }
        },
        plugins: {
            legend: {
                position: 'top',
            },
            title: {
                display: false
            }
        }
    }
});

// Pie Chart - Gender Distribution
const ctxGender = document.getElementById('genderChart').getContext('2d');
new Chart(ctxGender, {
    type: 'pie',
    data: {
        labels: ['Male', 'Female'],
        datasets: [{
            data: [" . $maleCount . ", " . $femaleCount . "],
            backgroundColor: ['#3b82f6', '#ec4899'],
            borderColor: ['#2563eb', '#db2777'],
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                position: 'bottom',
            },
            title: {
                display: false
            }
        }
    }
});
</script>
";

include '../includes/footer.php';
?>

