<?php
require __DIR__ . "/core/session.php";

if (!is_logged_in()) {
    header("Location: ../index.php");
    exit;
}

$usersDir = __DIR__ . '/../users';

$users = [];

foreach (glob($usersDir . '/*/data.json') as $file) {
    $json = json_decode(file_get_contents($file), true);
    if ($json) $users[] = $json;
}

$totalUsers = count($users);

$active24h = 0;
$now = time();
foreach ($users as $u) {
    if (isset($u['last_login'])) {
        if ($now - strtotime($u['last_login']) <= 86400) $active24h++;
    }
}

$latestRegistered = $users;
usort($latestRegistered, fn($a, $b) => strtotime($b['registered']) - strtotime($a['registered']));
$latestRegistered = array_slice($latestRegistered, 0, 10);

$latestLogin = $users;
usort($latestLogin, fn($a, $b) => strtotime($b['last_login']) - strtotime($a['last_login']));
$latestLogin = array_slice($latestLogin, 0, 10);

$onlineUsers = [];
foreach ($users as $u) {
    if ($now - strtotime($u['last_login']) <= 60) {
        $onlineUsers[] = $u;
    }
}

$ipCount = [];
foreach ($users as $u) {
    $ip = $u['now_ip'] ?? 'unknown';
    if (!isset($ipCount[$ip])) $ipCount[$ip] = 0;
    $ipCount[$ip]++;
}

$ageMap = [
    'Young' => 18,
    'Adult' => 30,
    'Middle' => 45,
    'Senior' => 65
];
$sumAge = 0;
$ageUsers = 0;

foreach ($users as $u) {
    if (isset($ageMap[$u['age']])) {
        $sumAge += $ageMap[$u['age']];
        $ageUsers++;
    }
}
$avgAge = $ageUsers > 0 ? round($sumAge / $ageUsers, 1) : 0;

$highRisk = [];
foreach ($users as $u) {
    if (!empty($u['last_ip']) && !empty($u['now_ip']) && $u['last_ip'] !== $u['now_ip']) {
        $highRisk[] = $u;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/lucide@latest/dist/lucide.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="style.css">
    <title>Admin Dashboard</title>
</head>

<body>

    <div class="menu flex flex-col h-screen w-min">
        <div class="flex justify-center items-center mt-3">
            <img src="/../images/loading.png" alt="iamge" class="w-20">
        </div>
        <div class="pl-4 mt-5 text-[#00000075] font-medium">
            <a href="dashboard.php" class="flex row items-center"><i data-lucide="house" class="w-5 h-5"></i>Home</a>
            <a href="send_post.php" class="flex row items-center"><i data-lucide="send" class="w-5 h-5"></i>Post</a>
            <a href="comparisons.php" class="flex row items-center"><i data-lucide="search" class="w-5 h-5"></i>Comparisons</a>
            <a href="requests.php" class="flex row items-center"><i data-lucide="list-check" class="w-5 h-5"></i>Requests</a>
        </div>

        <div class="mt-auto pl-4 pb-4">
            <a href="core/logout.php" class="flex row items-center text-[#00000075]"><i data-lucide="octagon-minus" class="w-5 h-5"></i>Log Out</a>
        </div>
    </div>

    <div class="flex-1 p-8 pt-2 m-5">

        <h1 class="text-[35px] font-semibold">Hello, Admin</h1>
        <span class="text-[#000000]/50 text-[15px] font-normal">Join the team work, Have a nice day!</span>

        <div class="grid grid-cols-3 mt-8 border-y-[2px] border-[#00000010]">

            <div class="flex items-center p-6 my-2 border-r-[2px] border-[#00000005]">
                <div class="flex justify-center items-center bg-[#F2F2F2] rounded-full w-16 h-16">
                    <i data-lucide="users" class="w-8 h-8"></i>
                </div>
                <div class="flex flex-col ml-4">
                    <p class="text-black text-sm">Total Users</p>
                    <p class="text-3xl font-medium"><?= $totalUsers ?></p>
                </div>
            </div>

            <div class="flex items-center p-6 my-2 border-r-[2px] border-[#00000005]">
                <div class="flex justify-center items-center bg-[#F2F2F2] rounded-full w-16 h-16">
                    <i data-lucide="clock-arrow-up" class="w-8 h-8"></i>
                </div>
                <div class="flex flex-col ml-4">
                    <p class="text-black text-sm">Active (Last 24h)</p>
                    <p class="text-3xl font-medium"><?= $active24h ?></p>
                </div>
            </div>

            <div class="flex items-center p-6 my-2 border-r-[2px] border-[#00000005]">
                <div class="flex justify-center items-center bg-[#F2F2F2] rounded-full w-16 h-16">
                    <i data-lucide="activity" class="w-8 h-8"></i>
                </div>
                <div class="flex flex-col ml-4">
                    <p class="text-black text-sm">Online Users</p>
                    <p class="text-3xl font-medium"><?= count($onlineUsers) ?></p>
                </div>
            </div>
        </div>

        <h2 class="text-[21px] font-semibold mt-10 mb-2">Latest Registered Users</h2>
        <div class="divide-y divide-[#2F323A]">
            <?php foreach ($latestRegistered as $u): ?>
                <div class="flex justify-between items-center py-3 border-b-[1px] border-[#00000010]">
                    <div class="flex items-center">

                        <i data-lucide="user-plus" class="w-4 h-4 text-gray-400"></i>

                        <div class="ml-3">
                            <p class="font-medium text-[15px]"><?= htmlspecialchars($u['displayname']) ?></p>
                            <p class="text-gray-400 text-xs"><?= htmlspecialchars($u['email']) ?></p>
                        </div>
                    </div>

                    <div class="text-right">
                        <p class="text-sm text-gray-300"><?= $u['registered'] ?></p>
                        <p class="text-gray-500 text-xs">
                            ID: <?= substr($u['id'], 0, 10) ?>...
                        </p>
                    </div>

                </div>
            <?php endforeach; ?>
        </div>


        <h2 class="text-[21px] font-semibold mt-10 mb-2">Latest User Logins</h2>
        <div class="divide-y divide-[#2F323A]">
            <?php foreach ($latestLogin as $u): ?>
                <div class="flex justify-between items-center py-3 border-b-[1px] border-[#00000010]">

                    <div class="flex items-center">

                        <i data-lucide="log-in" class="w-4 h-4 text-gray-400"></i>

                        <div class="ml-3">
                            <p class="font-medium text-[15px]"><?= htmlspecialchars($u['displayname']) ?></p>
                            <p class="text-gray-400 text-xs">IP: <?= $u['now_ip'] ?></p>
                        </div>
                    </div>

                    <div class="text-right">
                        <p class="text-sm text-gray-300"><?= $u['last_login'] ?></p>
                        <p class="text-gray-500 text-xs">
                            <?= $u['user_agent'] ? 'Device detected' : 'Unknown device' ?>
                        </p>
                    </div>

                </div>
            <?php endforeach; ?>
        </div>
    </div>

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

</body>

</html>