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

$allowedRoles = ['AC', 'AAC', 'NROI', 'PPSA'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'] ?? '', $allowedRoles)) {
    header("Location: ../index.php");
    exit;
}

$userId = (int) $_SESSION['user_id'];
$role = $_SESSION['user_role'] ?? '';
$firstName = $_SESSION['name'] ?? 'User';
$is_special = in_array(strtoupper($role), ['PPSA', 'NROI']);

// User full name and NROI ID for summary/PDF
$stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id, profile_photo FROM users WHERE id = ?");
$stmtUser->execute([$userId]);
$userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);
$userFullName = $userInfo ? trim(($userInfo['last_name'] ?? '') . ', ' . ($userInfo['first_name'] ?? '')) : $firstName;
$userNroiId = $userInfo['nroi_id'] ?? '';

// 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'];

// Handle manual match points actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_action'])) {
    $mAction = $_POST['manual_action'];
    try {
        // Collect disciplines from array to string
        $disciplinesArr = $_POST['disciplines'] ?? [];
        $disciplineStr = !empty($disciplinesArr) ? implode(', ', array_map('trim', $disciplinesArr)) : 'Handgun';

        if ($mAction === 'add') {
            $stmt = $pdo->prepare("INSERT INTO manual_match_points (user_id, recorded_by_user_id, recorded_by_admin_id, match_name, discipline, year, month, level, role, points, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $userId,
                $_SESSION['user_id'] ?? null,
                $_SESSION['admin_id'] ?? null,
                $_POST['match_name'],
                $disciplineStr,
                (int) $_POST['year'],
                !empty($_POST['month']) ? (int) $_POST['month'] : null,
                $_POST['level'],
                $_POST['role'],
                (float) $_POST['points'],
                $_POST['location'] ?? '---'
            ]);
            header("Location: my_points.php?success=added");
            exit;
        } elseif ($mAction === 'edit') {
            $mId = (int) $_POST['record_id'];
            $stmtCheck = $pdo->prepare("SELECT id FROM manual_match_points WHERE id = ? AND (recorded_by_user_id = ? OR recorded_by_admin_id = ?)");
            $stmtCheck->execute([$mId, $_SESSION['user_id'] ?? 0, $_SESSION['admin_id'] ?? 0]);
            if (!$stmtCheck->fetch())
                throw new Exception("Unauthorized to edit this record.");
            $stmt = $pdo->prepare("UPDATE manual_match_points SET match_name=?, discipline=?, year=?, month=?, level=?, role=?, points=?, location=? WHERE id=?");
            $stmt->execute([
                $_POST['match_name'],
                $disciplineStr,
                (int) $_POST['year'],
                !empty($_POST['month']) ? (int) $_POST['month'] : null,
                $_POST['level'],
                $_POST['role'],
                (float) $_POST['points'],
                $_POST['location'] ?? '---',
                $mId
            ]);
            header("Location: my_points.php?success=updated");
            exit;
        } elseif ($mAction === 'delete') {
            $mId = (int) $_POST['record_id'];
            $stmtCheck = $pdo->prepare("SELECT id FROM manual_match_points WHERE id = ? AND (recorded_by_user_id = ? OR recorded_by_admin_id = ?)");
            $stmtCheck->execute([$mId, $_SESSION['user_id'] ?? 0, $_SESSION['admin_id'] ?? 0]);
            if (!$stmtCheck->fetch())
                throw new Exception("Unauthorized to delete this record.");
            $pdo->prepare("DELETE FROM manual_match_points WHERE id = ?")->execute([$mId]);
            header("Location: my_points.php?success=deleted");
            exit;
        }
    } catch (Exception $e) {
        $manual_error = $e->getMessage();
    }
}

// Year filter (default 'all' for all years)
$yearParam = $_GET['year'] ?? 'all';
$year = $yearParam === 'all' ? 'all' : (int) $yearParam;

if ($year !== 'all' && ($year < 2000 || $year > 2100)) {
    $year = 'all';
}

// Total points calculation including manual points
$totalManualSql = "SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = ?";
if ($year !== 'all') {
    $totalManualSql .= " AND year = ?";
}
$stmtManualTotal = $pdo->prepare($totalManualSql);
if ($year !== 'all') {
    $stmtManualTotal->execute([$userId, $year]);
} else {
    $stmtManualTotal->execute([$userId]);
}
$manualTotalSum = (float) $stmtManualTotal->fetchColumn();

$totalSql = "SELECT COALESCE(SUM(mp.points), 0) FROM match_points mp JOIN match_schedules m ON mp.match_id = m.id WHERE mp.user_id = ? AND mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT'";
if ($year !== 'all') {
    $totalSql .= " AND YEAR(m.start_date) = ?";
}
$stmtTotal = $pdo->prepare($totalSql);
if ($year !== 'all') {
    $stmtTotal->execute([$userId, $year]);
} else {
    $stmtTotal->execute([$userId]);
}
$yearTotal = (float) $stmtTotal->fetchColumn() + $manualTotalSum;

