<?php
include_once __DIR__ . "/../../config/check-login.php";
include_once __DIR__ . "/../../config/dbcon.php";

/* Fetch logged-in user ONCE */
$user = null;

if (!empty($_SESSION['user_uid'])) {
    $stmt = $conn->prepare("
        SELECT name, email, phone, profile
        FROM users
        WHERE firebase_uid = :uid
        LIMIT 1
    ");
    $stmt->execute([':uid' => $_SESSION['user_uid']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
}

function calculatePercentageChange($previous, $current)
{
    if ($previous == 0)
        return 100;
    $change = (($current - $previous) / $previous) * 100;
    return round($change, 1);
}

$totalCountries = $totalCategories = $totalUsers = $totalJobs = 0;
$countryPercent = $categoryPercent = $userPercent = $jobPercent = 0;

try {

    $totalCountries = (int) $conn->query("SELECT COUNT(*) FROM countries WHERE deleted_at IS NULL")->fetchColumn();
    $prevCountries = (int) $conn->query("SELECT COUNT(*) FROM countries WHERE deleted_at IS NULL AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH))")->fetchColumn();
    $countryPercent = calculatePercentageChange($prevCountries, $totalCountries);

    $totalCategories = (int) $conn->query("SELECT COUNT(*) FROM categories WHERE deleted_at IS NULL")->fetchColumn();
    $prevCategories = (int) $conn->query("SELECT COUNT(*) FROM categories WHERE deleted_at IS NULL AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH))")->fetchColumn();
    $categoryPercent = calculatePercentageChange($prevCategories, $totalCategories);

    $totalUsers = (int) $conn->query("SELECT COUNT(*) FROM users WHERE deleted_at IS NULL AND role = 'user'")->fetchColumn();
    $prevUsers = (int) $conn->query("SELECT COUNT(*) FROM users WHERE deleted_at IS NULL AND role = 'user' AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH))")->fetchColumn();
    $userPercent = calculatePercentageChange($prevUsers, $totalUsers);

    $totalJobs = (int) $conn->query("SELECT COUNT(*) FROM jobs WHERE deleted_at IS NULL")->fetchColumn();
    $prevJobs = (int) $conn->query("SELECT COUNT(*) FROM jobs WHERE deleted_at IS NULL AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH))")->fetchColumn();
    $jobPercent = calculatePercentageChange($prevJobs, $totalJobs);

} catch (PDOException $e) {
    error_log("Error fetching totals: " . $e->getMessage());
}

function badgeClass($percent)
{
    return $percent >= 0 ? 'success' : 'danger';
}

$months = [];
$usersCount = [];
$jobsCount = [];

for ($i = 5; $i >= 0; $i--) {
    $month = date('M Y', strtotime("-$i month"));
    $months[] = $month;

    // Users this month
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM users WHERE MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL :i MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL :i MONTH)) AND deleted_at IS NULL");
    $stmt->execute([':i' => $i]);
    $usersCount[] = (int) $stmt->fetchColumn();

    // Jobs this month
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM jobs WHERE MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL :i MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(NOW(), INTERVAL :i MONTH)) AND deleted_at IS NULL");
    $stmt->execute([':i' => $i]);
    $jobsCount[] = (int) $stmt->fetchColumn();
}
?>

<?php
$pageTitle = "Dashboard - Job Admin Panel";
$pageHeading = "Dashboard";
?>
<?php include __DIR__ . '/../../components/backend/sidebar.php'; ?>
<?php include __DIR__ . '/../../components/backend/header.php'; ?>

<!-- Main Content -->
<div class="main-wrapper">
    <h2 class="dashboard-heading">Dashboard Overview</h2>

    <div class="dashboard-cards">
        <div class="card">
            <div class="card-icon bg-blue"><i class="fas fa-flag"></i></div> <!-- Countries -->
            <h3>Total Countries</h3>
            <div class="value"><?= number_format($totalCountries) ?></div>
            <span class="badge <?= badgeClass($countryPercent) ?>">
                <?= ($countryPercent >= 0 ? '+' : '') . $countryPercent ?>% this month
            </span>
        </div>

        <div class="card">
            <div class="card-icon bg-green"><i class="fas fa-list-alt"></i></div> <!-- Categories -->
            <h3>Total Categories</h3>
            <div class="value"><?= number_format($totalCategories) ?></div>
            <span class="badge <?= badgeClass($categoryPercent) ?>">
                <?= ($categoryPercent >= 0 ? '+' : '') . $categoryPercent ?>% this month
            </span>
        </div>

        <div class="card">
            <div class="card-icon bg-orange"><i class="fas fa-users"></i></div> <!-- Users -->
            <h3>Total Users</h3>
            <div class="value"><?= number_format($totalUsers) ?></div>
            <span class="badge <?= badgeClass($userPercent) ?>">
                <?= ($userPercent >= 0 ? '+' : '') . $userPercent ?>% this month
            </span>
        </div>

        <div class="card">
            <div class="card-icon bg-purple"><i class="fas fa-briefcase"></i></div> <!-- Jobs -->
            <h3>Total Jobs</h3>
            <div class="value"><?= number_format($totalJobs) ?></div>
            <span class="badge <?= badgeClass($jobPercent) ?>">
                <?= ($jobPercent >= 0 ? '+' : '') . $jobPercent ?>% this month
            </span>
        </div>

    </div>

    <div class="dashboard-graphs">
        <div class="graph-card">
            <h4>Users Over Time</h4>
            <canvas id="usersChart"></canvas>
        </div>
        <div class="graph-card">
            <h4>Jobs Over Time</h4>
            <canvas id="jobsChart"></canvas>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Pass PHP arrays to JS
    const months = <?= json_encode($months) ?>;
    const usersData = <?= json_encode($usersCount) ?>;
    const jobsData = <?= json_encode($jobsCount) ?>;

    // Users Chart
    new Chart(document.getElementById('usersChart'), {
        type: 'line',
        data: {
            labels: months,
            datasets: [{
                label: 'Users',
                data: usersData,
                borderColor: 'rgba(54, 162, 235, 1)',
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } },
            scales: { y: { beginAtZero: true } }
        }
    });

    // Jobs Chart
    new Chart(document.getElementById('jobsChart'), {
        type: 'line',
        data: {
            labels: months,
            datasets: [{
                label: 'Jobs',
                data: jobsData,
                borderColor: 'rgba(255, 159, 64, 1)',
                backgroundColor: 'rgba(255, 159, 64, 0.2)',
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } },
            scales: { y: { beginAtZero: true } }
        }
    });
</script>
<?php include __DIR__ . '/../../components/backend/footer.php'; ?>