<?php
session_start();
require_once '../config/db.php';

// Status display: approved=Active, deactivated/withdrawn=Inactive, rejected=Unrecognized
function status_display_label($status)
{
    $s = strtolower(trim((string) ($status ?? '')));
    $labels = ['approved' => 'Active', 'deactivated' => 'Inactive', 'withdrawn' => 'Inactive', 'rejected' => 'Unrecognized', 'pending' => 'Pending'];
    return $labels[$s] ?? $status;
}

if (!isset($_SESSION['admin_id'])) {
    if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['AC', 'AAC', 'NROI', 'PPSA'])) {
        header("Location: ../officer/dashboard.php");
    } else {
        header("Location: ../index.php");
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | NROI Portal</title>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>



    <!-- Sidebar Navigation -->
    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">ADMIN</div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link active">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/users.php" class="sidebar-link">
                    <i class="fas fa-user-friends"></i> Accounts
                </a>
            </li>
            <li class="sidebar-item">
                <a href="management.php" class="sidebar-link">
                    <i class="fas fa-cog"></i> Management
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/matches.php" class="sidebar-link">
                    <i class="fas fa-trophy"></i> Matches
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/request.php" class="sidebar-link">
                    <i class="fas fa-inbox"></i> For Approval
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
            <li class="sidebar-item">
                <a href="system_logs.php" class="sidebar-link">
                    <i class="fas fa-list-alt"></i> System Log
                </a>
            </li>
        </ul>

        <!-- Sidebar Profile -->
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">AD</div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">Administrator</div>
                    <div class="sidebar-user-role">System Admin</div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>

                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="profile.php" class="dropdown-item">
                        <i class="far fa-user-circle"></i> My Profile
                    </a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </aside>

    <div class="main-layout">

        <!-- Main Content Area -->
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>DASHBOARD</p>
                    </div>
                </div>
            </header>

            <!-- Stats Grid -->
            <div class="metrics-grid">
                <a href="../api/users.php" class="metric-card-fancy"
                    style="text-decoration: none; color: inherit; display: block;">
                    <div class="metric-content">
                        <div class="metric-info">
                            <h4>Total Users</h4>
                            <?php
                            $stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE status != 'pending'");
                            $totalUsers = $stmt->fetchColumn();
                            ?>
                            <span class="value"><?php echo $totalUsers; ?></span>
                        </div>
                        <div class="metric-icon-circle icon-blue">
                            <i class="fas fa-users"></i>
                        </div>
                    </div>
                </a>

                <a href="../api/users.php?tab=pending" class="metric-card-fancy"
                    style="text-decoration: none; color: inherit; display: block;">
                    <div class="metric-content">
                        <div class="metric-info">
                            <h4>Pending</h4>
                            <?php
                            $stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE status = 'pending'");
                            $pendingCount = $stmt->fetchColumn();
                            ?>
                            <span class="value"><?php echo $pendingCount; ?></span>
                        </div>
                        <div class="metric-icon-circle icon-orange">
                            <i class="fas fa-clock"></i>
                        </div>
                    </div>
                </a>
            </div>




            <?php
            // Small summary cards for Ongoing / Upcoming matches
            $today = date('Y-m-d');
            $twoDays = date('Y-m-d', strtotime('+2 days'));

            // Ongoing: matches where today is between start and end
            $ongoingCount = 0;
            $upcomingCount = 0;
            try {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM match_schedules WHERE start_date <= ? AND end_date >= ?");
                $stmt->execute([$today, $today]);
                $ongoingCount = (int) $stmt->fetchColumn();

                // Upcoming: next 2 days
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM match_schedules WHERE start_date > ? AND start_date <= ?");
                $stmt->execute([$today, $twoDays]);
                $upcomingCount = (int) $stmt->fetchColumn();
            } catch (Exception $e) {
                $ongoingCount = 0;
                $upcomingCount = 0;
            }
            ?>

            <div class="metrics-grid" style="margin-top: 24px;">
                <div class="metric-card-fancy">
                    <div class="metric-content">
                        <div class="metric-info">
                            <h4>Ongoing Matches</h4>
                            <span class="value"><?php echo $ongoingCount; ?></span>
                        </div>
                        <div class="metric-icon-circle icon-green">
                            <i class="fas fa-play-circle"></i>
                        </div>
                    </div>
                </div>

                <div class="metric-card-fancy">
                    <div class="metric-content">
                        <div class="metric-info">
                            <h4>Upcoming Matches (48h)</h4>
                            <span class="value"><?php echo $upcomingCount; ?></span>
                        </div>
                        <div class="metric-icon-circle icon-orange">
                            <i class="fas fa-hourglass-start"></i>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            // --- Chart Data: Area Distribution ---
            $stmtAreaData = $pdo->query("
                SELECT area, COUNT(*) as member_count
                FROM users
                WHERE status = 'approved' AND area IS NOT NULL AND area != ''
                  AND (role NOT IN ('RM','PPSA','NROI') OR role IS NULL)
                GROUP BY area ORDER BY CAST(area AS UNSIGNED) ASC
            ");
            $areaChartRows = $stmtAreaData->fetchAll(PDO::FETCH_ASSOC);
            $areaLabels = json_encode(array_map(fn($r) => 'Area ' . $r['area'], $areaChartRows));
            $areaValues = json_encode(array_column($areaChartRows, 'member_count'));

            // --- Chart Data: Top 10 Scorers (With File Verification) ---
            $stmtScores = $pdo->query("
                SELECT u.id, u.first_name, u.last_name, u.area,
                    COALESCE((SELECT SUM(mmx.points) FROM manual_match_points mmx WHERE mmx.user_id = u.id), 0) AS manual_total
                FROM users u
                WHERE u.status = 'approved' AND (u.role NOT IN ('RM','PPSA','NROI') OR u.role IS NULL)
            ");
            $allPotenders = $stmtScores->fetchAll(PDO::FETCH_ASSOC);

            if (!empty($allPotenders)) {
                $uIds = array_column($allPotenders, 'id');
                $placeholders = implode(',', array_fill(0, count($uIds), '?'));
                $chkStmt = $pdo->prepare("SELECT user_id, points, rm_signature FROM match_points WHERE user_id IN ($placeholders) AND rm_signature IS NOT NULL AND rm_signature != '' AND rm_signature != 'DEMERIT'");
                $chkStmt->execute($uIds);
                $allMatches = $chkStmt->fetchAll();

                $matchTotals = [];
                foreach ($allMatches as $m) {
                    if (!empty($m['rm_signature']) && file_exists('../' . $m['rm_signature'])) {
                        $matchTotals[$m['user_id']] = ($matchTotals[$m['user_id']] ?? 0) + (float) $m['points'];
                    }
                }

                foreach ($allPotenders as &$p) {
                    $p['total_points'] = (float) ($p['manual_total'] ?? 0) + (float) ($matchTotals[$p['id']] ?? 0);
                }
                unset($p);

                // Sort and take top 10
                usort($allPotenders, fn($a, $b) => $b['total_points'] <=> $a['total_points']);
                $scoreRows = array_slice($allPotenders, 0, 10);
            } else {
                $scoreRows = [];
            }

            $scoreLabels = json_encode(array_map(fn($r) => capitalizeWords($r['last_name'] . ', ' . $r['first_name']), $scoreRows));
            $scoreValues = json_encode(array_map(fn($r) => (float) $r['total_points'], $scoreRows));

            // --- Performance summary (Verified Totals) ---
            $grand_total = 0;
            $top_score = 0;
            $total_members = count($allPotenders);
            foreach ($allPotenders as $p) {
                $grand_total += (float) $p['total_points'];
                if ((float) $p['total_points'] > $top_score) {
                    $top_score = (float) $p['total_points'];
                }
            }
            $avgScore = $total_members > 0 ? round($grand_total / $total_members, 2) : 0;
            $perf = ['total_members' => $total_members, 'top_score' => $top_score];
            ?>

            <!-- Two-column charts row -->
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:20px; margin-top:24px;">

                <!-- Chart 1: Area Distribution -->
                <div
                    style="background:#fff; border-radius:18px; box-shadow:0 4px 24px rgba(30,58,138,0.08); padding:24px 28px;">
                    <div
                        style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:18px;">
                        <div>
                            <h3 style="margin:0 0 4px; font-size:1rem; font-weight:800; color:#1e293b;">National Member
                                Distribution</h3>
                            <p style="margin:0; font-size:0.78rem; color:#94a3b8; font-weight:500;">Approved members per
                                area</p>
                        </div>
                        <div
                            style="background:#eff6ff; color:#2563eb; font-size:0.7rem; font-weight:800; padding:5px 12px; border-radius:20px; text-transform:uppercase;">
                            <i class="fas fa-chart-line" style="margin-right:4px;"></i> Areas
                        </div>
                    </div>
                    <div style="position:relative; height:220px;">
                        <canvas id="adminAreaChart"></canvas>
                    </div>
                </div>

                <!-- Chart 2: Score Overview -->
                <div
                    style="background:#fff; border-radius:18px; box-shadow:0 4px 24px rgba(30,58,138,0.08); padding:24px 28px;">
                    <div
                        style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:18px;">
                        <div>
                            <h3 style="margin:0 0 4px; font-size:1rem; font-weight:800; color:#1e293b;">Total Score
                                Overview</h3>
                            <p style="margin:0; font-size:0.78rem; color:#94a3b8; font-weight:500;">Top 10 members by
                                accumulated points</p>
                        </div>
                        <div
                            style="background:#f0fdf4; color:#059669; font-size:0.7rem; font-weight:800; padding:5px 12px; border-radius:20px; text-transform:uppercase;">
                            <i class="fas fa-trophy" style="margin-right:4px;"></i> Scores
                        </div>
                    </div>
                    <div style="position:relative; height:220px;">
                        <canvas id="adminScoreChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Performance Summary -->
            <div
                style="background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%); border-radius:16px; padding:22px 28px; margin-top:20px; display:flex; align-items:center; gap:32px; flex-wrap:wrap; box-shadow:0 8px 24px rgba(37,99,235,0.25);">
                <div style="flex:1; min-width:160px; text-align:center;">
                    <div
                        style="font-size:0.7rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                        Total Members</div>
                    <div style="font-size:2rem; font-weight:900; color:#fff;">
                        <?php echo number_format($perf['total_members']); ?>
                    </div>
                </div>
                <div style="width:1px; height:48px; background:rgba(255,255,255,0.15); flex-shrink:0;"></div>
                <div style="flex:1; min-width:160px; text-align:center;">
                    <div
                        style="font-size:0.7rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                        Avg. Score / Member</div>
                    <div style="font-size:2rem; font-weight:900; color:#fff;"><?php echo number_format($avgScore, 2); ?>
                    </div>
                </div>
                <div style="width:1px; height:48px; background:rgba(255,255,255,0.15); flex-shrink:0;"></div>
                <div style="flex:1; min-width:160px; text-align:center;">
                    <div
                        style="font-size:0.7rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                        Highest Score</div>
                    <div style="font-size:2rem; font-weight:900; color:#fff;">
                        <?php echo number_format($perf['top_score'], 2); ?>
                    </div>
                </div>
                <div style="flex:3; min-width:220px; padding-left:12px; border-left:1px solid rgba(255,255,255,0.15);">
                    <div
                        style="font-size:0.7rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:6px;">
                        <i class="fas fa-chart-bar" style="margin-right:5px;"></i> Performance Summary
                    </div>
                    <p style="margin:0; font-size:0.88rem; color:rgba(255,255,255,0.85); line-height:1.6;">
                        <?php
                        if ($perf['total_members'] == 0) {
                            echo 'No member data available yet.';
                        } elseif ($avgScore >= 20) {
                            echo 'Excellent national performance. Members are consistently accumulating high match points across all areas.';
                        } elseif ($avgScore >= 10) {
                            echo 'Good overall performance. Most members are actively participating in matches with solid point accumulation.';
                        } elseif ($avgScore >= 5) {
                            echo 'Moderate performance. Some areas show strong activity while others may need more engagement.';
                        } else {
                            echo 'Performance is still building up. Encourage more member participation across areas to improve overall scores.';
                        }
                        ?>
                    </p>
                </div>
            </div>

            <script>
                (function () {
                    // Chart 1: Area Distribution
                    const aCtx = document.getElementById('adminAreaChart').getContext('2d');
                    const aGrad = aCtx.createLinearGradient(0, 0, 0, 220);
                    aGrad.addColorStop(0, 'rgba(37,99,235,0.22)');
                    aGrad.addColorStop(1, 'rgba(37,99,235,0)');
                    new Chart(aCtx, {
                        type: 'line',
                        data: { labels: <?php echo $areaLabels; ?>, datasets: [{ label: 'Members', data: <?php echo $areaValues; ?>, fill: true, backgroundColor: aGrad, borderColor: '#2563eb', borderWidth: 3, pointBackgroundColor: '#fff', pointBorderColor: '#2563eb', pointBorderWidth: 3, pointRadius: 5, pointHoverRadius: 8, tension: 0.4 }] },
                        options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: false }, tooltip: { backgroundColor: '#1e293b', titleColor: '#94a3b8', bodyColor: '#fff', bodyFont: { weight: 700, size: 13 }, padding: 10, cornerRadius: 10, callbacks: { label: c => ' ' + c.parsed.y + ' member' + (c.parsed.y !== 1 ? 's' : '') } } }, scales: { x: { grid: { display: false }, ticks: { color: '#64748b', font: { weight: 600, size: 11 } }, border: { display: false } }, y: { beginAtZero: true, ticks: { color: '#94a3b8', font: { weight: 600 }, stepSize: 1, precision: 0 }, grid: { color: 'rgba(0,0,0,0.04)' }, border: { display: false } } } }
                    });

                    // Chart 2: Score Overview
                    const sCtx = document.getElementById('adminScoreChart').getContext('2d');
                    const sGrad = sCtx.createLinearGradient(0, 0, 0, 220);
                    sGrad.addColorStop(0, 'rgba(5,150,105,0.85)');
                    sGrad.addColorStop(1, 'rgba(5,150,105,0.3)');
                    new Chart(sCtx, {
                        type: 'bar',
                        data: { labels: <?php echo $scoreLabels; ?>, datasets: [{ label: 'Points', data: <?php echo $scoreValues; ?>, backgroundColor: sGrad, borderColor: '#059669', borderWidth: 0, borderRadius: 8, borderSkipped: false }] },
                        options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: false }, tooltip: { backgroundColor: '#1e293b', titleColor: '#94a3b8', bodyColor: '#fff', bodyFont: { weight: 700, size: 13 }, padding: 10, cornerRadius: 10, callbacks: { label: c => ' ' + c.parsed.y.toFixed(2) + ' pts' } } }, scales: { x: { grid: { display: false }, ticks: { color: '#64748b', font: { weight: 600, size: 10 }, maxRotation: 35, minRotation: 20 }, border: { display: false } }, y: { beginAtZero: true, ticks: { color: '#94a3b8', font: { weight: 600 } }, grid: { color: 'rgba(0,0,0,0.04)' }, border: { display: false } } } }
                    });
                })();
            </script>

            <div class="content-box" style="margin-top: 20px;">
                <div class="table-header"
                    style="gap: 12px; flex-wrap: wrap; justify-content: space-between; align-items: center;">
                    <div>
                        <h3 style="margin:0;">Activity Log</h3>
                        <div style="font-size:0.85rem; color:#64748b;">
                            Recent system-level actions
                        </div>
                    </div>
                    <a href="system_logs.php" class="btn-secondary"
                        style="margin:0; width:auto; padding: 8px 15px; font-size: 0.85rem;">
                        <i class="fas fa-list-alt" style="margin-right: 5px;"></i> See All Logs
                    </a>
                </div>

                <div style="overflow-x:auto;">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Reference</th>
                                <th>Description</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $activityLogs = [];
                            try {
                                // Ensure activity_logs table exists
                                $pdo->exec("
                                    CREATE TABLE IF NOT EXISTS activity_logs (
                                        id INT AUTO_INCREMENT PRIMARY KEY,
                                        reference_type VARCHAR(50) NOT NULL,
                                        reference_id INT NULL,
                                        description TEXT NOT NULL,
                                        status VARCHAR(50) NOT NULL,
                                        performed_by_role VARCHAR(20) NOT NULL,
                                        performed_by_user_id INT NULL,
                                        performed_by_admin_id INT NULL,
                                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                        INDEX idx_created_at (created_at),
                                        INDEX idx_performed_by (performed_by_role, performed_by_user_id, performed_by_admin_id)
                                    )
                                ");

                                // Fetch all activity logs (Admin can see all actions by Admin, AC, AAC, PPSA, NROI)
                                $stmt = $pdo->query("
                                    SELECT al.*, 
                                        CASE 
                                            WHEN al.performed_by_role = 'ADMIN' THEN COALESCE(a.username, 'Admin')
                                            ELSE CONCAT(u.first_name, ' ', u.last_name)
                                        END as performer_name
                                    FROM activity_logs al
                                    LEFT JOIN users u ON al.performed_by_user_id = u.id
                                    LEFT JOIN admins a ON al.performed_by_admin_id = a.id
                                    WHERE al.performed_by_role IN ('ADMIN', 'AC', 'AAC', 'PPSA', 'NROI')
                                    ORDER BY al.created_at DESC 
                                    LIMIT 8
                                ");
                                $activityLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            } catch (PDOException $e) {
                                // Silently handle - table might not exist yet or no data
                                $activityLogs = [];
                            } catch (Exception $e) {
                                // Silently handle any other errors
                                $activityLogs = [];
                            }
                            ?>
                            <?php if (empty($activityLogs)): ?>
                                <tr>
                                    <td colspan="5" style="text-align: center; color: #64748b; padding: 60px;">
                                        <i class="fas fa-folder-open"
                                            style="font-size: 2rem; display: block; margin-bottom: 15px; opacity: 0.5;"></i>
                                        No activity log entries found yet.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($activityLogs as $log): ?>
                                    <tr>
                                        <td style="font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                                            <?php echo htmlspecialchars($log['performer_name'] ?: 'System'); ?>
                                        </td>
                                        <td>
                                            <span class="role-badge" style="background: #eff6ff; color: #1e40af;">
                                                <?php echo $log['reference_type'] === 'user' ? 'Account' : htmlspecialchars(ucfirst($log['reference_type'])); ?>
                                            </span>
                                        </td>
                                        <td style="font-size: 0.9rem; color: #1e293b;">
                                            <?php echo htmlspecialchars($log['description']); ?>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo htmlspecialchars($log['status']); ?>">
                                                <?php echo status_display_label($log['status']); ?>
                                            </span>
                                        </td>
                                        <td style="font-size: 0.85rem; color: #64748b;">
                                            <?php echo isset($log['created_at']) ? date('M d, Y h:i A', strtotime($log['created_at'])) : 'N/A'; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </main>
    </div> <!-- End Main Layout -->


    <script src="../assets/js/loader.js"></script>
    <script>
        // Profile Dropdown Toggle
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');

        if (profileToggle && profileDropdown) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });

            // Close dropdown when clicking outside
            document.addEventListener('click', (e) => {
                if (!profileToggle.contains(e.target) && !profileDropdown.contains(e.target)) {
                    profileDropdown.classList.remove('active');
                }
            });
        }

    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>

</script>
<script src="../assets/js/dashboard-transitions.js"></script>
</body>


</html>