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

$is_admin = isset($_SESSION['admin_id']);
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
$is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
$is_special_role = isset($_SESSION['user_role']) && in_array(strtoupper($_SESSION['user_role']), ['PPSA', 'NROI']);
$is_officer_role = $is_ac || $is_aac || $is_special_role;

// Allow admin and AC/AAC/PPSA/NROI only
if (!$is_admin && !$is_officer_role) {
    header("Location: ../index.php");
    exit;
}
$pdo->exec("
    CREATE TABLE IF NOT EXISTS manual_match_points (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        recorded_by_user_id INT NULL,
        recorded_by_admin_id INT NULL,
        match_name VARCHAR(255) NOT NULL,
        discipline VARCHAR(100) DEFAULT 'Handgun',
        year INT NOT NULL,
        level VARCHAR(50) NOT NULL,
        role VARCHAR(100) NOT NULL,
        points DECIMAL(10, 2) NOT NULL,
        location VARCHAR(255) DEFAULT '---',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// Check if discipline column exists, if not add it
$checkCol = $pdo->query("SHOW COLUMNS FROM manual_match_points LIKE 'discipline'");
if (!$checkCol->fetch()) {
    $pdo->exec("ALTER TABLE manual_match_points ADD COLUMN discipline VARCHAR(100) DEFAULT 'Handgun' AFTER match_name");
}

// Fetch disciplines for the modals
$stmtDisc = $pdo->query("SELECT name FROM disciplines WHERE name != 'Bad Record' ORDER BY name ASC");
$allDisciplines = $stmtDisc->fetchAll(PDO::FETCH_COLUMN) ?: ['Handgun', 'PCC', 'Mini Rifle', 'Shotgun', 'Rifle'];

// Fetch users with their total points - Admin and Special Roles (PPSA/NROI) see all, AC/AAC see only their area
if ($is_admin || $is_special_role) {
    $stmt = $pdo->prepare("
        SELECT u.*, 
        (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = u.id) as manual_total,
        (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
        profile_photo
        FROM users u 
        WHERE u.status = 'approved' AND (u.role NOT IN ('RM', 'PPSA', 'NROI') OR u.role IS NULL)
        ORDER BY 
            CASE 
                WHEN u.role = 'AC' THEN 1 
                WHEN u.role = 'AAC' THEN 2 
                WHEN u.role IN ('RO', 'R.O', 'member', '') OR u.role IS NULL THEN 3
                WHEN u.role IN ('CRO', 'C.R.O') THEN 4
                ELSE 5 
            END, 
            last_name ASC
    ");
    $stmt->execute();
} else {
    $area = $_SESSION['area'] ?? '';
    
    $roleFilter = "";
    if ($is_ac) {
        $roleFilter = " AND (u.role IN ('AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member') OR u.role IS NULL OR u.role = '')";
    } elseif ($is_aac) {
        $roleFilter = " AND (u.role IN ('R.O', 'C.R.O', 'RO', 'CRO', 'member') OR u.role IS NULL OR u.role = '')";
    }

    $stmt = $pdo->prepare("
        SELECT u.*, 
        (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = u.id) as manual_total,
        (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
        profile_photo
        FROM users u 
        WHERE u.area = ? AND u.status = 'approved' AND (u.role NOT IN ('RM', 'PPSA', 'NROI', 'AC', 'AAC') OR u.role IS NULL) $roleFilter
        ORDER BY 
            CASE 
                WHEN u.role = 'AC' THEN 1 
                WHEN u.role = 'AAC' THEN 2 
                WHEN u.role IN ('RO', 'R.O', 'member', '') OR u.role IS NULL THEN 3
                WHEN u.role IN ('CRO', 'C.R.O') THEN 4
                ELSE 5 
            END, 
            last_name ASC
    ");
    $stmt->execute([$area]);
}
$allUsers = $stmt->fetchAll();

// Robust recalculated totals (Mirroring member_points_summary.php)
if (!empty($allUsers)) {
    $uIds = array_column($allUsers, 'id');
    $placeholders = implode(',', array_fill(0, count($uIds), '?'));
    
    // Fetch all match points with filters matching SQL logic
    $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 ($allUsers as &$usr) {
        $usr['total_points'] = (float)($usr['manual_total'] ?? 0) + (float)($matchTotals[$usr['id']] ?? 0);
    }
    unset($usr);
    
    // Perform manual sorting by points since SQL subquery was removed
    usort($allUsers, function($a, $b) {
        // Priority by role first (mirroring SQL CASE)
        $p = ['AC' => 1, 'AAC' => 2, 'R.O' => 3, 'RO' => 3, 'member' => 3, 'C.R.O' => 4, 'CRO' => 4];
        $rA = (!empty($a['role']) && $a['role'] !== 'member') ? $a['role'] : 'R.O';
        $rB = (!empty($b['role']) && $b['role'] !== 'member') ? $b['role'] : 'R.O';
        $pA = $p[$rA] ?? 5;
        $pB = $p[$rB] ?? 5;
        
        if ($pA !== $pB) return $pA - $pB;
        if ($b['total_points'] != $a['total_points']) return $b['total_points'] > $a['total_points'] ? 1 : -1;
        return strcasecmp($a['last_name'], $b['last_name']);
    });
}
$totalMembersInArea = count($allUsers);

// Fetch Area Coordinator Map
$acMap = [];
try {
    $stmtAC = $pdo->query("SELECT first_name, last_name, area FROM users WHERE role = 'AC' AND status = 'approved'");
    while ($row = $stmtAC->fetch(PDO::FETCH_ASSOC)) {
        $areaName = trim($row['area']);
        if (!empty($areaName)) {
            $acMap[$areaName] = $row['first_name'] . ' ' . $row['last_name'];
        }
    }
} catch (Exception $e) {
    // Silent fail
}

// Fetch AC Signature for the current area (if not admin/global)
$acSigPathForBulk = "";
$acNameForBulk = "";
if (!$is_admin && isset($_SESSION['area'])) {
    $currentArea = trim($_SESSION['area']);
    $stmtAcBulk = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE role = 'AC' AND area = ? AND status = 'approved' LIMIT 1");
    $stmtAcBulk->execute([$currentArea]);
    $acBulk = $stmtAcBulk->fetch(PDO::FETCH_ASSOC);
    if ($acBulk) {
        $acNameForBulk = $acBulk['first_name'] . ' ' . $acBulk['last_name'];
        $sigDir = __DIR__ . '/../storage/officers_signature/';
        $acFiles = glob($sigDir . 'officer_' . $acBulk['id'] . '_*');
        if (!empty($acFiles)) {
            usort($acFiles, fn($a, $b) => filemtime($b) - filemtime($a));
            $acSigPathForBulk = 'storage/officers_signature/' . basename($acFiles[0]);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Points Card | NROI Portal</title>
    <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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.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">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
    <style>
        .modern-table tbody tr {
            cursor: pointer;
            transition: background 0.2s;
        }

        .modern-table tbody tr:hover {
            background-color: #f8fafc !important;
        }

        .row-clickable-link {
            text-decoration: none;
            color: inherit;
        }
    </style>
</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">
                <?php
                if ($is_admin) {
                    echo 'ADMIN';
                } elseif ($is_ac) {
                    echo 'A.C';
                } elseif ($is_aac) {
                    echo 'A.A.C';
                } else {
                    echo htmlspecialchars($_SESSION['user_role'] ?? 'OFFICER');
                }
                ?>
            </div>
        </div>
        <ul class="sidebar-menu">
            <?php if ($is_admin): ?>
                <li class="sidebar-item">
                    <a href="../admin/dashboard.php" class="sidebar-link">
                        <i class="fas fa-th-large"></i> Overview
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="users.php" class="sidebar-link">
                        <i class="fas fa-user-friends"></i> Accounts
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="../admin/management.php" class="sidebar-link">
                        <i class="fas fa-cog"></i> Management
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="matches.php" class="sidebar-link">
                        <i class="fas fa-trophy"></i> Matches
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="request.php" class="sidebar-link">
                        <i class="fas fa-inbox"></i> For Approval
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="points_card.php" class="sidebar-link active">
                        <i class="fas fa-id-card"></i> Points Card
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="../admin/system_logs.php" class="sidebar-link">
                        <i class="fas fa-list-alt"></i> System Log
                    </a>
                </li>
            <?php else: ?>
                <li class="sidebar-item">
                    <a href="../officer/dashboard.php" class="sidebar-link">
                        <i class="fas fa-th-large"></i> Overview
                    </a>
                </li>
                <?php if (!$is_special_role): ?>
                    <li class="sidebar-item">
                        <a href="../officer/notifications.php" class="sidebar-link">
                            <i class="fas fa-bell"></i> Notifications
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="users.php" class="sidebar-link">
                            <i class="fas fa-user-friends"></i> Accounts
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="request.php" class="sidebar-link">
                            <i class="fas fa-inbox"></i> For Approval
                        </a>
                    </li>
                <?php endif; ?>
                <li class="sidebar-item">
                    <a href="points_card.php" class="sidebar-link active">
                        <i class="fas fa-id-card"></i> Points Card
                    </a>
                </li>
            <?php endif; ?>
        </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;">
                    <?php
                    if ($is_admin) {
                        echo 'AD';
                    } elseif ($is_ac) {
                        echo 'AC';
                    } elseif ($is_aac) {
                        echo 'AA';
                    } else {
                        echo strtoupper(substr($_SESSION['user_role'] ?? 'OF', 0, 2));
                    }
                    ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">
                        <?php echo $is_admin ? 'Administrator' : capitalizeWords($_SESSION['name'] ?? 'Officer'); ?>
                    </div>
                    <div class="sidebar-user-role">
                        <?php
                        if ($is_admin) {
                            echo 'System Admin';
                        } elseif ($is_ac) {
                            echo 'A.C Account';
                        } elseif ($is_aac) {
                            echo 'A.A.C Account';
                        } else {
                            echo htmlspecialchars($_SESSION['user_role'] ?? 'Officer') . ' Account';
                        }
                        ?>
                    </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="<?php echo $is_admin ? '../admin/profile.php' : '../officer/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 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>

            <div class="content-box">
                <div class="table-header" style="flex-wrap: wrap; gap: 12px;">
                    <div>
                        <h3 style="margin: 0;">User Points Card</h3>
                        <?php if ($totalMembersInArea >= 0): ?>
                            <p style="margin: 6px 0 0 0; font-size: 0.9rem; color: #64748b;">
                                <strong><?php echo ($is_admin || $is_special_role) ? 'Total members:' : 'Total members in your area:'; ?></strong>
                                <span style="color: #1e3a8a; font-weight: 700;"><?php echo $totalMembersInArea; ?></span>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <?php if ($is_admin || $is_special_role): ?>
                            <select id="areaFilter" onchange="filterTable()" style="padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; font-family: 'Inter', sans-serif; min-width: 150px;">
                                <option value="">All Areas</option>
                                <?php
                                $uniqueAreas = array_unique(array_filter(array_column($allUsers, 'area')));
                                sort($uniqueAreas);
                                foreach ($uniqueAreas as $a) {
                                    echo '<option value="' . htmlspecialchars($a) . '">Area ' . htmlspecialchars($a) . '</option>';
                                }
                                ?>
                            </select>
                        <?php endif; ?>
                        <input type="text" id="searchInput" placeholder="Search user..."
                            style="width: 300px; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;"
                            onkeyup="filterTable()">
                        <button id="exportPdfBtn" class="btn-primary"
                            style="padding: 10px 20px; white-space: nowrap; height: 42px;">
                            <i class="fas fa-file-pdf"></i> Export as PDF
                        </button>
                    </div>
                </div>

                <table class="modern-table" id="pointsTable">
                    <thead>
                        <tr>
                            <th>Rank</th>
                            <th>NROI ID</th>
                            <th>Name</th>
                            <?php if ($is_admin || $is_special_role): ?>
                                <th>Area</th>
                                <?php if ($is_admin): ?>
                                    <th>Area Coordinator</th>
                                <?php endif; ?>
                            <?php endif; ?>
                            <th style="padding: 15px 20px; text-align: left; font-size: 0.8rem; color: #64748b; text-transform: uppercase; font-weight: 700;">Withdrawal Count</th>
                            <th style="padding: 15px 20px; text-align: left; font-size: 0.8rem; color: #64748b; text-transform: uppercase; font-weight: 700;">TOTAL POINTS (ALL YEARS)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($allUsers)): ?>
                            <tr>
                                <td colspan="<?php echo $is_admin ? '7' : ($is_special_role ? '6' : '5'); ?>"
                                    style="text-align:center; padding: 20px;">No users found.</td>
                            </tr>
                        <?php else: ?>
                            <?php
                            $rank = 1;
                            foreach ($allUsers as $u):
                                ?>
                                <tr
                                    onclick="window.location.href='member_points_summary.php?user_id=<?php echo (int) $u['id']; ?>'">
                                    <td style="font-weight: 700;">
                                        <span class="role-badge"
                                            style="background: #eff6ff; color: #1e40af; font-size: 0.9rem; padding: 6px 14px;">
                                            <?php echo (!empty($u['role']) && $u['role'] !== 'member') ? htmlspecialchars($u['role']) : 'R.O'; ?>
                                        </span>
                                        <?php
                                        $displayRoleU = (!empty($u['role']) && $u['role'] !== 'member') ? $u['role'] : 'R.O';
                                        if ($displayRoleU !== 'AC' && $displayRoleU !== 'AAC'):
                                        ?>
                                        <div style="font-size: 0.7rem; color: #64748b; font-weight: 500; margin-top: 4px; text-align: center;">
                                            <i class="fas fa-info-circle" style="font-size: 0.65rem; opacity: 0.5;"></i>
                                            Status: <?php echo htmlspecialchars(($u['rank'] === 'Regular' || $u['rank'] === 'OJT') ? $u['rank'] : 'Regular'); ?>
                                        </div>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($u['nroi_id'] ?? 'N/A'); ?></td>
                                    <td style="font-weight: 600; color: #1e293b;">
                                        <?php if ($is_admin || $is_officer_role): ?>
                                            <span
                                                style="color: #1e40af;"><?php echo htmlspecialchars(capitalizeWords($u['last_name'] . ', ' . $u['first_name'])); ?></span>
                                        <?php else: ?>
                                            <?php echo htmlspecialchars(capitalizeWords($u['last_name'] . ', ' . $u['first_name'])); ?>
                                        <?php endif; ?>
                                    </td>
                                    <?php if ($is_admin || $is_special_role): ?>
                                        <td>
                                            <?php if ($u['area']): ?>
                                                <span class="area-tag" style="margin:0; font-weight: 600; color: #475569;">
                                                    <i class="fas fa-location-dot"
                                                        style="color:var(--primary-color); font-size: 0.75rem;"></i>
                                                    <?php echo htmlspecialchars($u['area']); ?>
                                                </span>
                                            <?php else: ?>
                                                <span style="color: #cbd5e1; font-size: 0.8rem;">---</span>
                                            <?php endif; ?>
                                        </td>
                                        <?php if ($is_admin): ?>
                                            <td style="font-weight: 500; color: #475569;">
                                                <?php echo htmlspecialchars(capitalizeWords($acMap[trim($u['area'])] ?? '---')); ?>
                                            </td>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    <td style="padding: 15px 20px; text-align: left; font-weight: 700; color: <?php echo $u['withdraw_count'] > 10 ? '#ef4444' : '#1e3a8a'; ?>; font-size: 1.1rem;">
                                        <?php echo $u['withdraw_count']; ?>
                                        <?php if ($u['withdraw_count'] > 10): ?>
                                            <i class="fas fa-exclamation-triangle" style="font-size: 0.8rem; margin-left: 5px;"></i>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 15px 20px; text-align: left; font-weight: 700; color: #1e3a8a; font-size: 1.1rem;">
                                        <?php echo number_format($u['total_points'], 2); ?>
                                    </td>
                                </tr>
                                <?php
                                $rank++;
                            endforeach;
                            ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- PDF Export Hidden Container (Off-screen) -->
    <div style="position: absolute; left: -9999px; top: -9999px; width: 1px; height: 1px; overflow: hidden;">
        <div id="pointsCardForPdf"
            style="width: 1000px; padding: 50px; background: #fff; color: #1e293b; font-family: 'Inter', sans-serif;">
            <div
                style="text-align: center; margin-bottom: 40px; border-bottom: 3px solid #1e3a8a; padding-bottom: 30px;">
                <img src="../assets/images/nroi_logo.png" style="height: 100px; margin-bottom: 15px;">
                <h1 style="margin: 0; font-size: 2.2rem; color: #1e3a8a; letter-spacing: -0.02em;">NATIONAL RANGE
                    OFFICER
                    INSTITUTE</h1>
                <p
                    style="margin: 8px 0 0 0; font-size: 1.2rem; color: #64748b; font-weight: 600; text-transform: uppercase;">
                    Official User Points Card Summary Report</p>
            </div>

            <?php if (!$is_admin && $is_officer_role): ?>
                <div
                    style="margin-bottom: 30px; padding: 10px 0; border-bottom: 2px solid #f1f5f9; display: flex; gap: 30px;">
                    <div>
                        <span
                            style="font-size: 0.8rem; color: #64748b; font-weight: 700; text-transform: uppercase;">Area:</span>
                        <span
                            style="font-size: 1.1rem; font-weight: 800; color: #1e3a8a; margin-left: 5px;"><?php echo htmlspecialchars($_SESSION['area'] ?? 'Not Set'); ?></span>
                    </div>
                    <div>
                        <span style="font-size: 0.8rem; color: #64748b; font-weight: 700; text-transform: uppercase;">Area
                            Coordinator (AC):</span>
                        <span style="font-size: 1.1rem; font-weight: 800; color: #1e3a8a; margin-left: 5px;">
                            <?php
                            $currentArea = trim($_SESSION['area'] ?? '');
                            echo htmlspecialchars(capitalizeWords($acMap[$currentArea] ?? 'Not Set'));
                            ?>
                        </span>
                    </div>
                </div>
            <?php endif; ?>

            <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
                <thead>
                    <tr style="background: #f8fafc; border-bottom: 2px solid #e2e8f0;">
                        <th
                            style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                            RANK/ROLE</th>
                        <th
                            style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                            NROI ID</th>
                        <th
                            style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                            NAME</th>
                        <?php if ($is_admin || $is_special_role): ?>
                            <th
                                style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                AREA</th>
                            <?php if ($is_admin): ?>
                                <th
                                    style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                    AREA COORDINATOR</th>
                            <?php endif; ?>
                        <?php endif; ?>
                        <th
                            style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                            W/D COUNT</th>
                        <th
                            style="padding: 15px; text-align: right; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                            TOTAL POINTS (ALL YEARS)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($allUsers as $u): ?>
                        <tr style="border-bottom: 1px solid #f1f5f9;">
                            <td style="padding: 15px;">
                                <span
                                    style="font-weight: 700; color: #1e40af; background: #eff6ff; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem;">
                                    <?php echo (!empty($u['role']) && $u['role'] !== 'member') ? htmlspecialchars($u['role']) : 'R.O'; ?>
                                </span>
                            </td>
                            <td style="padding: 15px; font-weight: 500;">
                                <?php echo htmlspecialchars($u['nroi_id'] ?? 'N/A'); ?>
                            </td>
                            <td style="padding: 15px; font-weight: 600; color: #0f172a;">
                                <?php echo htmlspecialchars(capitalizeWords($u['last_name'] . ', ' . $u['first_name'])); ?>
                            </td>
                            <?php if ($is_admin || $is_special_role): ?>
                                <td style="padding: 15px; color: #475569;"><?php echo htmlspecialchars($u['area'] ?: '---'); ?>
                                </td>
                                <?php if ($is_admin): ?>
                                    <td style="padding: 15px; color: #475569; font-weight: 500;">
                                        <?php echo htmlspecialchars(capitalizeWords($acMap[trim($u['area'])] ?? '---')); ?>
                                    </td>
                                <?php endif; ?>
                            <?php endif; ?>
                            <td
                                style="padding: 15px; text-align: left; font-weight: 700; color: <?php echo $u['withdraw_count'] > 10 ? '#ef4444' : '#1e3a8a'; ?>; font-size: 1.1rem;">
                                <?php echo $u['withdraw_count']; ?>
                                <?php if ($u['withdraw_count'] > 10): ?>
                                    <span style="font-size: 0.8rem;">⚠️</span>
                                <?php endif; ?>
                            </td>
                            <td
                                style="padding: 15px; text-align: right; font-weight: 800; color: #1e3a8a; font-size: 1.1rem;">
                                <?php echo number_format($u['total_points'], 2); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Summary Page Footer -->
            <div
                style="margin-top: 60px; padding-top: 30px; border-top: 2px solid #1e3a8a; display: flex; justify-content: space-between; align-items: flex-end;">
                <div style="color: #64748b; font-size: 0.9rem; line-height: 1.5;">
                    <div
                        style="font-weight: 700; color: #94a3b8; text-transform: uppercase; font-size: 0.8rem; margin-bottom: 4px;">
                        Report Metadata</div>
                    <div style="display: flex; flex-direction: column;">
                        <span>Generated by NROI Portal</span>
                        <span
                            style="font-weight: 800; color: #475569; font-size: 1rem;"><?php echo date('F d, Y | H:i:s'); ?></span>
                        <span style="font-weight: 600;">Official Summary Report</span>
                    </div>
                </div>

                <?php if ($acSigPathForBulk): ?>
                    <div style="text-align: center; min-width: 280px; color: #1e293b;">
                        <img src="../<?php echo htmlspecialchars($acSigPathForBulk); ?>"
                            style="max-width: 250px; max-height: 100px; display: block; margin: 0 auto;" alt="AC Signature">
                        <div
                            style="border-top: 2px solid #1e293b; font-weight: 800; font-size: 1.2rem; text-transform: uppercase; margin-top: 5px; padding-top: 5px;">
                            <?php echo htmlspecialchars(capitalizeWords($acNameForBulk)); ?>
                        </div>
                        <div style="font-size: 0.95rem; color: #64748b; font-weight: 700;">Area Coordinator</div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Individual Record Summaries (Appended after Bulk List) -->
        <?php foreach ($allUsers as $u): ?>
            <div
                style="page-break-before: always; background: #fff; width: 1000px; padding: 50px; min-height: 1400px; box-sizing: border-box; font-family: 'Inter', sans-serif;">
                <div
                    style="text-align: center; margin-bottom: 40px; border-bottom: 3px solid #1e3a8a; padding-bottom: 30px; position: relative;">
                    <img src="../assets/images/nroi_logo.png" style="height: 100px; margin-bottom: 15px;" class="nroi-logo">
                    <?php if (!empty($u['profile_photo'])): ?>
                        <div style="position: absolute; top: 0; right: 0;">
                            <img src="../<?php echo htmlspecialchars($u['profile_photo']); ?>"
                                style="width: 120px; height: 120px; object-fit: cover; border: 2px solid #e2e8f0; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.05);"
                                alt="Profile Picture">
                        </div>
                    <?php endif; ?>
                    <h1 style="margin: 0; font-size: 2.2rem; color: #1e3a8a; letter-spacing: -0.02em;">NATIONAL RANGE
                        OFFICER
                        INSTITUTE</h1>
                    <p
                        style="margin: 8px 0 0 0; font-size: 1.2rem; color: #64748b; font-weight: 600; text-transform: uppercase;">
                        Official Individual Points Record Summary</p>
                </div>

                <?php
                // Fetch matches for this specific user
                $stmtM = $pdo->prepare("
                (SELECT mp.points, mp.rm_signature, mp.created_at as submitted_at,
                       m.match_name, m.match_level, m.start_date, m.location, m.range_master, m.rm_name, 0 as is_manual
                FROM match_points mp
                JOIN match_schedules m ON mp.match_id = m.id
                WHERE mp.user_id = ?)
                UNION ALL
                (SELECT points, NULL as rm_signature, created_at as submitted_at,
                       match_name, level as match_level, CAST(CONCAT(year, '-01-01') AS DATE) as start_date, location, '---' as range_master, 'Manual Entry' as rm_name, 1 as is_manual
                FROM manual_match_points
                WHERE user_id = ?)
                ORDER BY start_date DESC
            ");
                $stmtM->execute([$u['id'], $u['id']]);
                $userMatches = $stmtM->fetchAll(PDO::FETCH_ASSOC);
                ?>

                <div
                    style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; background: #f8fafc; padding: 20px; border-radius: 12px; border: 1px solid #e2e8f0;">
                    <div>
                        <div style="font-weight: 800; font-size: 1.5rem; color: #1e3a8a;">
                            <?php echo htmlspecialchars(capitalizeWords($u['last_name'] . ', ' . $u['first_name'])); ?>
                        </div>
                        <div style="font-size: 1rem; color: #64748b; font-weight: 600; margin-top: 4px;">
                            NROI ID: <span
                                style="color: #1e293b;"><?php echo htmlspecialchars($u['nroi_id'] ?? '---'); ?></span> |
                            Rank: <span style="color: #1e293b;"><?php echo (!empty($u['role']) && $u['role'] !== 'member') ? htmlspecialchars($u['role']) : 'R.O'; ?></span> |
                            Area: <span style="color: #1e293b;"><?php echo htmlspecialchars($u['area'] ?: '---'); ?></span>
                        </div>
                    </div>
                    <div style="text-align: right;">
                        <div
                            style="font-size: 0.9rem; color: #64748b; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em;">
                            Total Earned (All Years)</div>
                        <div style="font-size: 2.5rem; font-weight: 900; color: #1e3a8a; line-height: 1;">
                            <?php echo number_format($u['total_points'], 2); ?>
                        </div>
                    </div>
                </div>

                <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
                    <thead>
                        <tr style="background: #f1f5f9; border-bottom: 2px solid #e2e8f0;">
                            <th
                                style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                MATCH NAME</th>
                            <th
                                style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                LOCATION</th>
                            <th
                                style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                DISCIPLINE</th>
                            <th
                                style="padding: 15px; text-align: left; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                DATE/LVL</th>
                            <th
                                style="padding: 15px; text-align: right; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700;">
                                POINTS</th>
                            <th
                                style="padding: 15px; text-align: center; font-size: 0.9rem; color: #475569; text-transform: uppercase; font-weight: 700; width: 140px;">
                                RM SIG</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($userMatches)): ?>
                            <tr>
                                <td colspan="6" style="padding: 40px; text-align: center; color: #94a3b8; font-style: italic;">
                                    No
                                    match records found for this year.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($userMatches as $m): ?>
                                <tr style="border-bottom: 1px solid #f1f5f9;">
                                    <td style="padding: 15px; font-weight: 700; color: #0f172a;">
                                        <?php echo htmlspecialchars($m['match_name']); ?>
                                    </td>
                                    <td style="padding: 15px; color: #475569;">
                                        <?php echo htmlspecialchars($m['location'] ?: '---'); ?>
                                    </td>
                                    <td style="padding: 15px; color: #64748b; font-size: 0.75rem; font-weight: 600;">
                                        <?php echo !empty($m['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($m['range_master'])) : '---'; ?>
                                    </td>
                                    <td style="padding: 15px; color: #475569;">
                                        <div style="font-weight: 600;"><?php echo date('M d, Y', strtotime($m['start_date'])); ?>
                                        </div>
                                        <span
                                            style="font-weight: 700; color: #64748b; font-size: 0.75rem; background: #f1f5f9; padding: 2px 6px; border-radius: 4px;">LVL
                                            <?php echo preg_replace('/\D/', '', $m['match_level']); ?></span>
                                    </td>
                                    <td
                                        style="padding: 15px; text-align: right; font-weight: 800; color: #16a34a; font-size: 1.1rem;">
                                        +<?php echo number_format($m['points'], 2); ?></td>
                                    <td style="padding: 15px; text-align: center;">
                                        <?php if ($m['rm_signature']): ?>
                                            <div style="display: flex; flex-direction: column; align-items: center; min-width: 130px;">
                                                <img src="../<?php echo htmlspecialchars($m['rm_signature']); ?>"
                                                    style="max-width: 100px; max-height: 50px; display: block;">
                                                <div style="font-size: 0.75rem; font-weight: 800; margin-top: 4px; color: #1e293b;">
                                                    <?php echo htmlspecialchars($m['rm_name'] ?: 'Range Master'); ?>
                                                </div>
                                                <div style="font-size: 0.65rem; color: #94a3b8; font-weight: 600;">
                                                    <?php echo date('M d, Y | h:i A', strtotime($m['submitted_at'])); ?>
                                                </div>
                                            </div>
                                        <? else: ?>
                                            <span style="color: #cbd5e1;">---</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>

                <!-- Authenticated AC Signature at the bottom of each individual page -->
                <div
                    style="margin-top: auto; padding-top: 50px; display: flex; justify-content: space-between; align-items: flex-end; border-top: 2px solid #1e3a8a;">
                    <div style="color: #64748b; font-size: 0.9rem; line-height: 1.5;">
                        <div
                            style="font-weight: 700; color: #94a3b8; text-transform: uppercase; font-size: 0.8rem; margin-bottom: 4px;">
                            Record Verification</div>
                        <div style="display: flex; flex-direction: column;">
                            <span>Generated by NROI Portal</span>
                            <span
                                style="font-weight: 800; color: #475569; font-size: 1rem;"><?php echo date('F d, Y | H:i:s'); ?></span>
                            <span style="font-weight: 600;">Official Individual Report</span>
                        </div>
                    </div>

                    <?php if ($acSigPathForBulk): ?>
                        <div style="text-align: center; min-width: 280px; color: #1e293b;">
                            <img src="../<?php echo htmlspecialchars($acSigPathForBulk); ?>"
                                style="max-width: 250px; max-height: 100px; display: block; margin: 0 auto;" alt="AC Signature">
                                 <div
                                     style="border-top: 2px solid #1e293b; font-weight: 800; font-size: 1.2rem; text-transform: uppercase; margin-top: 5px; padding-top: 5px;">
                                     <?php echo htmlspecialchars(capitalizeWords($acNameForBulk)); ?>
                                 </div>
                            <div style="font-size: 0.95rem; color: #64748b; font-weight: 700;">Area Coordinator</div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');
        if (profileToggle) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });
        }
        document.addEventListener('click', () => profileDropdown?.classList.remove('active'));
        
        function sortTable(n) {
            var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById("pointsTable");
            switching = true;
            dir = "asc";
            while (switching) {
                switching = false;
                rows = table.rows;
                for (i = 1; i < (rows.length - 1); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("TD")[n];
                    y = rows[i + 1].getElementsByTagName("TD")[n];
                    
                    let xContent = x.textContent || x.innerText;
                    let yContent = y.textContent || y.innerText;
                    
                    // Specific handling for points and numbers
                    if (n >= 3) { // Numeric columns (Area, Withdrawal Count, Total Points) are from index 3 onwards depending on role
                         // But Area might be a string. Withdrawal and Total Points are definitely numeric.
                         // Let's try to parse as float if it looks like a number.
                         let xVal = parseFloat(xContent.replace(/[^0-9.-]+/g,""));
                         let yVal = parseFloat(yContent.replace(/[^0-9.-]+/g,""));
                         
                         if (!isNaN(xVal) && !isNaN(yVal)) {
                             if (dir == "asc") {
                                 if (xVal > yVal) { shouldSwitch = true; break; }
                             } else if (dir == "desc") {
                                 if (xVal < yVal) { shouldSwitch = true; break; }
                             }
                         } else {
                             // String comparison
                             if (dir == "asc") {
                                 if (xContent.toLowerCase() > yContent.toLowerCase()) { shouldSwitch = true; break; }
                             } else if (dir == "desc") {
                                 if (xContent.toLowerCase() < yContent.toLowerCase()) { shouldSwitch = true; break; }
                             }
                         }
                    } else {
                        // String comparison for Rank, ID, Name
                        if (dir == "asc") {
                            if (xContent.toLowerCase() > yContent.toLowerCase()) { shouldSwitch = true; break; }
                        } else if (dir == "desc") {
                            if (xContent.toLowerCase() < yContent.toLowerCase()) { shouldSwitch = true; break; }
                        }
                    }
                }
                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                    switchcount++;
                } else {
                    if (switchcount == 0 && dir == "asc") {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }

        function filterTable() {
            const searchInput = document.getElementById('searchInput');
            const areaFilter = document.getElementById('areaFilter');
            
            const searchText = searchInput ? searchInput.value.toLowerCase() : '';
            const areaValue = areaFilter ? areaFilter.value.toLowerCase() : '';
            
            const table = document.getElementById('pointsTable');
            const tr = table.getElementsByTagName('tr');

            // Find the index of the Area column for the roles that have it
            let areaColIdx = -1;
            const headers = table.getElementsByTagName('th');
            for(let i=0; i<headers.length; i++) {
                if(headers[i].innerText.trim().toLowerCase().includes('area') && !headers[i].innerText.trim().toLowerCase().includes('coordinator')) {
                    areaColIdx = i;
                    break;
                }
            }

            for (let i = 1; i < tr.length; i++) {
                const td = tr[i].getElementsByTagName('td');
                let foundSearch = false;
                let foundArea = true; // Default true if no area filter selected

                // Check text search across all columns
                if (searchText === '') {
                    foundSearch = true;
                } else {
                    for (let j = 0; j < td.length; j++) {
                        if (td[j]) {
                            const txtValue = td[j].textContent || td[j].innerText;
                            if (txtValue.toLowerCase().indexOf(searchText) > -1) {
                                foundSearch = true;
                                break;
                            }
                        }
                    }
                }

                // Check Area filter if one is selected and the column exists
                if (areaValue !== '' && areaColIdx > -1 && td[areaColIdx]) {
                    const areaText = td[areaColIdx].textContent || td[areaColIdx].innerText;
                    if (areaText.trim().toLowerCase() !== areaValue) {
                        foundArea = false;
                    }
                }

                tr[i].style.display = (foundSearch && foundArea) ? '' : 'none';
            }
        }

        function exportPointsPdf() {
            var btn = document.getElementById('exportPdfBtn');
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating…';
            }

            var el = document.getElementById('pointsCardForPdf');
            if (!el) {
                if (btn) {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';
                }
                return;
            }

            // Dynamically load libraries
            var script = document.createElement('script');
            script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
            script.onload = function () {
                var s2 = document.createElement('script');
                s2.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
                s2.onload = function () {
                    // Pre-load imaging
                    var imgs = el.querySelectorAll('img');
                    var loaded = 0, need = imgs.length;

                    function onImgLoad() {
                        loaded++;
                        if (loaded >= need) doExport();
                    }

                    imgs.forEach(function (img) {
                        if (img.complete) onImgLoad();
                        else img.addEventListener('load', onImgLoad);
                    });

                    if (need === 0) doExport();

                    function doExport() {
                        const { jsPDF } = window.jspdf;
                        const pdf = new jsPDF('p', 'mm', 'a4');
                        const pageW = pdf.internal.pageSize.getWidth();
                        const pageH = pdf.internal.pageSize.getHeight();

                        // 1. Export the Sumary Page
                        html2canvas(el, {
                            scale: 1.5,
                            useCORS: true,
                            allowTaint: true,
                            logging: false,
                            backgroundColor: '#ffffff'
                        }).then(function (summaryCanvas) {
                            var sW = summaryCanvas.width;
                            var sH = summaryCanvas.height;
                            var sRatio = Math.min(pageW / (sW * 0.264583), pageH / (sH * 0.264583));
                            var finalSW = (sW * 0.264583) * sRatio;
                            var finalSH = (sH * 0.264583) * sRatio;
                            pdf.addImage(summaryCanvas.toDataURL('image/png'), 'PNG', (pageW - finalSW) / 2, 10, finalSW, finalSH);

                            // 2. Export each Individual Page
                            const individualPages = document.querySelectorAll('div[style*="page-break-before: always"]');
                            let pChain = Promise.resolve();

                            individualPages.forEach((pageEl, idx) => {
                                pChain = pChain.then(() => {
                                    return html2canvas(pageEl, {
                                        scale: 1.5,
                                        useCORS: true,
                                        allowTaint: true,
                                        logging: false,
                                        backgroundColor: '#ffffff'
                                    }).then(pageCanvas => {
                                        pdf.addPage();
                                        var pW = pageCanvas.width;
                                        var pH = pageCanvas.height;
                                        var pRatio = Math.min(pageW / (pW * 0.264583), pageH / (pH * 0.264583));
                                        var finalPW = (pW * 0.264583) * pRatio;
                                        var finalPH = (pH * 0.264583) * pRatio;
                                        pdf.addImage(pageCanvas.toDataURL('image/png'), 'PNG', (pageW - finalPW) / 2, 10, finalPW, finalPH);
                                    });
                                });
                            });

                            return pChain.then(() => {
                                pdf.save('NROI-Bulk-Points-Report-<?php echo date('Y-m-d'); ?>.pdf');
                                if (btn) {
                                    btn.disabled = false;
                                    btn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';
                                }
                            });
                        }).catch(function (err) {
                            console.error('PDF export failed:', err);
                            alert('PDF export failed. Please try again.');
                            if (btn) {
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';
                            }
                        });
                    }
                };
                document.head.appendChild(s2);
            };
            document.head.appendChild(script);
        }

        document.getElementById('exportPdfBtn').addEventListener('click', exportPointsPdf);
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>