<?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';
$role = $_SESSION['user_role'] ?? '';
$is_special_role = in_array(strtoupper($role), ['PPSA', 'NROI']);
$is_officer = $is_ac || $is_aac || $is_special_role;

if (!$is_admin && !$is_officer) {
    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,
        month INT 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
    )
");

$checkMonth = $pdo->query("SHOW COLUMNS FROM manual_match_points LIKE 'month'");
if (!$checkMonth->fetch()) {
    $pdo->exec("ALTER TABLE manual_match_points ADD COLUMN month INT NULL AFTER year");
}

$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");
}

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

$stmtRefRoles = $pdo->query("SELECT name FROM reference_match_roles ORDER BY name ASC");
$refRoles = $stmtRefRoles->fetchAll(PDO::FETCH_COLUMN);

$stmtRefAss = $pdo->query("SELECT name FROM reference_match_assignments ORDER BY name ASC");
$refAssignments = $stmtRefAss->fetchAll(PDO::FETCH_COLUMN);

$memberId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
if ($memberId <= 0) {
    header("Location: points_card.php");
    exit;
}

// Fetch member and ensure they are in the officer's area (or any for admin)
$stmtMember = $pdo->prepare("SELECT id, first_name, last_name, nroi_id, area, role, rank, profile_photo FROM users WHERE id = ? AND status IN ('approved', 'deactivated')");
$stmtMember->execute([$memberId]);
$member = $stmtMember->fetch(PDO::FETCH_ASSOC);

if (!$member) {
    header("Location: points_card.php?error=member_not_found");
    exit;
}

if (!$is_admin && !$is_special_role) {
    $area = $_SESSION['area'] ?? '';
    if ($member['area'] !== $area) {
        header("Location: points_card.php?error=access_denied");
        exit;
    }

    // Enforce role boundaries for officers
    $targetUserRole = $member['role'] ?? 'member';
    if ($is_ac) {
        $canHandle = in_array($targetUserRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
    } else { // is_aac
        $canHandle = in_array($targetUserRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
    }

    if (!$canHandle) {
        header("Location: points_card.php?error=access_denied&role_msg=unauthorized_role");
        exit;
    }
}

$userFullName = trim($member['last_name'] . ', ' . $member['first_name']);
$userNroiId = $member['nroi_id'] ?? '';

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

// 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([
                $memberId,
                $_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: member_points_summary.php?user_id=$memberId&success=added");
            exit;
        } elseif ($mAction === 'edit') {
            $mId = (int) $_POST['record_id'];
            // Verify ownership
            $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: member_points_summary.php?user_id=$memberId&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: member_points_summary.php?user_id=$memberId&success=deleted");
            exit;
        }
    } catch (Exception $e) {
        $manual_error = $e->getMessage();
    }
}

// Handle fixing missing role
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fix_missing_role') {
    try {
        if (!$is_admin && !$is_ac && !$is_aac)
            throw new Exception("Unauthorized action.");

        $fMatchId = (int) $_POST['match_id'];
        $fRole = $_POST['role'];
        $fAssignmentType = $_POST['assignment_type']; // 'Stage', 'Statistics', etc.

        // Map assignment type to table
        $typeKey = strtolower(str_replace(' ', '_', $fAssignmentType));
        if ($typeKey === 'stage' || $typeKey === 'states') {
            $table = 'match_states_assignments';
        } else {
            $table = 'match_' . $typeKey . '_assignments';
        }

        // Verify role and assignment exist in references
        if (!in_array($fRole, $refRoles) || !in_array($fAssignmentType, $refAssignments)) {
            throw new Exception("Invalid Role or Assignment Type.");
        }

        // Use user's name for officer_name/lro_name
        $offName = $member['first_name'] . ' ' . $member['last_name'];

        // Ensure table exists (copy logic from matches.php)
        if ($table === 'match_states_assignments') {
            $pdo->exec("CREATE TABLE IF NOT EXISTS `$table` (id INT AUTO_INCREMENT PRIMARY KEY, match_id INT NOT NULL, states_number VARCHAR(100) NOT NULL, lro_name VARCHAR(255) NULL, role VARCHAR(100) NULL, rm_signature VARCHAR(255) NULL, submitted_by INT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uniq_ms (match_id, submitted_by))");
            $stmt = $pdo->prepare("INSERT INTO `$table` (match_id, states_number, lro_name, role, submitted_by) VALUES (?, '---', ?, ?, ?) ON DUPLICATE KEY UPDATE role=VALUES(role)");
            $stmt->execute([$fMatchId, $offName, $fRole, $memberId]);
        } else {
            $pdo->exec("CREATE TABLE IF NOT EXISTS `$table` (id INT AUTO_INCREMENT PRIMARY KEY, match_id INT NOT NULL, officer_name VARCHAR(255) NOT NULL, role VARCHAR(100) NULL, rm_signature VARCHAR(255) NULL, submitted_by INT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uniq_{$typeKey} (match_id, submitted_by))");
            $stmt = $pdo->prepare("INSERT INTO `$table` (match_id, officer_name, role, submitted_by) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE role=VALUES(role)");
            $stmt->execute([$fMatchId, $offName, $fRole, $memberId]);
        }

        // Sync profile assignment/role
        $pdo->prepare("UPDATE users SET match_assignment = ?, match_role = ? WHERE id = ?")
            ->execute([$fAssignmentType, $fRole, $memberId]);

        header("Location: member_points_summary.php?user_id=$memberId&success=role_fixed");
        exit;
    } catch (Exception $e) {
        $manual_error = "Error fixing role: " . $e->getMessage();
    }
}