// Matches including manual points
// Dynamic role recognition for all assignment tables
$roleCases = "";
try {
    $stmtTables = $pdo->query("SHOW TABLES LIKE 'match_%_assignments'");
    $assignmentTables = $stmtTables->fetchAll(PDO::FETCH_COLUMN);

    usort($assignmentTables, function ($a, $b) {
        $priority = ['match_states_assignments' => 1, 'match_stats_assignments' => 2, 'match_chrono_assignments' => 3, 'match_equipment_check_assignments' => 4];
        $pA = $priority[$a] ?? 99;
        $pB = $priority[$b] ?? 99;
        return $pA - $pB;
    });

    foreach ($assignmentTables as $tbl) {
        if ($tbl === 'match_range_master_assignments')
            continue;
        $roleCases .= "               WHEN (SELECT role FROM `$tbl` WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1) > '' 
                    THEN (SELECT role FROM `$tbl` WHERE match_id = m.id AND submitted_by = mp.user_id LIMIT 1)\n";
    }
} catch (Exception $e) {
}

$matchesSql = "
    (SELECT mp.id as mp_id, mp.points, mp.rm_signature, mp.created_at as submitted_at,
           m.id as match_id, m.match_name, m.match_level, m.start_date, m.end_date, m.location, m.range_master, m.rm_name,
           CASE 
               WHEN m.rm_id = ? THEN 'Range Master'
               WHEN rma.role IS NOT NULL AND rma.role != '' THEN rma.role
$roleCases               ELSE '---'
           END as assigned_role,
           NULL as recorded_by_user_id, NULL as recorded_by_admin_id, 0 as is_manual, NULL as month
    FROM match_points mp
    JOIN match_schedules m ON mp.match_id = m.id
    LEFT JOIN match_range_master_assignments rma ON rma.match_id = m.id AND rma.submitted_by = mp.user_id
    WHERE mp.user_id = ? AND mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' " . ($year !== 'all' ? " AND YEAR(m.start_date) = ?" : "") . ")
    UNION ALL
    (SELECT id as mp_id, points, NULL as rm_signature, created_at as submitted_at,
           NULL as match_id, match_name, level as match_level, 
           CASE 
               WHEN month IS NOT NULL AND month > 0 THEN CAST(CONCAT(year, '-', LPAD(month, 2, '0'), '-01') AS DATE)
               ELSE CAST(CONCAT(year, '-01-01') AS DATE)
           END as start_date,
           CASE 
               WHEN month IS NOT NULL AND month > 0 THEN CAST(CONCAT(year, '-', LPAD(month, 2, '0'), '-01') AS DATE)
               ELSE CAST(CONCAT(year, '-01-01') AS DATE)
           END as end_date,
           location, discipline as range_master, 'Manual Entry' as rm_name,
           role as assigned_role,
           recorded_by_user_id, recorded_by_admin_id, 1 as is_manual,
           month
    FROM manual_match_points
    WHERE user_id = ? " . ($year !== 'all' ? " AND year = ?" : "") . ")
    ORDER BY start_date DESC
";

$stmtMatches = $pdo->prepare($matchesSql);
$params = [$userId, $userId];
if ($year !== 'all')
    $params[] = $year;
$params[] = $userId;
if ($year !== 'all')
    $params[] = $year;

$stmtMatches->execute($params);
$matches = $stmtMatches->fetchAll(PDO::FETCH_ASSOC);

// Calculate role statistics for web display
$roleStats = [];
foreach ($matches as $m) {
    $r = $m['assigned_role'] ?? '---';
    if ($r === '---')
        continue;
    $roleStats[$r] = ($roleStats[$r] ?? 0) + 1;
}
arsort($roleStats);
$maxCount = !empty($roleStats) ? max($roleStats) : 1;

$is_ac = ($role === 'AC');
$is_aac = ($role === 'AAC');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Points | 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .year-select-wrap {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .year-select-wrap select {
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.95rem;
        }

        .total-card {
            background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
            color: white;
            padding: 24px;
            border-radius: 16px;
            margin-bottom: 24px;
            box-shadow: 0 10px 25px rgba(30, 58, 138, 0.2);
        }

        .total-card h3 {
            margin: 0 0 8px 0;
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .total-card .value {
            font-size: 2.5rem;
            font-weight: 800;
        }

        .match-row {
            cursor: pointer;
            transition: background 0.2s;
        }

        .match-row:hover {
            background: #f8fafc;
        }

        .modal-content .signature-box {
            max-width: 280px;
            margin: 15px 0;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 10px;
            background: #f8fafc;
        }

        .modal-content .signature-box img {
            width: 100%;
            height: auto;
            display: block;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 30px;
            border-radius: 16px;
            width: 500px;
            max-width: 90%;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f1f5f9;
        }

        .modal-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e3a8a;
        }

        .close-modal {
            font-size: 1.5rem;
            color: #64748b;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close-modal:hover {
            color: #ef4444;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-size: 0.85rem;
            font-weight: 600;
            color: #475569;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.95rem;
        }

        .action-btns {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            border-radius: 4px;
            transition: all 0.2s;
            font-size: 0.9rem;
        }

        .btn-edit {
            color: #2563eb;
        }

        .btn-edit:hover {
            background: #eff6ff;
        }

        .btn-delete {
            color: #ef4444;
        }

        .btn-delete:hover {
            background: #fef2f2;
        }

        /* NEW ROLE SUMMARY STYLES */
        .role-summary-container {
            background: white;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid #e2e8f0;
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }

        .role-summary-list {
            flex: 1;
            min-width: 250px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            justify-content: center;
        }

        .role-summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            background: #f8fafc;
            border-radius: 10px;
            border-left: 4px solid #3b82f6;
            transition: transform 0.2s;
        }

        .role-summary-item:hover {
            transform: translateX(5px);
            background: #f1f5f9;
        }

        .role-summary-item.active-filter {
            background: #e0f2fe;
            border-right: 2px solid #2563eb;
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.1);
        }

        .role-summary-name {
            font-weight: 600;
            color: #1e3a8a;
            font-size: 0.95rem;
        }

        .role-summary-count {
            background: #dae5ff;
            color: #1e40af;
            padding: 4px 10px;
            border-radius: 20px;
            font-weight: 800;
            font-size: 0.9rem;
        }

        .role-chart-wrapper {
            flex: 2;
            min-width: 350px;
            height: 250px;
            position: relative;
        }

        @media screen and (max-width: 768px) {
            .role-summary-container {
                flex-direction: column;
            }

            .role-chart-wrapper {
                min-width: 100%;
                height: 200px;
            }
        }

        /* Summary block for PDF export */
        #pointsSummaryForPdf {
            background: #fff;
            color: #1e293b;
            padding: 24px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            max-width: 900px;
            position: relative;
        }

        #pointsSummaryForPdf .profile-pic {
            position: absolute;
            top: 24px;
            right: 24px;
            width: 100px;
            height: 100px;
            object-fit: cover;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        #pointsSummaryForPdf .summary-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: #1e3a8a;
            margin-bottom: 4px;
            padding-right: 120px;
        }

        #pointsSummaryForPdf .summary-sub {
            font-size: 0.85rem;
            color: #64748b;
            margin-bottom: 20px;
        }

        #pointsSummaryForPdf .summary-total {
            background: #f1f5f9;
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        #pointsSummaryForPdf .summary-total .label {
            font-size: 0.8rem;
            color: #64748b;
        }

        #pointsSummaryForPdf .summary-total .val {
            font-size: 1.75rem;
            font-weight: 800;
            color: #16a34a;
        }

        #pointsSummaryForPdf .summary-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }

        #pointsSummaryForPdf .summary-table th,
        #pointsSummaryForPdf .summary-table td {
            border: 1px solid #e2e8f0;
            padding: 10px 12px;
            text-align: left;
        }

        #pointsSummaryForPdf .summary-table th {
            background: #f8fafc;
            font-weight: 700;
            color: #475569;
        }

        #pointsSummaryForPdf .summary-table .sig-cell {
            width: 100px;
            text-align: center;
        }

        #pointsSummaryForPdf .summary-table .sig-cell img {
            max-width: 90px;
            max-height: 45px;
            object-fit: contain;
            display: inline-block;
        }

        .no-print {}

        @media print {
            .no-print {
                display: none !important;
            }
        }

        /* Role Stats Chart Styles */
        .role-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }

        .role-stat-card {
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s;
        }

        .role-stat-card:hover {
            transform: translateY(-2px);
            border-color: #2563eb;
        }

        .role-stat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .role-stat-name {
            font-size: 0.8rem;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.02em;
        }

        .role-stat-count {
            font-size: 1.25rem;
            font-weight: 800;
            color: #1e3a8a;
        }

        .role-stat-progress-bg {
            height: 8px;
            background: #f1f5f9;
            border-radius: 4px;
            overflow: hidden;
        }

        .role-stat-progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #2563eb, #3b82f6);
            border-radius: 4px;
        }

        .discipline-checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
            gap: 12px;
            background: #f8fafc;
            padding: 15px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            max-height: 180px;
            overflow-y: auto;
        }

        .discipline-check-label {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.85rem;
            font-weight: 600;
            color: #475569;
            cursor: pointer;
            padding: 6px 10px;
            border-radius: 8px;
            transition: all 0.2s;
            border: 1px solid transparent;
        }

        .discipline-check-label:hover {
            background: white;
            border-color: #cbd5e1;
            color: #2563eb;
        }

        .discipline-check-label input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #2563eb;
            margin: 0;
        }
    </style>