// 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([$memberId, $year]);
} else {
    $stmtManualTotal->execute([$memberId]);
}
$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([$memberId, $year]);
} else {
    $stmtTotal->execute([$memberId]);
}
$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);

    // Sort to ensure common roles are checked in a priority order if multiple exist
    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 = [$memberId, $memberId];
if ($year !== 'all')
    $params[] = $year;
$params[] = $memberId;
if ($year !== 'all')
    $params[] = $year;

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

// Filter out matches where signature file is missing on disk (only for non-manual matches)
$matches = [];
foreach ($allMatchesRaw as $m) {
    if (!$m['is_manual']) {
        $sigPath = '../' . $m['rm_signature'];
        if (empty($m['rm_signature']) || $m['rm_signature'] === 'DEMERIT' || !file_exists($sigPath)) {
            continue; // Skip incomplete matches in summary
        }
    }
    $matches[] = $m;
}

// Recalculate year total based on filtered matches to ensure accuracy if file_exists fails
$yearTotal = 0;
foreach ($matches as $m) {
    $yearTotal += (float) $m['points'];
}

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

// Fetch AC for this user's area
$acId = 0;
$acName = "Area Coordinator";
$acSigPath = "";
$stmtAC = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE role = 'AC' AND area = ? AND status = 'approved' LIMIT 1");
$stmtAC->execute([$member['area']]);
$ac = $stmtAC->fetch(PDO::FETCH_ASSOC);