</head>

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

    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($role === 'AC')
                    echo 'A.C';
                elseif ($role === 'AAC')
                    echo 'A.A.C';
                else
                    echo htmlspecialchars($role);
                ?>
            </div>
        </div>
        <ul class="sidebar-menu">
            <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_ac || $is_aac): ?>
                <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>
                <li class="sidebar-item">
                    <a href="points_card.php" class="sidebar-link">
                        <i class="fas fa-id-card"></i> Points Card
                    </a>
                </li>
            <?php else: ?>
                <?php if (!$is_special): ?>
                    <li class="sidebar-item">
                        <a href="matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                <?php else: ?>
                    <li class="sidebar-item">
                        <a href="points_card.php" class="sidebar-link">
                            <i class="fas fa-id-card"></i> Points Card
                        </a>
                    </li>
                <?php endif; ?>
            <?php endif; ?>
            <?php if (!$is_special): ?>
                <li class="sidebar-item">
                    <a href="my_points.php" class="sidebar-link active">
                        <i class="fas fa-star"></i> My Points
                    </a>
                </li>
            <?php endif; ?>
        </ul>
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">
                    <?php echo strtoupper(substr($role, 0, 2)); ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name"><?php echo htmlspecialchars(capitalizeWords($firstName)); ?></div>
                    <div class="sidebar-user-role"><?php echo htmlspecialchars($role); ?> 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="../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: 20px; align-items: center; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 20px; margin-bottom: 24px; background: transparent; padding-left: 0; padding-right: 0;">
                    <h3
                        style="margin: 0; font-size: 1.5rem; font-weight: 800; color: #1e293b; letter-spacing: -0.02em;">
                        My Points
                    </h3>
                    <div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
                        <div class="year-select-wrap"
                            style="background: #f8fafc; padding: 4px 4px 4px 12px; border-radius: 12px; display: flex; align-items: center; gap: 8px; border: 1px solid #e2e8f0; transition: all 0.2s;">
                            <label for="yearSelect"
                                style="font-size: 0.7rem; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.05em;">Year</label>
                            <select id="yearSelect"
                                style="padding: 8px 16px; border: none; background: white; border-radius: 8px; font-weight: 700; color: #1e293b; box-shadow: 0 1px 2px rgba(0,0,0,0.05); outline: none; cursor: pointer;"
                                onchange="window.location.href='my_points.php?year='+this.value">
                                <?php
                                $currentY = (int) date('Y');
                                echo '<option value="all"' . ($year === "all" ? " selected" : "") . '>All Years</option>';
                                for ($y = $currentY; $y >= 2020; $y--) {
                                    $sel = ($year !== "all" && (int) $year === $y) ? ' selected' : '';
                                    echo "<option value=\"$y\"$sel>$y</option>";
                                }
                                ?>
                            </select>
                        </div>
                        <div class="header-actions" style="display: flex; gap: 10px;">
                            <button type="button" onclick="openManualModal()" class="btn-success"
                                style="width: 160px; height: 40px; padding: 0; font-size: 0.8rem; background: #10b981; border:none; border-radius:10px; color:white; cursor:pointer; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; gap: 6px; box-shadow: 0 4px 6px -1px rgba(16, 185, 129, 0.2); transition: all 0.2s;">
                                <i class="fas fa-calendar-plus" style="font-size: 0.9rem;"></i> Add Prev. Points
                            </button>
                            <button type="button" id="exportPdfBtn" class="btn-primary"
                                style="width: 160px; height: 40px; padding: 0; font-size: 0.8rem; border-radius:10px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; gap: 6px; box-shadow: 0 4px 10px rgba(37, 99, 235, 0.3); transition: all 0.2s;">
                                <i class="fas fa-file-pdf" style="font-size: 0.9rem;"></i> Export as PDF
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Removed total-card as requested -->

                <!-- Summary (for PDF export): total + list of matches with points and RM signature -->
                <h4
                    style="color: #1e293b; margin: 40px 0 24px 0; font-size: 1.25rem; font-weight: 800; text-align: center; text-transform: uppercase; letter-spacing: 0.1em; position: relative;">
                    SUMMARY ROLES TRACKING
                    <span
                        style="display: block; width: 60px; height: 4px; background: #2563eb; margin: 10px auto 0; border-radius: 2px;"></span>
                </h4>
                <div id="pointsSummaryForPdf">
                    <?php if (!empty($userInfo['profile_photo'])): ?>
                        <img src="../<?php echo htmlspecialchars($userInfo['profile_photo']); ?>" alt="Profile Picture"
                            class="profile-pic">
                    <?php endif; ?>
                    <div class="summary-title">Match Point Card — Summary</div>
                    <div class="summary-sub">
                        <?php echo htmlspecialchars(capitalizeWords($userFullName)); ?><?php if ($userNroiId): ?> ·
                            NROI ID: <?php echo htmlspecialchars($userNroiId); ?><?php endif; ?> · Year:
                        <?php echo $year === 'all' ? 'All Years' : $year; ?>
                    </div>
                    <div class="summary-total">
                        <div class="label">Total points <?php echo $year === 'all' ? '(All Years)' : "in $year"; ?>
                        </div>
                        <div class="val"><?php echo number_format($yearTotal, 2); ?></div>
                    </div>
                    <table class="summary-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Match Name</th>
                                <th>Location</th>
                                <th>Discipline</th>
                                <th>Date</th>
                                <th>Level</th>
                                <th>Points</th>
                                <th>RM Name and Signature</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($matches)): ?>
                                <tr>
                                    <td colspan="8" style="text-align: center; color: #64748b;">No matches for this year.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($matches as $i => $row): ?>
                                    <tr>
                                        <td><?php echo $i + 1; ?></td>
                                        <td style="font-weight: 600;"><?php echo htmlspecialchars($row['match_name']); ?></td>
                                        <td><?php echo htmlspecialchars($row['location'] ?? '---'); ?></td>
                                        <td><?php echo !empty($row['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($row['range_master'])) : '---'; ?>
                                        </td>
                                        <td>
                                            <?php
                                            if ($row['is_manual']) {
                                                if (!empty($row['month']) && $row['month'] > 0) {
                                                    echo date('F', mktime(0, 0, 0, $row['month'], 10)) . ' ' . date('Y', strtotime($row['start_date']));
                                                } else {
                                                    echo date('Y', strtotime($row['start_date']));
                                                }
                                            } else {
                                                echo date('M d, Y', strtotime($row['start_date']));
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo preg_replace('/\D/', '', $row['match_level']); ?></td>
                                        <td style="font-weight: 700; color: #16a34a;">
                                            +<?php echo number_format($row['points'], 2); ?></td>
                                        <td class="sig-cell">
                                            <?php if (!empty($row['rm_signature'])): ?>
                                                <div style="text-align: center;">
                                                    <img src="../<?php echo htmlspecialchars($row['rm_signature']); ?>" alt="RM Sig"
                                                        loading="lazy"
                                                        style="max-width: 120px; max-height: 60px; display: block; margin: 0 auto;"
                                                        onerror="this.style.display='none'; this.nextElementSibling.style.display='inline';">
                                                    <span style="display: none; font-size: 0.75rem; color: #94a3b8;">—</span>
                                                    <div
                                                        style="font-size: 0.8rem; font-weight: 700; margin-top: 5px; color: #1e293b; border-top: 1px solid #e2e8f0; padding-top: 2px;">
                                                        <?php echo htmlspecialchars(!empty($row['rm_name']) ? capitalizeWords($row['rm_name']) : 'Range Master'); ?>
                                                    </div>
                                                    <div style="font-size: 0.75rem; color: #64748b; line-height: 1.2;">
                                                        <?php echo date('M d, Y', strtotime($row['submitted_at'])); ?><br>
                                                        <?php echo date('h:i A', strtotime($row['submitted_at'])); ?>
                                                    </div>
                                                </div>
                                            <?php elseif ($row['is_manual']): ?>
                                                <div style="text-align: center;">
                                                    <span style="font-size: 0.7rem; color: #64748b; font-weight: 700;">[MANUAL
                                                        ENTRY]</span>
                                                    <?php
                                                    $canEdit = ($row['recorded_by_user_id'] == ($userId) || $row['recorded_by_admin_id'] == ($_SESSION['admin_id'] ?? 0));
                                                    if ($canEdit):
                                                        ?>
                                                        <div class="action-btns" style="margin-top: 5px; justify-content: center;">
                                                            <button title="Edit" class="action-btn btn-edit"
                                                                onclick="event.stopPropagation(); editManual(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <form method="POST" action="my_points.php?year=<?php echo $yearParam; ?>"
                                                                onsubmit="return confirm('Delete this manual record?');"
                                                                style="display:inline;">
                                                                <input type="hidden" name="manual_action" value="delete">
                                                                <input type="hidden" name="record_id"
                                                                    value="<?php echo $row['mp_id']; ?>">
                                                                <button type="submit" title="Delete" class="action-btn btn-delete">
                                                                    <i class="fas fa-trash"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else: ?>
                                                <span style="font-size: 0.75rem; color: #94a3b8;">—</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <h4 style="color: #64748b; margin: 24px 0 12px 0; font-size: 0.95rem;">Matches I participated in
                    (<?php echo $year === 'all' ? 'All Years' : $year; ?>)</h4>

                <?php if (!empty($roleStats)): ?>
                    <div class="role-summary-container">
                        <div class="role-summary-list">
                            <?php
                            $roleColors = ['#2563eb', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899'];
                            $idx = 0;
                            foreach ($roleStats as $rName => $rCount):
                                $color = $roleColors[$idx % count($roleColors)];
                                ?>
                                <div class="role-summary-item"
                                    style="border-left-color: <?php echo $color; ?>; cursor: pointer;"
                                    onclick="filterByRole(this, '<?php echo htmlspecialchars($rName); ?>')"
                                    data-role="<?php echo htmlspecialchars($rName); ?>">
                                    <span class="role-summary-name"><?php echo htmlspecialchars($rName); ?></span>
                                    <span class="role-summary-count"><?php echo $rCount; ?></span>
                                </div>
                                <?php
                                $idx++;
                            endforeach; ?>
                        </div>
                        <div class="role-chart-wrapper">
                            <canvas id="roleTrendChart"></canvas>
                        </div>
                    </div>

                    <?php
                    // Prepare data for the chart
                    if ($year === 'all') {
                        // Aggregate by Year
                        $matchYears = [];
                        foreach ($matches as $m) {
                            $y = date('Y', strtotime($m['start_date']));
                            $matchYears[] = $y;
                        }
                        $uniqueYears = array_unique($matchYears);
                        sort($uniqueYears);
                        if (empty($uniqueYears))
                            $uniqueYears = [date('Y')];

                        $labels = $uniqueYears;
                    } else {
                        // Aggregate by Month
                        $labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                    }

                    $datasets = [];
                    $idx = 0;
                    foreach ($roleStats as $rName => $rCount) {
                        if ($rName === '---')
                            continue;

                        if ($year === 'all') {
                            $data = array_fill(0, count($labels), 0);
                            foreach ($matches as $m) {
                                if (($m['assigned_role'] ?? '---') === $rName) {
                                    $y = date('Y', strtotime($m['start_date']));
                                    $lIdx = array_search($y, $labels);
                                    if ($lIdx !== false)
                                        $data[$lIdx]++;
                                }
                            }
                        } else {
                            $data = array_fill(0, 12, 0);
                            foreach ($matches as $m) {
                                if (($m['assigned_role'] ?? '---') === $rName) {
                                    $mIdx = (int) date('n', strtotime($m['start_date'])) - 1;
                                    $data[$mIdx]++;
                                }
                            }
                        }

                        $color = $roleColors[$idx % count($roleColors)];
                        $datasets[] = [
                            'label' => $rName,
                            'data' => $data,
                            'borderColor' => $color,
                            'backgroundColor' => $color . '20',
                            'tension' => 0.4,
                            'fill' => false,
                            'borderWidth' => 3,
                            'pointRadius' => 4,
                            'pointHoverRadius' => 6
                        ];
                        $idx++;
                    }
                    ?>

                    <script>
                        document.addEventListener('DOMContentLoaded', function () {
                            const ctx = document.getElementById('roleTrendChart').getContext('2d');
                            new Chart(ctx, {
                                type: 'line',
                                data: {
                                    labels: <?php echo json_encode($labels); ?>,
                                    datasets: <?php echo json_encode($datasets); ?>
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        legend: {
                                            position: 'top',
                                            labels: {
                                                usePointStyle: true,
                                                boxWidth: 8,
                                                padding: 15,
                                                font: { size: 10, family: 'Inter' }
                                            }
                                        },
                                        tooltip: {
                                            mode: 'index',
                                            intersect: false,
                                        }
                                    },
                                    scales: {
                                        y: {
                                            beginAtZero: true,
                                            ticks: { stepSize: 1, precision: 0, font: { size: 10 } },
                                            grid: { borderDash: [5, 5], color: '#e2e8f0' }
                                        },
                                        x: {
                                            ticks: { font: { size: 10 } },
                                            grid: { display: false }
                                        }
                                    }
                                }
                            });
                        });
                    </script>
                <?php endif; ?>
                <table class="modern-table">
                    <thead>
                        <tr>
                            <th>Match Name</th>
                            <th>Location</th>
                            <th>Discipline</th>
                            <th>Role</th>
                            <th>Date</th>
                            <th>Level</th>
                            <th>Points</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($matches)): ?>
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 40px; color: #64748b;">
                                    <i class="fas fa-calendar-times"
                                        style="font-size: 2rem; display: block; margin-bottom: 10px; opacity: 0.5;"></i>
                                    No matches recorded for this year.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($matches as $row): ?>
                                <tr class="match-row"
                                    data-match='<?php echo htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8'); ?>'
                                    data-role="<?php echo htmlspecialchars($row['assigned_role'] ?? '---'); ?>"
                                    onclick="openMatchDetail(this)">
                                    <td style="font-weight: 600; color: #1e3a8a;">
                                        <?php echo htmlspecialchars($row['match_name']); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($row['location'] ?? '---'); ?></td>
                                    <td><?php echo !empty($row['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($row['range_master'])) : '---'; ?>
                                    </td>
                                    <td><span class="role-badge"
                                            style="background: #f1f5f9; color: #475569; padding: 4px 8px; border-radius: 6px; font-size: 0.8rem; font-weight: 600;"><?php echo htmlspecialchars($row['assigned_role'] ?? '---'); ?></span>
                                    </td>
                                    <td>
                                        <?php
                                        if ($row['is_manual']) {
                                            if (!empty($row['month']) && $row['month'] > 0) {
                                                echo date('F', mktime(0, 0, 0, $row['month'], 10)) . ' ' . date('Y', strtotime($row['start_date']));
                                            } else {
                                                echo date('Y', strtotime($row['start_date']));
                                            }
                                        } else {
                                            echo date('M d, Y', strtotime($row['start_date']));
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <div
                                            style="display: flex; align-items: center; justify-content: center; background: #e0f2fe; color: #0369a1; width: 32px; height: 32px; border-radius: 8px; border: 1px solid #bae6fd; font-weight: 800; font-size: 1.1rem; margin: 0 auto;">
                                            <?php echo preg_replace('/\D/', '', $row['match_level']); ?>
                                        </div>
                                    </td>
                                    <td style="font-weight: 700; color: #16a34a;">
                                        +<?php echo number_format($row['points'], 2); ?></td>
                                    <td>
                                        <?php if ($row['is_manual']): ?>
                                            <div class="action-btns">
                                                <button title="Edit" class="action-btn btn-edit"
                                                    onclick="event.stopPropagation(); editManual(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" action="my_points.php?year=<?php echo $yearParam; ?>"
                                                    onsubmit="return confirm('Delete this manual record?');"
                                                    style="display:inline;">
                                                    <input type="hidden" name="manual_action" value="delete">
                                                    <input type="hidden" name="record_id" value="<?php echo $row['mp_id']; ?>">
                                                    <button type="submit" title="Delete" class="action-btn btn-delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="icon-btn btn-edit"
                                                onclick="event.stopPropagation(); openMatchDetail(this.closest('tr'))"
                                                title="View details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Match detail modal: points + RM signature -->
    <div id="matchDetailModal" class="modal">
        <div class="modal-content" style="max-width: 480px;">
            <h3 style="margin-top: 0;" id="modalMatchName">Match</h3>
            <div style="display: grid; gap: 10px; font-size: 0.9rem; color: #64748b;">
                <div><strong style="color: #1e293b;">Date:</strong> <span id="modalDate"></span></div>
                <div><strong style="color: #1e293b;">Level:</strong> <span id="modalLevel"></span></div>
                <div><strong style="color: #1e293b;">Location:</strong> <span id="modalLocation"></span></div>
                <div><strong style="color: #1e293b;">Role:</strong> <span id="modalRole"
                        style="font-weight: 700; color: #1e3a8a;"></span></div>
                <div><strong style="color: #1e293b;">Disciplines:</strong> <span id="modalDisciplines"></span></div>
            </div>
            <div
                style="margin: 20px 0 10px 0; padding: 15px; background: #f0fdf4; border-radius: 10px; border: 1px solid #bbf7d0;">
                <div style="font-size: 0.8rem; color: #166534;">Points earned in this match</div>
                <div id="modalPoints" style="font-size: 1.8rem; font-weight: 800; color: #16a34a;"></div>
            </div>
            <div>
                <div style="font-size: 0.85rem; font-weight: 700; color: #64748b; margin-bottom: 8px;">Range Master
                    Name and Signature</div>
                <div class="signature-box" id="modalSignatureBox">
                    <span id="modalSignaturePlaceholder" style="color: #94a3b8; font-style: italic;">No signature</span>
                    <img id="modalSignatureImg" alt="RM Signature" style="display: none;"
                        onerror="this.style.display='none'; document.getElementById('modalSignaturePlaceholder').style.display='inline'; document.getElementById('modalSignaturePlaceholder').textContent='Image unavailable';">
                    <div id="modalRmName"
                        style="font-size: 1rem; font-weight: 700; color: #1e293b; margin-top: 10px; border-top: 1px solid #e2e8f0; padding-top: 5px; text-align: center;">
                    </div>
                </div>
            </div>
            <div style="font-size: 0.8rem; color: #94a3b8; margin-top: 10px;">Submitted:<br><span
                    id="modalSubmittedAt"></span></div>
            <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                <button type="button" onclick="document.getElementById('matchDetailModal').classList.remove('active')"
                    class="btn-secondary" style="padding: 10px 20px;">Close</button>
            </div>
        </div>
    </div>

    <!-- Manual Entry Modal -->
    <div id="manualModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header"
                style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid #e2e8f0; padding-bottom: 15px;">
                <h3 id="modalTitle" style="margin: 0;">Add Previous Match Points</h3>
                <span class="close-modal" onclick="closeManualModal()"
                    style="font-size: 1.5rem; cursor: pointer; color: #64748b;">&times;</span>
            </div>
            <form method="POST">
                <input type="hidden" name="manual_action" id="manualAction" value="add">
                <input type="hidden" name="record_id" id="recordId" value="">

                <div class="form-group" style="margin-bottom: 15px;">
                    <label
                        style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Match
                        Name</label>
                    <input type="text" name="match_name" id="fieldMatchName" required
                        placeholder="e.g. 2023 National Level"
                        style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                </div>

                <div class="form-group" style="margin-bottom: 15px;">
                    <label
                        style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 8px; color: #475569;">Disciplines</label>
                    <div class="discipline-checkbox-group">
                        <?php foreach ($allDisciplines as $d): ?>
                            <label class="discipline-check-label">
                                <input type="checkbox" name="disciplines[]" value="<?php echo htmlspecialchars($d); ?>"
                                    class="fieldDisciplineCheckbox">
                                <?php echo htmlspecialchars($d); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="form-group" style="margin-bottom: 15px;">
                    <label
                        style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Location</label>
                    <input type="text" name="location" id="fieldLocation" placeholder="e.g. Manila"
                        style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                </div>

                <div style="display: grid; grid-template-columns: 1.5fr 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <div class="form-group">
                        <label
                            style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Year</label>
                        <input type="number" name="year" id="fieldYear" required value="<?php echo date('Y'); ?>"
                            min="1990" max="2100"
                            style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                    </div>
                    <div class="form-group">
                        <label
                            style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Month
                            (Optional)</label>
                        <select name="month" id="fieldMonth"
                            style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                            <option value="">---</option>
                            <option value="1">January</option>
                            <option value="2">February</option>
                            <option value="3">March</option>
                            <option value="4">April</option>
                            <option value="5">May</option>
                            <option value="6">June</option>
                            <option value="7">July</option>
                            <option value="8">August</option>
                            <option value="9">September</option>
                            <option value="10">October</option>
                            <option value="11">November</option>
                            <option value="12">December</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label
                            style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Level</label>
                        <select name="level" id="fieldLevel" required
                            style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                            <option value="1">Level 1</option>
                            <option value="2">Level 2</option>
                            <option value="3">Level 3</option>
                            <option value="4">Level 4</option>
                            <option value="5">Level 5</option>
                        </select>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                    <div class="form-group">
                        <label
                            style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Role</label>
                        <select name="role" id="fieldRole" required
                            style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                            <option value="Range Officer">Range Officer</option>
                            <option value="Lead Range Officer">Lead Range Officer</option>
                            <option value="Area Chief Range Officer">Area Chief Range Officer</option>
                            <option value="Quarter Master">Quarter Master</option>
                            <option value="Range Master">Range Master</option>
                            <option value="Stats Officer">Stats Officer</option>
                            <option value="Stats Director">Stats Director</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label
                            style="display: block; font-weight: 700; font-size: 0.85rem; margin-bottom: 5px; color: #475569;">Points</label>
                        <input type="number" step="0.5" name="points" id="fieldPoints" required placeholder="0.00"
                            style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0;">
                    </div>
                </div>

                <div
                    style="display: flex; gap: 10px; justify-content: flex-end; border-top: 1px solid #e2e8f0; padding-top: 20px;">
                    <button type="button" onclick="closeManualModal()" class="btn-secondary"
                        style="padding: 10px 20px; border-radius: 8px; border: 1px solid #e2e8f0; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" class="btn-primary"
                        style="padding: 10px 25px; border-radius: 8px; background: #2563eb; color: white; border: none; font-weight: 700; cursor: pointer;">Save
                        Changes</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        function capitalizeWords(str) {
            if (!str) return '';
            return str.trim().toLowerCase().split(' ').map(word => {
                if (word.length === 0) return word;
                return word.charAt(0).toUpperCase() + word.slice(1);
            }).join(' ');
        }
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');
        if (profileToggle && profileDropdown) {
            profileToggle.addEventListener('click', function (e) { e.stopPropagation(); profileDropdown.classList.toggle('active'); });
            document.addEventListener('click', function () { profileDropdown.classList.remove('active'); });
        }

        function openMatchDetail(row) {
            const data = row.getAttribute('data-match');
            if (!data) return;
            const m = JSON.parse(data);
            document.getElementById('modalMatchName').textContent = m.match_name || 'Match';
            document.getElementById('modalDate').textContent = m.start_date ? new Date(m.start_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—';
            document.getElementById('modalLevel').textContent = (m.match_level || '').replace(/\D/g, '') || '—';
            document.getElementById('modalLocation').textContent = m.location || '—';
            document.getElementById('modalRole').textContent = m.assigned_role || '—';
            document.getElementById('modalDisciplines').innerHTML = m.range_master ? m.range_master.split(', ').join('<br>') : '—';
            document.getElementById('modalRmName').textContent = capitalizeWords(m.rm_name || 'Range Master');
            document.getElementById('modalPoints').textContent = '+' + parseFloat(m.points).toFixed(2);
            if (m.submitted_at) {
                const dt = new Date(m.submitted_at);
                const datePart = dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                const timePart = dt.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                document.getElementById('modalSubmittedAt').innerHTML = datePart + '<br>' + timePart;
            } else {
                document.getElementById('modalSubmittedAt').textContent = '—';
            }

            const img = document.getElementById('modalSignatureImg');
            const placeholder = document.getElementById('modalSignaturePlaceholder');
            if (m.rm_signature) {
                img.src = '../' + m.rm_signature;
                img.style.display = 'block';
                placeholder.style.display = 'none';
                img.onerror = function () {
                    img.style.display = 'none';
                    placeholder.style.display = 'inline';
                    placeholder.textContent = 'Image unavailable';
                };
            } else {
                img.style.display = 'none';
                placeholder.style.display = 'inline';
                placeholder.textContent = 'No signature';
            }

            document.getElementById('matchDetailModal').classList.add('active');
        }

        function exportSummaryPdf() {
            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('pointsSummaryForPdf');
            if (!el) { if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF'; } return; }
            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 () {
                    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() {
                        html2canvas(el, { scale: 2, useCORS: true, allowTaint: true, logging: false }).then(function (canvas) {
                            var imgW = canvas.width, imgH = canvas.height;
                            var pdf = new jspdf.jsPDF('p', 'mm', 'a4');
                            var pageW = pdf.internal.pageSize.getWidth();
                            var pageH = pdf.internal.pageSize.getHeight();
                            var ratio = Math.min(pageW / (imgW / 2), pageH / (imgH / 2));
                            var w = (imgW / 2) * ratio, h = (imgH / 2) * ratio;
                            pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, w, h);
                            pdf.save('Match-Point-Card-Summary-<?php echo (int) $year; ?>.pdf');
                            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF'; }
                        }).catch(function (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', exportSummaryPdf);

        let currentFilter = null;
        function filterByRole(el, role) {
            const rows = document.querySelectorAll('.match-row');
            const items = document.querySelectorAll('.role-summary-item');

            if (currentFilter === role) {
                // Clear filter
                rows.forEach(r => r.style.display = '');
                items.forEach(it => it.classList.remove('active-filter'));
                currentFilter = null;
            } else {
                // Apply filter
                rows.forEach(r => {
                    if (r.getAttribute('data-role') === role) {
                        r.style.display = '';
                    } else {
                        r.style.display = 'none';
                    }
                });

                items.forEach(it => {
                    if (it.getAttribute('data-role') === role) {
                        it.classList.add('active-filter');
                    } else {
                        it.classList.remove('active-filter');
                    }
                });
                currentFilter = role;
            }
        }

        function openManualModal() {
            document.getElementById('manualAction').value = 'add';
            document.getElementById('modalTitle').innerText = 'Add Previous Match Points';
            document.getElementById('fieldMatchName').value = '';

            // Clear all checkboxes
            document.querySelectorAll('.fieldDisciplineCheckbox').forEach(cb => {
                cb.checked = false;
            });

            document.getElementById('fieldLocation').value = '';
            document.getElementById('fieldYear').value = new Date().getFullYear();
            document.getElementById('fieldMonth').value = '';
            document.getElementById('fieldLevel').value = '1';
            document.getElementById('fieldRole').value = 'Range Officer';
            document.getElementById('fieldPoints').value = '';
            document.getElementById('manualModal').style.display = 'block';
        }

        function closeManualModal() {
            document.getElementById('manualModal').style.display = 'none';
        }

        function editManual(data) {
            document.getElementById('manualAction').value = 'edit';
            document.getElementById('recordId').value = data.mp_id;
            document.getElementById('modalTitle').innerText = 'Edit Previous Match Points';
            document.getElementById('fieldMatchName').value = data.match_name;

            // Handle multiple disciplines
            const disciplines = data.range_master ? data.range_master.split(',').map(s => s.trim()) : [];
            document.querySelectorAll('.fieldDisciplineCheckbox').forEach(cb => {
                cb.checked = disciplines.includes(cb.value);
            });

            document.getElementById('fieldLocation').value = data.location;
            document.getElementById('fieldYear').value = data.year || new Date(data.start_date).getFullYear();
            document.getElementById('fieldMonth').value = data.month || '';
            document.getElementById('fieldLevel').value = data.match_level.replace(/\D/g, '') || '1';
            document.getElementById('fieldRole').value = data.assigned_role;
            document.getElementById('fieldPoints').value = data.points;
            document.getElementById('manualModal').style.display = 'block';
        }

        window.onclick = function (event) {
            let modal = document.getElementById('manualModal');
            if (event.target == modal) closeManualModal();
        }
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>