if ($ac) {
    $acId = $ac['id'];
    $acName = $ac['first_name'] . ' ' . $ac['last_name'];
    $sigDir = __DIR__ . '/../storage/officers_signature/';
    $acFiles = glob($sigDir . 'officer_' . $acId . '_*');
    if (!empty($acFiles)) {
        usort($acFiles, fn($a, $b) => filemtime($b) - filemtime($a));
        $acSigPath = '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>Point Card Summary — <?php echo htmlspecialchars($userFullName); ?> | 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .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;
            }
        }

        .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;
        }

        #pointsSummaryForPdf {
            background: #fff;
            color: #1e293b;
            padding: 24px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            max-width: 100%;
        }

        #pointsSummaryForPdf .summary-header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 3px solid #1e3a8a;
            padding-bottom: 25px;
            position: relative;
        }

        #pointsSummaryForPdf .summary-header img.nroi-logo {
            height: 80px;
            margin-bottom: 12px;
        }

        #pointsSummaryForPdf .summary-header .profile-pic {
            position: absolute;
            top: 0;
            right: 0;
            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);
        }

        #pointsSummaryForPdf .summary-header h1 {
            margin: 0;
            font-size: 1.8rem;
            color: #1e3a8a;
            text-transform: uppercase;
            letter-spacing: -0.01em;
            font-weight: 800;
            line-height: 1.1;
        }

        #pointsSummaryForPdf .summary-header p {
            margin: 6px 0 0 0;
            font-size: 1rem;
            color: #64748b;
            font-weight: 700;
            text-transform: uppercase;
        }

        #pointsSummaryForPdf .summary-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: #1e3a8a;
            margin-bottom: 6px;
            text-align: center;
            letter-spacing: -0.01em;
        }

        #pointsSummaryForPdf .summary-sub {
            font-size: 1rem;
            color: #64748b;
            margin-bottom: 24px;
            text-align: center;
            font-weight: 500;
        }

        #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.9rem;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        #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;
        }

        /* 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;
        }

        /* Hide elements from PDF */
        .no-pdf {
            display: table-cell;
        }

        .summary-table td.no-pdf {
            border: none !important;
            background: transparent !important;
            width: 40px;
            padding: 0 10px !important;
            vertical-align: middle;
        }

        .summary-table th.no-pdf {
            border: none !important;
            background: transparent !important;
            width: 40px;
        }

        .fix-role-btn {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            color: #2563eb;
            cursor: pointer;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            transition: all 0.2s;
            box-shadow: 0 2px 4px rgba(37, 99, 235, 0.1);
        }

        .fix-role-btn:hover {
            background: #2563eb;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 4px 8px rgba(37, 99, 235, 0.2);
        }

        .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;
        }

        .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;
        }

        .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;
        }
    </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 ($is_admin) {
                    echo 'ADMIN';
                } elseif ($is_ac) {
                    echo 'A.C';
                } elseif ($is_aac) {
                    echo 'A.A.C';
                } elseif ($is_special_role) {
                    echo htmlspecialchars(strtoupper($_SESSION['user_role'] ?? 'OFFICER'));
                } else {
                    echo '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>
        <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>

            <?php if (isset($_GET['success'])): ?>
                <div
                    style="margin: 20px 40px -10px 40px; padding: 15px 20px; background: #ecfdf5; border-left: 5px solid #10b981; border-radius: 8px; color: #065f46; display: flex; align-items: center; gap: 12px; font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                    <i class="fas fa-check-circle"></i>
                    <?php
                    $msg = "Operation completed successfully.";
                    if ($_GET['success'] === 'role_fixed')
                        $msg = "Match role has been successfully assigned and verified.";
                    if ($_GET['success'] === 'updated')
                        $msg = "Match record updated successfully.";
                    if ($_GET['success'] === 'deleted')
                        $msg = "Manual record has been permanently removed.";
                    echo $msg;
                    ?>
                </div>
            <?php endif; ?>

            <?php if (isset($manual_error)): ?>
                <div
                    style="margin: 20px 40px -10px 40px; padding: 15px 20px; background: #fef2f2; border-left: 5px solid #ef4444; border-radius: 8px; color: #991b1b; display: flex; align-items: center; gap: 12px; font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($manual_error); ?>
                </div>
            <?php endif; ?>

            <div class="content-box">
                <div class="table-header"
                    style="flex-wrap: wrap; gap: 16px; align-items: flex-end; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 20px; margin-bottom: 24px; background: transparent; padding-left: 0; padding-right: 0;">
                    <div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
                        <h3
                            style="margin: 0; font-size: 1.5rem; font-weight: 800; color: #1e293b; letter-spacing: -0.02em; display: flex; align-items: center; gap: 12px;">
                            Match Point Card — <span
                                style="color: #2563eb;"><?php echo htmlspecialchars(capitalizeWords($userFullName)); ?></span>
                            <?php if (!empty($member['rank'])): ?>
                                <span
                                    class="rank-badge <?php echo strpos(strtoupper($member['rank']), 'OJT') !== false ? 'rank-ojt' : 'rank-regular'; ?>"
                                    style="font-size: 0.75rem; padding: 4px 12px; height: auto;">
                                    <?php echo htmlspecialchars($member['rank']); ?>
                                </span>
                            <?php endif; ?>
                        </h3>
                    </div>

                    <!-- Right: Controls row -->
                    <div style="display: flex; align-items: flex-end; gap: 10px; flex-wrap: nowrap;">
                        <!-- Year Selector -->
                        <div style="display: flex; flex-direction: column; gap: 3px;">
                            <label for="yearSelect"
                                style="font-size: 0.65rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.07em; padding-left: 4px;">Year</label>
                            <select id="yearSelect"
                                style="height: 42px; padding: 0 14px; border: 1px solid #e2e8f0; border-radius: 10px; background: white; font-weight: 700; font-size: 0.9rem; color: #1e293b; outline: none; cursor: pointer; font-family: 'Inter', sans-serif;"
                                onchange="window.location.href='member_points_summary.php?user_id=<?php echo $memberId; ?>&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>
                            </select>
                        </div>

                        <!-- Add Prev. Points -->
                        <button type="button" onclick="openManualModal()"
                            style="height: 42px; padding: 0 18px; font-size: 0.85rem; background: #10b981; border: none; border-radius: 10px; color: white; cursor: pointer; font-weight: 700; display: inline-flex; align-items: center; gap: 7px; box-shadow: 0 4px 6px -1px rgba(16,185,129,0.25); transition: all 0.2s; white-space: nowrap; font-family: 'Inter', sans-serif;">
                            <i class="fas fa-calendar-plus"></i> Add Prev. Points
                        </button>


                        <!-- Export PDF -->
                        <button type="button" id="exportPdfBtn"
                            style="height: 42px; padding: 0 18px; font-size: 0.85rem; background: #1e3a8a; border: none; border-radius: 10px; color: white; cursor: pointer; font-weight: 700; display: inline-flex; align-items: center; gap: 7px; box-shadow: 0 4px 10px rgba(30,58,138,0.3); transition: all 0.2s; white-space: nowrap; font-family: 'Inter', sans-serif;">
                            <i class="fas fa-file-pdf"></i> Export as PDF
                        </button>
                    </div>
                </div>

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

                <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>

                <?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; ?>
                <!-- PDF-only Header (Hidden on Web) -->
                <div style="display: none;">
                    <div id="pdfHeaderBranding">
                        <div class="summary-header">
                            <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="nroi-logo">
                            <?php if (!empty($member['profile_photo'])): ?>
                                <img src="../<?php echo htmlspecialchars($member['profile_photo']); ?>"
                                    alt="Profile Picture" class="profile-pic">
                            <?php endif; ?>
                            <h1>NATIONAL RANGE OFFICERS INSTITUTE</h1>
                            <p>Official User Points Card Summary Report</p>
                        </div>
                    </div>
                </div>

                <div id="pointsSummaryForPdf">
                    <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>
                                <th class="no-pdf"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($matches)): ?>
                                <tr>
                                    <td colspan="9" style="text-align: center; color: #64748b;">No matches for this year.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($matches as $i => $row): ?>
                                    <tr class="match-row"
                                        data-role="<?php echo htmlspecialchars($row['assigned_role'] ?? '---'); ?>">
                                        <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']) && $row['rm_signature'] !== 'DEMERIT'): ?>
                                                <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'] ?? false)): ?>
                                                <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'] ?? 0) == ($_SESSION['user_id'] ?? 0) || ($row['recorded_by_admin_id'] ?? 0) == ($_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="editManual(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <form method="POST" 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>
                                        <td class="no-pdf">
                                            <?php if (($row['assigned_role'] ?? '---') === '---' && !($row['is_manual'] ?? false) && ($is_admin || $is_ac || $is_aac)): ?>
                                                <button type="button" class="fix-role-btn"
                                                    onclick="openFixRoleModal(<?php echo $row['match_id']; ?>, '<?php echo addslashes($row['match_name']); ?>')"
                                                    title="Assign Missing Role">
                                                    <i class="fas fa-plus"></i>
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <!-- PDF-only Footer (Hidden on Web) -->
                    <div style="display: none;">
                        <div id="pdfFooterBranding">
                            <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; text-align: left;">
                                    <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 Report</span>
                                    </div>
                                </div>

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

            <!-- Manual Entry Modal -->
            <div id="manualModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="modal-title" id="modalTitle">Add Previous Match Points</div>
                        <span class="close-modal" onclick="closeManualModal()">&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">
                            <label>Match Name</label>
                            <input type="text" name="match_name" id="fieldMatchName" required
                                placeholder="e.g. 2023 National Level">
                        </div>

                        <div class="form-group">
                            <label style="margin-bottom: 8px; display: block;">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">
                            <label>Location</label>
                            <input type="text" name="location" id="fieldLocation" placeholder="e.g. Manila">
                        </div>

                        <div style="display: grid; grid-template-columns: 1.5fr 1fr 1fr; gap: 15px;">
                            <div class="form-group">
                                <label>Year</label>
                                <input type="number" name="year" id="fieldYear" required
                                    value="<?php echo date('Y'); ?>" min="1990" max="2100">
                            </div>
                            <div class="form-group">
                                <label>Month (Optional)</label>
                                <select name="month" id="fieldMonth">
                                    <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>Level</label>
                                <select name="level" id="fieldLevel" required>
                                    <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 class="form-group">
                            <label>Role</label>
                            <select name="role" id="fieldRole" required>
                                <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>Points</label>
                            <input type="number" name="points" id="fieldPoints" step="0.01" required placeholder="0.00">
                        </div>

                        <div style="margin-top: 20px; text-align: right;">
                            <button type="button" onclick="closeManualModal()" class="btn-secondary"
                                style="margin-right: 10px;">Cancel</button>
                            <button type="submit" class="btn-primary" id="saveManualBtn">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Fix Missing Role Modal -->
            <div id="fixRoleModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="modal-title">Fix Missing Match Role</div>
                        <span class="close-modal" onclick="closeFixRoleModal()">&times;</span>
                    </div>
                    <form method="POST" id="fixRoleForm"
                        onsubmit="return confirm('Attention: This manual role assignment can only be done ONCE. Are you absolutely sure the selected Role and Assignment Type are correct?')">
                        <input type="hidden" name="action" value="fix_missing_role">
                        <input type="hidden" name="match_id" id="fixRoleMatchId">

                        <div
                            style="background: #fff5f5; border: 1px solid #feb2b2; color: #c53030; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 0.9rem; font-weight: 500;">
                            <i class="fas fa-exclamation-triangle" style="margin-right: 8px;"></i>
                            <strong>Important:</strong> Adding a missing role manually can only be done
                            <strong>once</strong> for each match. Please double-check the role before saving.
                        </div>

                        <div class="form-group">
                            <label>Match Name</label>
                            <input type="text" id="fixRoleMatchName" readonly
                                style="background: #f8fafc; cursor: default;">
                        </div>

                        <div class="form-group">
                            <label>Assignment Type</label>
                            <select name="assignment_type" id="fixRoleAssignmentType" required>
                                <option value="">--- Select Assignment ---</option>
                                <?php foreach ($refAssignments as $assName): ?>
                                    <option value="<?php echo htmlspecialchars($assName); ?>">
                                        <?php echo htmlspecialchars($assName); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p style="font-size: 0.75rem; color: #64748b; margin-top: 5px;">This determines which
                                technical table the role is saved to.</p>
                        </div>

                        <div class="form-group">
                            <label>Role</label>
                            <select name="role" id="fixRoleName" required>
                                <option value="">--- Select Role ---</option>
                                <?php foreach ($refRoles as $roleName): ?>
                                    <option value="<?php echo htmlspecialchars($roleName); ?>">
                                        <?php echo htmlspecialchars($roleName); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div style="margin-top: 25px; text-align: right;">
                            <button type="button" onclick="closeFixRoleModal()" class="btn-secondary"
                                style="margin-right: 10px;">Cancel</button>
                            <button type="submit" class="btn-primary" style="background: #2563eb;">Save Role
                                Information</button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        var profileToggle = document.getElementById('profileToggle');
        var 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 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,
                            onclone: function (clonedDoc) {
                                // Find the elements in the CLONED document
                                const clonedEl = clonedDoc.getElementById('pointsSummaryForPdf');
                                const headerMarkup = clonedDoc.getElementById('pdfHeaderBranding').innerHTML;
                                const footerMarkup = clonedDoc.getElementById('pdfFooterBranding').innerHTML;

                                // Style the cloned element for PDF layout
                                clonedEl.style.padding = '40px';
                                clonedEl.style.width = '1000px';
                                clonedEl.style.background = '#ffffff';

                                // Inject branding into the CLONE only
                                clonedEl.innerHTML = headerMarkup + clonedEl.innerHTML + footerMarkup;

                                // Remove elements that should not be in the PDF (like the fix button column)
                                clonedEl.querySelectorAll('.no-pdf').forEach(el => el.remove());

                                // Ensure any hidden branding containers are technically "visible" in the clone if they hold content
                                // but since we take innerHTML and put it into clonedEl, it's fine.
                            }
                        }).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; ?>-Member-<?php echo (int) $memberId; ?>.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 Error:', 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';
        }

        function openFixRoleModal(matchId, matchName) {
            document.getElementById('fixRoleMatchId').value = matchId;
            document.getElementById('fixRoleMatchName').value = matchName;
            document.getElementById('fixRoleAssignmentType').value = "";
            document.getElementById('fixRoleName').value = "";
            document.getElementById('fixRoleModal').style.display = 'block';
        }

        function closeFixRoleModal() {
            document.getElementById('fixRoleModal').style.display = 'none';
        }

        window.onclick = function (event) {
            let manualModal = document.getElementById('manualModal');
            let fixRoleModal = document.getElementById('fixRoleModal');
            if (event.target == manualModal) closeManualModal();
            if (event.target == fixRoleModal) closeFixRoleModal();
        }

        // Handle auto-selection of assignment type based on role
        document.getElementById('fixRoleName').addEventListener('change', function () {
            const role = this.value;
            const assType = document.getElementById('fixRoleAssignmentType');

            if (role.includes('Stats') || role.includes('Statistics')) {
                assType.value = 'Statistics';
            } else if (role === 'Range Master' || role === 'Deputy Range Master') {
                assType.value = 'Range Master';
            } else if (role === 'Match Director') {
                assType.value = 'Match Director';
            } else if (role === 'Quarter Master') {
                assType.value = 'Quarter Master';
            } else if (role.includes('Chrono')) {
                assType.value = 'Chrono';
            } else if (role.includes('Equipment')) {
                assType.value = 'Equipment Check';
            } else {
                assType.value = 'Stage';
            }
        });
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>