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

// Allow both admin and officers to access matches
$is_admin = isset($_SESSION['admin_id']);
$is_officer = isset($_SESSION['user_id']);

$is_special = isset($_SESSION['user_role']) && in_array(strtoupper($_SESSION['user_role']), ['PPSA', 'NROI']);

if (!$is_admin && !$is_officer) {
    header("Location: ../index.php");
    exit;
}
if (!$is_admin && $is_special) {
    header("Location: ../officer/dashboard.php");
    exit;
}

// Handle POST requests BEFORE any HTML output
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
$is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
$is_officer_role = $is_ac || $is_aac;
$userArea = $_SESSION['area'] ?? '';

// Helper function to log activities
try {
    // Fetch all approved disciplines
    $stmtDisc = $pdo->query("SELECT * FROM disciplines WHERE name != 'Bad Record' ORDER BY name ASC");
    $disciplines = $stmtDisc->fetchAll(PDO::FETCH_ASSOC);

    // Fetch approved users with specific roles for Range Master (RO, CRO, AC, AAC, RM)
    $stmtRM = $pdo->query("SELECT id, first_name, last_name, nroi_id, role FROM users WHERE status = 'approved' AND (role IN ('RO', 'R.O', 'CRO', 'C.R.O', 'AC', 'AAC', 'RM') OR role IS NULL OR role = '' OR role = 'member') ORDER BY last_name ASC, first_name ASC");
    $rmUsersList = $stmtRM->fetchAll(PDO::FETCH_ASSOC);
    $rm_users = $rmUsersList; // For compatibility with different parts of the file

    // Fetch dynamic Match Assignments
    $stmtMA = $pdo->query("SELECT * FROM reference_match_assignments ORDER BY name ASC");
    $dynamicMatchAssignments = $stmtMA->fetchAll(PDO::FETCH_ASSOC);

    // Fetch dynamic Match Roles
    $stmtMR = $pdo->query("SELECT * FROM reference_match_roles ORDER BY name ASC");
    $dynamicMatchRoles = $stmtMR->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $disciplines = [];
    $rmUsersList = [];
    $rm_users = [];
    $dynamicMatchAssignments = [];
    $dynamicMatchRoles = [];
}

function logActivity($pdo, $referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId = null, $performedByAdminId = null)
{
    // Ensure activity_logs table exists
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS activity_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            reference_type VARCHAR(50) NOT NULL,
            reference_id INT NULL,
            description TEXT NOT NULL,
            status VARCHAR(50) NOT NULL,
            performed_by_role VARCHAR(20) NOT NULL,
            performed_by_user_id INT NULL,
            performed_by_admin_id INT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_created_at (created_at),
            INDEX idx_performed_by (performed_by_role, performed_by_user_id, performed_by_admin_id)
        )
    ");

    $stmt = $pdo->prepare("
        INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id, performed_by_admin_id) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId, $performedByAdminId]);
}

// Build a single string for discipline(s) from POST (supports legacy range_master + new disciplines[] checkboxes)
function buildDisciplinesStringFromPost($post)
{
    if (isset($post['disciplines']) && is_array($post['disciplines'])) {
        $vals = array_map('trim', $post['disciplines']);
        $vals = array_filter($vals, function ($v) {
            return $v !== '';
        });
        $vals = array_values(array_unique($vals));
        return implode(', ', $vals);
    }
    return trim($post['range_master'] ?? '');
}

function handleMatchAttachments($pdo, $matchId, $files)
{
    if (!empty($files['attachments']['name'][0])) {
        $uploadDir = __DIR__ . '/../storage/match_attachments/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $allowedExts = ['pdf', 'jpg', 'jpeg', 'png', 'gif'];
        foreach ($files['attachments']['tmp_name'] as $key => $tmpName) {
            if ($files['attachments']['error'][$key] === UPLOAD_ERR_OK) {
                $fileName = basename($files['attachments']['name'][$key]);
                $fileType = mime_content_type($tmpName);
                if (!$fileType) {
                    $fileType = $files['attachments']['type'][$key];
                }
                $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                if (in_array($fileExt, $allowedExts)) {
                    $uniqueName = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $fileName);
                    $destPath = $uploadDir . $uniqueName;
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $dbPath = 'storage/match_attachments/' . $uniqueName;
                        $stmtAttach = $pdo->prepare("INSERT INTO match_attachments (match_id, file_name, file_path, file_type) VALUES (?, ?, ?, ?)");
                        $stmtAttach->execute([$matchId, $fileName, $dbPath, $fileType]);
                    }
                }
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($is_admin || $is_officer_role) {
        // Fixed Match Handlers
        if (isset($_POST['action'])) {
            $action = $_POST['action'];
            if ($action === 'create_match' || $action === 'update_match') {
                try {
                    $disciplinesStr = buildDisciplinesStringFromPost($_POST);
                    if ($disciplinesStr === '')
                        throw new Exception('Please select at least one discipline.');
                    if (empty($_POST['rm_name']))
                        throw new Exception('Please select a Range Master.');

                    // Preserve existing values if they are NOT in the POST (we will fetch oldMatch below for updates)
                    // For create, default to 0.
                    $isRetroactive = isset($_POST['is_retroactive']) ? 1 : 0;
                    $isLocal = isset($_POST['is_local']) ? 1 : 0;

                    if ($action === 'create_match') {
                        // Uniqueness
                        $stmtUnique = $pdo->prepare("SELECT id FROM match_schedules WHERE LOWER(match_name) = LOWER(?) AND LOWER(location) = LOWER(?)");
                        $stmtUnique->execute([$_POST['match_name'], $_POST['location']]);
                        if ($stmtUnique->fetch())
                            throw new Exception('A match with the same name and location already exists.');

                        $createdBy = null;
                        $creatorArea = null;
                        if ($is_admin) {
                            $systemUser = $pdo->query("SELECT id FROM users ORDER BY id ASC LIMIT 1")->fetch();
                            $createdBy = $systemUser ? $systemUser['id'] : 1;
                        } else {
                            $createdBy = $_SESSION['user_id'];
                            $creatorArea = $pdo->prepare("SELECT area FROM users WHERE id = ?");
                            $creatorArea->execute([$createdBy]);
                            $creatorArea = $creatorArea->fetchColumn();
                        }

                        $stmt = $pdo->prepare("INSERT INTO match_schedules (match_name, start_date, end_date, match_level, range_master, location, created_by, ro_limit, rm_name, rm_id, is_retroactive, is_local, creator_area) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $_POST['match_name'],
                            $_POST['start_date'],
                            $_POST['end_date'],
                            $_POST['match_level'],
                            $disciplinesStr,
                            $_POST['location'],
                            $createdBy,
                            $_POST['ro_limit'],
                            $_POST['rm_name'],
                            $_POST['rm_id'] ?? null,
                            $isRetroactive,
                            $isLocal,
                            $creatorArea
                        ]);
                        $matchId = $pdo->lastInsertId();
                        handleMatchAttachments($pdo, $matchId, $_FILES);

                        // --- Notify assigned RM ---
                        if (!empty($_POST['rm_id'])) {
                            $stmtRm = $pdo->prepare("SELECT email, first_name, last_name FROM users WHERE id = ?");
                            $stmtRm->execute([$_POST['rm_id']]);
                            $rmUser = $stmtRm->fetch(PDO::FETCH_ASSOC);
                            if ($rmUser && !empty($rmUser['email'])) {
                                $rmFullName = $rmUser['first_name'] . ' ' . $rmUser['last_name'];
                                $rmSchedule = $_POST['start_date'] . ($_POST['start_date'] !== $_POST['end_date'] ? ' to ' . $_POST['end_date'] : '');
                                sendRmAssignmentNotification(
                                    $rmUser['email'],
                                    $rmFullName,
                                    $_POST['match_name'],
                                    $_POST['match_level'],
                                    $disciplinesStr,
                                    $rmSchedule,
                                    $_POST['location'],
                                    false // new assignment
                                );
                            }
                        }

                        // --- Notify all eligible members ---
                        $usersQuery = "SELECT email, first_name, last_name FROM users WHERE status = 'approved' AND email IS NOT NULL AND email != ''";
                        if (($isRetroactive || $isLocal) && !empty($creatorArea))
                            $usersQuery .= " AND area = " . $pdo->quote($creatorArea);
                        $stmtUsers = $pdo->query($usersQuery);
                        $usersToNotify = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);
                        $scheduleStr = $_POST['start_date'] . ($_POST['start_date'] !== $_POST['end_date'] ? " to " . $_POST['end_date'] : "");
                        foreach ($usersToNotify as $u) {
                            sendNewMatchNotification($u['email'], $u['first_name'] . ' ' . $u['last_name'], $_POST['match_name'], $scheduleStr, $_POST['location'], $_POST['match_level'], $disciplinesStr, $_POST['rm_name']);
                        }
                    } else {
                        // Uniqueness check
                        $stmtUnique = $pdo->prepare("SELECT id FROM match_schedules WHERE LOWER(match_name) = LOWER(?) AND LOWER(location) = LOWER(?) AND id != ?");
                        $stmtUnique->execute([$_POST['match_name'], $_POST['location'], $_POST['match_id']]);
                        if ($stmtUnique->fetch())
                            throw new Exception('A match with the same name and location already exists.');

                        // --- Fetch old match details before updating ---
                        $stmtOld = $pdo->prepare("SELECT * FROM match_schedules WHERE id = ?");
                        $stmtOld->execute([$_POST['match_id']]);
                        $oldMatch = $stmtOld->fetch();
                        if (!$oldMatch)
                            throw new Exception('Match not found.');

                        // --- Permission Check for AC/AAC ---
                        if (!$is_admin && $is_officer_role) {
                            $matchArea = $oldMatch['creator_area'] ?? '';
                            if ((($oldMatch['is_retroactive'] == 1 || $oldMatch['is_local'] == 1)) && $matchArea !== $userArea) {
                                throw new Exception('You do not have permission to manage this retroactive/local match belonging to another area.');
                            }
                        }

                        $oldRmId = $oldMatch['rm_id'];

                        // If dates are empty (e.g. disabled in UI for completed matches), keep old values
                        $startDate = !empty($_POST['start_date']) ? $_POST['start_date'] : $oldMatch['start_date'];
                        $endDate = !empty($_POST['end_date']) ? $_POST['end_date'] : $oldMatch['end_date'];

                        // Handle retroactive/local preservation:
                        // - Admin: never sees the checkboxes in the edit form, so always preserve the original DB values.
                        // - Officer role (AC/AAC): sees and controls the checkboxes, so read from POST.
                        // - Anyone else: preserve the DB values.
                        if ($is_admin || !$is_officer_role) {
                            $isRetroactive = $oldMatch['is_retroactive'];
                            $isLocal = $oldMatch['is_local'];
                        }

                        $stmt = $pdo->prepare("UPDATE match_schedules SET match_name=?, start_date=?, end_date=?, match_level=?, range_master=?, location=?, ro_limit=?, rm_name=?, rm_id=?, is_retroactive=?, is_local=? WHERE id=?");
                        $stmt->execute([
                            $_POST['match_name'],
                            $startDate,
                            $endDate,
                            $_POST['match_level'],
                            $disciplinesStr,
                            $_POST['location'],
                            $_POST['ro_limit'],
                            $_POST['rm_name'],
                            $_POST['rm_id'] ?? null,
                            $isRetroactive,
                            $isLocal,
                            $_POST['match_id']
                        ]);

                        // --- Notify RM on update ---
                        $newRmId = $_POST['rm_id'] ?? null;
                        if (!empty($newRmId)) {
                            $stmtRmU = $pdo->prepare("SELECT email, first_name, last_name FROM users WHERE id = ?");
                            $stmtRmU->execute([$newRmId]);
                            $rmUserU = $stmtRmU->fetch(PDO::FETCH_ASSOC);
                            if ($rmUserU && !empty($rmUserU['email'])) {
                                $rmFullNameU = $rmUserU['first_name'] . ' ' . $rmUserU['last_name'];
                                $rmScheduleU = $_POST['start_date'] . ($_POST['start_date'] !== $_POST['end_date'] ? ' to ' . $_POST['end_date'] : '');
                                // New assignment if RM changed; details update if RM stayed the same
                                $isRmChanged = ((string) $oldRmId !== (string) $newRmId);
                                sendRmAssignmentNotification(
                                    $rmUserU['email'],
                                    $rmFullNameU,
                                    $_POST['match_name'],
                                    $_POST['match_level'],
                                    $disciplinesStr,
                                    $rmScheduleU,
                                    $_POST['location'],
                                    !$isRmChanged // isUpdate = true when same RM, false when newly assigned
                                );
                            }
                        }

                        if (!empty($_POST['removed_attachments'])) {
                            foreach ($_POST['removed_attachments'] as $attId) {
                                $stmt = $pdo->prepare("SELECT file_path FROM match_attachments WHERE id = ? AND match_id = ?");
                                $stmt->execute([$attId, $_POST['match_id']]);
                                $att = $stmt->fetch();
                                if ($att) {
                                    $fullPath = __DIR__ . '/../' . $att['file_path'];
                                    if (file_exists($fullPath))
                                        unlink($fullPath);
                                    $pdo->prepare("DELETE FROM match_attachments WHERE id = ?")->execute([$attId]);
                                }
                            }
                        }
                        handleMatchAttachments($pdo, $_POST['match_id'], $_FILES);
                    }
                    header("Location: matches.php" . (isset($_GET['view']) ? "?view=schedule&" : "?") . "success=" . ($action === 'create_match' ? "created" : "updated"));
                    exit;
                } catch (Exception $e) {
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'delete_match') {
                try {
                    $pdo->beginTransaction();
                    $matchId = (int) $_POST['match_id'];

                    // --- Permission Check for AC/AAC ---
                    if (!$is_admin && $is_officer_role) {
                        $stmtCheck = $pdo->prepare("SELECT is_retroactive, is_local, creator_area FROM match_schedules WHERE id = ?");
                        $stmtCheck->execute([$matchId]);
                        $matchData = $stmtCheck->fetch();
                        if ($matchData) {
                            $matchArea = $matchData['creator_area'] ?? '';
                            if ((($matchData['is_retroactive'] == 1 || $matchData['is_local'] == 1)) && $matchArea !== $userArea) {
                                throw new Exception('You do not have permission to delete this retroactive/local match belonging to another area.');
                            }
                        }
                    }

                    // 1. Unlink attachment files
                    $stmtAtt = $pdo->prepare("SELECT file_path FROM match_attachments WHERE match_id = ?");
                    $stmtAtt->execute([$matchId]);
                    while ($att = $stmtAtt->fetch()) {
                        $fullPath = __DIR__ . '/../' . $att['file_path'];
                        if (!empty($att['file_path']) && file_exists($fullPath)) {
                            unlink($fullPath);
                        }
                    }

                    // 2. Clear all match-related tables
                    $tables = [
                        'match_points',
                        'match_range_master_assignments',
                        'match_states_assignments',
                        'match_stats_assignments',
                        'match_chrono_assignments',
                        'match_equipment_check_assignments',
                        'match_attachments',
                        'match_schedules'
                    ];

                    foreach ($tables as $tbl) {
                        $stmtDel = $pdo->prepare("DELETE FROM $tbl WHERE " . ($tbl === 'match_schedules' ? "id" : "match_id") . " = ?");
                        $stmtDel->execute([$matchId]);
                    }

                    $pdo->commit();
                    header("Location: matches.php" . (isset($_GET['view']) ? "?view=schedule&" : "?") . "success=deleted");
                    exit;
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'save_point_card_assignment') {
                // Save assignment and match points for an incomplete user (admin/AC/AAC)
                require_once '../config/points_config.php';
                try {
                    $pCMatchId = (int) ($_POST['pc_match_id'] ?? 0);
                    $pCUserId = (int) ($_POST['pc_user_id'] ?? 0);
                    $pCType = trim($_POST['pc_assignment_type'] ?? '');
                    $pCRole = trim($_POST['pc_role'] ?? '');
                    $pCOfficer = trim($_POST['pc_officer_name'] ?? '');
                    $pCStageNum = trim($_POST['pc_stage_number'] ?? '');
                    $pCSigData = $_POST['pc_rm_signature'] ?? '';

                    $allowedTypes = ['states', 'chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master'];
                    // Add dynamic types from DB
                    foreach ($dynamicMatchAssignments as $dma) {
                        $allowedTypes[] = strtolower(str_replace(' ', '_', $dma['name']));
                    }
                    if (!in_array($pCType, $allowedTypes))
                        throw new Exception('Invalid assignment type.');
                    if ($pCMatchId < 1 || $pCUserId < 1)
                        throw new Exception('Missing match or user.');
                    if ($pCRole === '')
                        throw new Exception('Role is required.');
                    if ($pCOfficer === '' && $pCType !== 'states')
                        throw new Exception('Officer name is required.');
                    if ($pCType === 'states' && $pCStageNum === '')
                        throw new Exception('Stage number is required.');
                    if ($pCType === 'states' && $pCOfficer === '')
                        throw new Exception('LRO name is required.');
                    if ($pCSigData === '')
                        throw new Exception('RM signature is required.');

                    // Save signature
                    $signaturePath = '';
                    if (!empty($pCSigData)) {
                        $sigRaw = $pCSigData;
                        $ext = 'png';
                        if (preg_match('/^data:image\/(\w+);base64,/', $sigRaw, $smatch)) {
                            $sigRaw = substr($sigRaw, strpos($sigRaw, ',') + 1);
                            $ext = strtolower($smatch[1]);
                        }
                        $sigDecoded = base64_decode($sigRaw, true);
                        if ($sigDecoded === false)
                            throw new Exception('Invalid signature data.');
                        $sigDir = __DIR__ . '/../storage/assignments_signatures/';
                        if (!is_dir($sigDir))
                            mkdir($sigDir, 0777, true);
                        $sigFile = 'web_' . $pCType . '_sig_' . $pCMatchId . '_' . $pCUserId . '_' . time() . '.' . $ext;
                        if (!file_put_contents($sigDir . $sigFile, $sigDecoded))
                            throw new Exception('Failed to save signature.');
                        $signaturePath = 'storage/assignments_signatures/' . $sigFile;
                    }

                    // Save to assignment table
                    if ($pCType === 'states') {
                        $tbl = 'match_states_assignments';
                        $pdo->exec("CREATE TABLE IF NOT EXISTS `$tbl` (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))");
                        try {
                            $pdo->exec("ALTER TABLE `$tbl` ADD COLUMN lro_name VARCHAR(255) NULL AFTER states_number");
                        } catch (Exception $e) {
                        }
                        try {
                            $pdo->exec("ALTER TABLE `$tbl` ADD COLUMN role VARCHAR(100) NULL AFTER lro_name");
                        } catch (Exception $e) {
                        }
                        $stmtA = $pdo->prepare("INSERT INTO `$tbl` (match_id, states_number, lro_name, role, rm_signature, submitted_by) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE states_number=VALUES(states_number), lro_name=VALUES(lro_name), role=VALUES(role), rm_signature=VALUES(rm_signature)");
                        $stmtA->execute([$pCMatchId, $pCStageNum, $pCOfficer, $pCRole, $signaturePath, $pCUserId]);
                    } else {
                        $tbl = 'match_' . $pCType . '_assignments';
                        $pdo->exec("CREATE TABLE IF NOT EXISTS `$tbl` (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_{$pCType} (match_id, submitted_by))");
                        try {
                            $pdo->exec("ALTER TABLE `$tbl` ADD COLUMN role VARCHAR(100) NULL AFTER officer_name");
                        } catch (Exception $e) {
                        }
                        $stmtA = $pdo->prepare("INSERT INTO `$tbl` (match_id, officer_name, role, rm_signature, submitted_by) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE officer_name=VALUES(officer_name), role=VALUES(role), rm_signature=VALUES(rm_signature)");
                        $stmtA->execute([$pCMatchId, $pCOfficer, $pCRole, $signaturePath, $pCUserId]);
                    }

                    // Calculate and save match_points
                    $stmtMD = $pdo->prepare("SELECT match_level, range_master FROM match_schedules WHERE id = ?");
                    $stmtMD->execute([$pCMatchId]);
                    $mData = $stmtMD->fetch(PDO::FETCH_ASSOC);
                    $pts = nroi_compute_match_points($mData['match_level'] ?? '', $mData['range_master'] ?? '');

                    $stmtPts = $pdo->prepare("INSERT INTO match_points (match_id, user_id, points, rm_signature) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE points=VALUES(points), rm_signature=VALUES(rm_signature)");
                    $stmtPts->execute([$pCMatchId, $pCUserId, $pts, $signaturePath]);

                    // Reset is_extended flag since the point card has now been properly filled
                    $pdo->prepare("UPDATE match_significations SET is_extended = 0 WHERE match_id = ? AND user_id = ?")->execute([$pCMatchId, $pCUserId]);

                    // Sync profile assignment/role
                    if ($pCType !== '' && $pCRole !== '') {
                        $typeNamePC = ($pCType === 'states') ? 'Stage' : $pCType;
                        if ($pCType !== 'states') {
                            foreach ($dynamicMatchAssignments as $dma) {
                                $dKey = strtolower(str_replace(' ', '_', $dma['name']));
                                if ($dKey === $pCType) {
                                    $typeNamePC = $dma['name'];
                                    break;
                                }
                            }
                        }
                        $pdo->prepare("UPDATE users SET match_assignment = ?, match_role = ? WHERE id = ?")
                            ->execute([$typeNamePC, $pCRole, $pCUserId]);
                    }

                    $redirectMatchId = $_POST['pc_redirect_match_id'] ?? $pCMatchId;
                    header("Location: matches.php?view=participants&match_id={$redirectMatchId}&success=pointcard");
                    exit;
                } catch (Exception $e) {
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'return_point_card') {
                // Return point card: delete existing record, clear assignment, flag as extended
                // so the Fill Point Card re-appears on the user's app dashboard.
                try {
                    $rpMatchId = (int) ($_POST['rp_match_id'] ?? 0);
                    $rpUserId = (int) ($_POST['rp_user_id'] ?? 0);
                    $rpType = trim($_POST['rp_assignment_type'] ?? '');
                    $rpRole = trim($_POST['rp_role'] ?? '');
                    $rpOfficer = trim($_POST['rp_officer_name'] ?? '');
                    $rpStage = trim($_POST['rp_stage_number'] ?? '');
                    $rpLro = trim($_POST['rp_lro_name'] ?? '');

                    $allowedRpTypes = ['states', 'chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master'];
                    // Add dynamic types from DB
                    foreach ($dynamicMatchAssignments as $dma) {
                        $allowedRpTypes[] = strtolower(str_replace(' ', '_', $dma['name']));
                    }
                    if (!in_array($rpType, $allowedRpTypes))
                        throw new Exception('Invalid assignment type for return.');
                    if ($rpMatchId < 1 || $rpUserId < 1)
                        throw new Exception('Missing match or user for return.');
                    if ($rpRole === '')
                        throw new Exception('Role is required for return.');

                    $pdo->beginTransaction();

                    // 1. Delete existing match_points record for this user+match
                    $pdo->prepare("DELETE FROM match_points WHERE match_id = ? AND user_id = ?")->execute([$rpMatchId, $rpUserId]);

                    // 2. Clear all assignment records for this user+match
                    $assignTables = ['match_states_assignments', 'match_chrono_assignments', 'match_stats_assignments', 'match_equipment_check_assignments', 'match_range_master_assignments'];
                    foreach ($assignTables as $atbl) {
                        try {
                            $pdo->prepare("DELETE FROM `$atbl` WHERE match_id = ? AND submitted_by = ?")->execute([$rpMatchId, $rpUserId]);
                        } catch (Exception $e) { /* table may not exist */
                        }
                    }
                    // Also clear quarter_master assignments table if it exists
                    try {
                        $pdo->prepare("DELETE FROM match_quarter_master_assignments WHERE match_id = ? AND submitted_by = ?")->execute([$rpMatchId, $rpUserId]);
                    } catch (Exception $e) {
                    }

                    // 3. Save the new assignment details (WITHOUT rm_signature — user's RM will sign on app)
                    if ($rpType === 'states') {
                        $tblR = 'match_states_assignments';
                        $pdo->exec("CREATE TABLE IF NOT EXISTS `$tblR` (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))");
                        $stmtRA = $pdo->prepare("INSERT INTO `$tblR` (match_id, states_number, lro_name, role, rm_signature, submitted_by) VALUES (?,?,?,?,NULL,?) ON DUPLICATE KEY UPDATE states_number=VALUES(states_number), lro_name=VALUES(lro_name), role=VALUES(role), rm_signature=NULL");
                        $stmtRA->execute([$rpMatchId, $rpStage, $rpLro, $rpRole, $rpUserId]);
                    } else {
                        $tblR = 'match_' . $rpType . '_assignments';
                        $pdo->exec("CREATE TABLE IF NOT EXISTS `$tblR` (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_{$rpType} (match_id, submitted_by))");
                        $stmtRA = $pdo->prepare("INSERT INTO `$tblR` (match_id, officer_name, role, rm_signature, submitted_by) VALUES (?,?,?,NULL,?) ON DUPLICATE KEY UPDATE officer_name=VALUES(officer_name), role=VALUES(role), rm_signature=NULL");
                        $stmtRA->execute([$rpMatchId, $rpOfficer, $rpRole, $rpUserId]);
                    }

                    // 4. Set is_extended = 1 so that get_ongoing_match.php returns this match as a Fill Point Card
                    try {
                        $pdo->exec("ALTER TABLE match_significations ADD COLUMN is_extended TINYINT(1) DEFAULT 0");
                    } catch (Exception $e) {
                    }
                    $pdo->prepare("UPDATE match_significations SET is_extended = 1 WHERE match_id = ? AND user_id = ?")->execute([$rpMatchId, $rpUserId]);

                    // Sync profile assignment/role
                    if ($rpType !== '' && $rpRole !== '') {
                        $typeNameRP = ($rpType === 'states') ? 'Stage' : $rpType;
                        if ($rpType !== 'states') {
                            foreach ($dynamicMatchAssignments as $dma) {
                                $dKey = strtolower(str_replace(' ', '_', $dma['name']));
                                if ($dKey === $rpType) {
                                    $typeNameRP = $dma['name'];
                                    break;
                                }
                            }
                        }
                        $pdo->prepare("UPDATE users SET match_assignment = ?, match_role = ? WHERE id = ?")
                            ->execute([$typeNameRP, $rpRole, $rpUserId]);
                    }

                    $pdo->commit();

                    $redirectMatchId = $_POST['rp_redirect_match_id'] ?? $rpMatchId;
                    header("Location: matches.php?view=participants&match_id={$redirectMatchId}&success=returned");
                    exit;
                } catch (Exception $e) {
                    if ($pdo->inTransaction())
                        $pdo->rollBack();
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'terminate_returned_point_card') {
                try {
                    $mId = (int) ($_POST['match_id'] ?? 0);
                    $uId = (int) ($_POST['user_id'] ?? 0);
                    if ($mId < 1 || $uId < 1)
                        throw new Exception('Missing data for termination.');

                    $pdo->beginTransaction();
                    $pdo->prepare("UPDATE match_significations SET is_extended = 0 WHERE match_id = ? AND user_id = ?")->execute([$mId, $uId]);
                    $assignTables = ['match_states_assignments', 'match_chrono_assignments', 'match_stats_assignments', 'match_equipment_check_assignments', 'match_range_master_assignments', 'match_quarter_master_assignments'];
                    foreach ($assignTables as $atbl) {
                        try {
                            $pdo->prepare("DELETE FROM `$atbl` WHERE match_id = ? AND submitted_by = ?")->execute([$mId, $uId]);
                        } catch (Exception $e) {
                        }
                    }
                    $pdo->commit();
                    header("Location: matches.php?view=participants&match_id={$mId}&success=terminated");
                    exit;
                } catch (Exception $e) {
                    if ($pdo->inTransaction())
                        $pdo->rollBack();
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'request_rm_signing') {
                try {
                    $mId = (int) ($_POST['match_id'] ?? 0);
                    $uId = (int) ($_POST['user_id'] ?? 0);
                    if ($mId < 1 || $uId < 1)
                        throw new Exception('Missing data for RM signing request.');

                    // Save assignment details before enabling RM signing
                    $type = trim($_POST['assignment_type'] ?? '');
                    $role = trim($_POST['role'] ?? '');
                    if ($type !== '' && $role !== '') {
                        if ($type === 'states') {
                            $tbl = 'match_states_assignments';
                            $pdo->exec("CREATE TABLE IF NOT EXISTS `$tbl` (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))");
                            $stmtA = $pdo->prepare("INSERT INTO `$tbl` (match_id, states_number, lro_name, role, submitted_by) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE states_number=VALUES(states_number), lro_name=VALUES(lro_name), role=VALUES(role)");
                            $stmtA->execute([$mId, $_POST['stage_number'] ?? '', $_POST['lro_name'] ?? '', $role, $uId]);
                        } else {
                            $tbl = 'match_' . $type . '_assignments';
                            $pdo->exec("CREATE TABLE IF NOT EXISTS `$tbl` (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_{$type} (match_id, submitted_by))");
                            $stmtA = $pdo->prepare("INSERT INTO `$tbl` (match_id, officer_name, role, submitted_by) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE officer_name=VALUES(officer_name), role=VALUES(role)");
                            $stmtA->execute([$mId, $_POST['officer_name'] ?? '', $role, $uId]);
                        }
                    }

                    $pdo->prepare("UPDATE match_significations SET is_rm_enabled = 1 WHERE match_id = ? AND user_id = ?")->execute([$mId, $uId]);

                    // Sync profile assignment/role so get_match_significations.php prioritizes it
                    if ($type !== '' && $role !== '') {
                        $typeName = $type;
                        if ($type === 'states')
                            $typeName = 'Stage';
                        else {
                            // Try to find the original name from reference_match_assignments
                            foreach ($dynamicMatchAssignments as $dma) {
                                $dKey = strtolower(str_replace(' ', '_', $dma['name']));
                                if ($dKey === $type) {
                                    $typeName = $dma['name'];
                                    break;
                                }
                            }
                        }
                        $pdo->prepare("UPDATE users SET match_assignment = ?, match_role = ? WHERE id = ?")
                            ->execute([$typeName, $role, $uId]);
                    }
                    header("Location: matches.php?view=participants&match_id={$mId}&success=rm_requested");
                    exit;
                } catch (Exception $e) {
                    $error_message = addslashes($e->getMessage());
                }
            } elseif ($action === 'terminate_rm_signing') {
                try {
                    $mId = (int) ($_POST['match_id'] ?? 0);
                    $uId = (int) ($_POST['user_id'] ?? 0);
                    if ($mId < 1 || $uId < 1)
                        throw new Exception('Missing data for RM signing termination.');

                    $pdo->prepare("UPDATE match_significations SET is_rm_enabled = 0 WHERE match_id = ? AND user_id = ?")->execute([$mId, $uId]);
                    header("Location: matches.php?view=participants&match_id={$mId}&success=rm_terminated");
                    exit;
                } catch (Exception $e) {
                    $error_message = addslashes($e->getMessage());
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Matches | NROI Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
    <style>
        .input-error {
            border-color: #ef4444 !important;
            background-color: #fef2f2 !important;
        }

        .error-label {
            color: #ef4444 !important;
        }

        .row-incomplete td {
            position: relative;
            background-color: rgba(239, 68, 68, 0.05) !important;
        }

        .row-incomplete td::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-top: 3px solid #ef4444;
            border-bottom: 3px solid #ef4444;
            pointer-events: none;
            z-index: 10;
        }

        .row-incomplete td:first-child::after {
            border-left: 3px solid #ef4444;
            border-top-left-radius: 8px;
            border-bottom-left-radius: 8px;
        }

        .row-incomplete td:last-child::after {
            border-right: 3px solid #ef4444;
            border-top-right-radius: 8px;
            border-bottom-right-radius: 8px;
        }
    </style>
</head>

<body class="dashboard-body">

    <datalist id="rm_names">
        <?php foreach ($rmUsersList as $rmu): ?>
            <option value="<?php echo htmlspecialchars($rmu['first_name'] . ' ' . $rmu['last_name']); ?>">
                <?php echo htmlspecialchars($rmu['nroi_id']); ?>
            </option>
        <?php endforeach; ?>
    </datalist>

    <?php include '../includes/loader.php'; ?>


    <!-- Sidebar Navigation -->
    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($is_admin) {
                    echo 'ADMIN';
                } else {
                    $role = $_SESSION['user_role'] ?? 'OFFICER';
                    if ($role === 'AC')
                        echo 'A.C';
                    elseif ($role === 'AAC')
                        echo 'A.A.C';
                    else
                        echo htmlspecialchars($role);
                }
                ?>
            </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 active">
                        <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>
                <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): ?>
                    <li class="sidebar-item">
                        <a href="../officer/notifications.php" class="sidebar-link">
                            <i class="fas fa-bell"></i> Notifications
                        </a>
                    </li>
                    <?php if ($is_officer_role): ?>
                        <li class="sidebar-item">
                            <a href="users.php" class="sidebar-link">
                                <i class="fas fa-user-friends"></i> Accounts
                            </a>
                        </li>
                    <?php endif; ?>
                    <li class="sidebar-item">
                        <a href="matches.php" class="sidebar-link active">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <?php if ($is_officer_role): ?>
                        <li class="sidebar-item">
                            <a href="request.php" class="sidebar-link">
                                <i class="fas fa-inbox"></i> For Approval
                            </a>
                        </li>
                    <?php endif; ?>
                <?php endif; ?>
                <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; ?>
        </ul>

        <!-- Sidebar Profile -->
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">
                    <?php
                    if ($is_admin) {
                        echo 'AD';
                    } 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';
                        else {
                            $role = $_SESSION['user_role'] ?? 'Officer';
                            if ($role === 'AC')
                                echo 'A.C Account';
                            elseif ($role === 'AAC')
                                echo 'A.A.C Account';
                            else
                                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="<?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">
            <?php if (isset($_GET['success'])): ?>
                <div class="success-banner"
                    style="background: #10b981; color: white; padding: 12px 20px; border-radius: 8px; margin: 20px; display: flex; justify-content: space-between; align-items: center; transition: opacity 0.5s ease;">
                    <span>
                        <i class="fas fa-check-circle"></i>
                        <?php
                        if ($_GET['success'] === 'created')
                            echo 'Match created successfully!';
                        elseif ($_GET['success'] === 'updated')
                            echo 'Match updated successfully!';
                        elseif ($_GET['success'] === 'deleted')
                            echo 'Match deleted successfully!';
                        elseif ($_GET['success'] === 'pointcard')
                            echo 'Point card assignment saved successfully!';
                        elseif ($_GET['success'] === 'returned')
                            echo 'Point card returned — the user\'s Fill Point Card is now visible on their app dashboard.';
                        elseif ($_GET['success'] === 'rm_requested')
                            echo 'RM signing requested — the user record is now visible on the RM\'s app dashboard.';
                        elseif ($_GET['success'] === 'rm_terminated')
                            echo 'RM signing terminated — the record has been removed from the RM\'s app dashboard.';
                        elseif ($_GET['success'] === 'terminated')
                            echo 'Returned point card terminated successfully.';
                        ?>
                    </span>
                    <button onclick="this.parentElement.remove()"
                        style="background: none; border: none; color: white; cursor: pointer; font-size: 1.2rem;">&times;</button>
                </div>
                <script>
                    if (window.history.replaceState) {
                        const url = new URL(window.location.href);
                        url.searchParams.delete('success');
                        window.history.replaceState(null, null, url.pathname + url.search);
                    }
                </script>
            <?php endif; ?>
            <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
            $is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
            $is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
            $is_officer_role = $is_ac || $is_aac;
            ?>

            <?php if (($is_admin || $is_officer_role) && (!isset($_GET['view']) || ($_GET['view'] !== 'participants' && $_GET['view'] !== 'history' && $_GET['view'] !== 'signified' && $_GET['view'] !== 'schedule' && $_GET['view'] !== 'points'))): ?>
                <?php
                try {
                    // The disciplines and rmUsersList are now fetched at the top of the file.
                    // $stmtDisc = $pdo->query("SELECT * FROM disciplines WHERE name != 'Bad Record' ORDER BY name ASC");
                    // $disciplines = $stmtDisc->fetchAll(PDO::FETCH_ASSOC);
            
                    // Fetch approved RM users for the Range Master Name field
                    // $stmtRM = $pdo->query("SELECT first_name, last_name FROM users WHERE role = 'RM' AND status = 'approved' ORDER BY last_name ASC");
                    // $rm_users = $stmtRM->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e) {
                    // $disciplines = []; // Already handled by global fetch
                    // $rm_users = []; // Already handled by global fetch
                }

                if (isset($error_message)) {
                    echo "<script>alert('Action failed: " . $error_message . "');</script>";
                }

                // Fetch Ongoing Matches with creator info
                $today = date('Y-m-d');
                $userArea = $_SESSION['area'] ?? '';

                $ongoingQuery = "
                    SELECT 
                        m.*,
                        u.first_name as creator_first_name,
                        u.last_name as creator_last_name,
                        u.area as creator_area_display
                    FROM match_schedules m
                    LEFT JOIN users u ON m.created_by = u.id
                    WHERE m.start_date <= ? AND m.end_date >= ?
                ";
                $ongoingParams = [$today, $today];

                if (!$is_admin) {
                    $ongoingQuery .= " AND ( (m.is_retroactive = 0 AND m.is_local = 0) OR m.creator_area = ? )";
                    $ongoingParams[] = $userArea;
                }

                $ongoingQuery .= " GROUP BY m.id ORDER BY m.start_date ASC ";
                $stmt = $pdo->prepare($ongoingQuery);
                $stmt->execute($ongoingParams);
                $ongoingMatches = $stmt->fetchAll();

                // Fetch Upcoming Matches
                $upcomingQuery = "
                    SELECT 
                        m.*,
                        u.first_name as creator_first_name,
                        u.last_name as creator_last_name,
                        u.area as creator_area_display
                    FROM match_schedules m
                    LEFT JOIN users u ON m.created_by = u.id
                    WHERE m.start_date > ?
                ";
                $upcomingParams = [$today];

                if (!$is_admin) {
                    $upcomingQuery .= " AND ( (m.is_retroactive = 0 AND m.is_local = 0) OR m.creator_area = ? )";
                    $upcomingParams[] = $userArea;
                }

                $upcomingQuery .= " GROUP BY m.id ORDER BY m.start_date ASC ";
                $stmt = $pdo->prepare($upcomingQuery);
                $stmt->execute($upcomingParams);
                $upcomingMatches = $stmt->fetchAll();

                // Fetch Completed Matches
                $completedQuery = "
                    SELECT 
                        m.*,
                        u.first_name as creator_first_name,
                        u.last_name as creator_last_name,
                        u.area as creator_area_display
                    FROM match_schedules m
                    LEFT JOIN users u ON m.created_by = u.id
                    WHERE m.end_date < ?
                ";
                $completedParams = [$today];

                if (!$is_admin) {
                    $completedQuery .= " AND ( (m.is_retroactive = 0 AND m.is_local = 0) OR m.creator_area = ? )";
                    $completedParams[] = $userArea;
                }

                $completedQuery .= " GROUP BY m.id ORDER BY m.end_date DESC ";
                $stmt = $pdo->prepare($completedQuery);
                $stmt->execute($completedParams);
                $completedMatches = $stmt->fetchAll();

                // Fetch attachments for all matches
                function getAttachmentsForMatches($pdo, $matches)
                {
                    if (empty($matches))
                        return [];
                    $ids = array_column($matches, 'id');
                    $in = str_repeat('?,', count($ids) - 1) . '?';
                    $stmt = $pdo->prepare("SELECT * FROM match_attachments WHERE match_id IN ($in)");
                    $stmt->execute($ids);
                    $allAtts = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    $map = [];
                    foreach ($allAtts as $att) {
                        $map[$att['match_id']][] = $att;
                    }
                    return $map;
                }

                $allMatches = array_merge($ongoingMatches, $upcomingMatches, $completedMatches);
                $attachmentsMap = getAttachmentsForMatches($pdo, $allMatches);

                foreach ($ongoingMatches as &$m)
                    $m['attachments'] = $attachmentsMap[$m['id']] ?? [];
                unset($m);
                foreach ($upcomingMatches as &$m)
                    $m['attachments'] = $attachmentsMap[$m['id']] ?? [];
                unset($m);
                foreach ($completedMatches as &$m)
                    $m['attachments'] = $attachmentsMap[$m['id']] ?? [];
                unset($m);
                ?>

                <?php
                // Encode all matches as JSON for client-side filtering
                $allMatchesForJs = [];
                foreach ($ongoingMatches as $m) {
                    $allMatchesForJs[] = array_merge($m, ['_section' => 'ongoing']);
                }
                foreach ($upcomingMatches as $m) {
                    $allMatchesForJs[] = array_merge($m, ['_section' => 'upcoming']);
                }
                foreach ($completedMatches as $m) {
                    $allMatchesForJs[] = array_merge($m, ['_section' => 'completed']);
                }
                ?>
                <style>
                    .content-box,
                    .matches-filter-bar {
                        background: rgba(255, 255, 255, 0.85);
                        /* Whiter background for better readability */
                        backdrop-filter: blur(16px);
                        -webkit-backdrop-filter: blur(16px);
                        border-radius: 16px;
                        border: 1px solid rgba(255, 255, 255, 0.8);
                        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06);
                        overflow: hidden;
                    }

                    .matches-filter-bar {
                        display: flex;
                        flex-wrap: wrap;
                        gap: 10px;
                        align-items: center;
                        margin-bottom: 20px;
                        padding: 18px 24px;
                    }

                    .matches-search-wrap {
                        display: flex;
                        align-items: center;
                        flex: 1;
                        min-width: 200px;
                        background: #f1f5f9;
                        border-radius: 10px;
                        padding: 0 12px;
                        border: 1.5px solid #e2e8f0;
                        transition: border-color .2s;
                    }

                    .matches-search-wrap:focus-within {
                        border-color: #1e3a8a;
                        background: #fff;
                    }

                    .matches-search-wrap i {
                        color: #94a3b8;
                        font-size: 0.9rem;
                        margin-right: 8px;
                    }

                    .matches-search-input {
                        border: none;
                        background: transparent;
                        outline: none;
                        font-size: 0.9rem;
                        color: #1e293b;
                        width: 100%;
                        padding: 9px 0;
                        font-family: inherit;
                    }

                    .matches-search-input::placeholder {
                        color: #94a3b8;
                    }

                    .matches-date-wrap {
                        display: flex;
                        align-items: center;
                        gap: 6px;
                        background: #f1f5f9;
                        border-radius: 10px;
                        padding: 0 12px;
                        border: 1.5px solid #e2e8f0;
                        cursor: pointer;
                        transition: border-color .2s, background .2s;
                    }

                    .matches-date-wrap:hover,
                    .matches-date-wrap.active-date {
                        border-color: #1e3a8a;
                        background: #eff6ff;
                    }

                    .matches-date-wrap i {
                        color: #1e3a8a;
                        font-size: 0.95rem;
                    }

                    #matchDatePicker {
                        border: none;
                        background: transparent;
                        outline: none;
                        font-size: 0.85rem;
                        color: #1e293b;
                        font-family: inherit;
                        cursor: pointer;
                        width: 110px;
                        padding: 9px 0;
                    }

                    .period-pills {
                        display: flex;
                        gap: 6px;
                    }

                    .period-pill {
                        padding: 7px 15px;
                        border-radius: 20px;
                        border: 1.5px solid #e2e8f0;
                        font-size: 0.8rem;
                        font-weight: 600;
                        cursor: pointer;
                        background: #f1f5f9;
                        color: #475569;
                        transition: all .2s;
                        user-select: none;
                    }

                    .period-pill:hover {
                        border-color: #1e3a8a;
                        color: #1e3a8a;
                        background: #eff6ff;
                    }

                    .period-pill.active {
                        background: #1e3a8a;
                        color: #fff;
                        border-color: #1e3a8a;
                        box-shadow: 0 2px 8px rgba(30, 58, 138, 0.18);
                    }

                    .matches-clear-btn {
                        display: none;
                        align-items: center;
                        gap: 5px;
                        padding: 7px 13px;
                        border-radius: 10px;
                        border: 1.5px solid #fca5a5;
                        background: #fff5f5;
                        color: #dc2626;
                        font-size: 0.8rem;
                        font-weight: 600;
                        cursor: pointer;
                        transition: all .2s;
                    }

                    .matches-clear-btn:hover {
                        background: #fee2e2;
                    }

                    .matches-no-results p {
                        font-size: 0.95rem;
                        margin: 0;
                    }

                    .location-cell {
                        max-width: 160px;
                        min-width: 120px;
                        white-space: normal !important;
                        word-wrap: break-word !important;
                        word-break: break-word !important;
                        vertical-align: top !important;
                        line-height: 1.4;
                    }

                    .match-section-title {
                        padding: 20px 24px;
                        font-size: 1.1rem;
                        font-weight: 800;
                        color: #1e3a8a;
                        letter-spacing: 1.5px;
                        text-transform: uppercase;
                        background: rgba(255, 255, 255, 0.4);
                        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        text-align: center;
                    }

                    .match-section-title span {
                        display: flex;
                        align-items: center;
                        gap: 12px;
                    }

                    .modern-table {
                        display: table;
                        width: 100%;
                        border-collapse: separate;
                        border-spacing: 0;
                    }

                    .modern-table th {
                        background: rgba(241, 245, 249, 0.5);
                        padding: 14px 24px;
                        font-size: 0.75rem;
                        font-weight: 700;
                        color: #64748b;
                        text-transform: uppercase;
                        letter-spacing: 1px;
                        text-align: left;
                        border-bottom: 1px solid rgba(226, 232, 240, 0.5);
                    }

                    .modern-table td {
                        padding: 16px 24px;
                        vertical-align: middle;
                        border-bottom: 1px solid rgba(0, 0, 0, 0.04);
                        transition: all 0.2s;
                        color: #1e293b;
                        /* Darker text for readability */
                    }

                    .modern-table tr:last-child td {
                        border-bottom: none;
                    }

                    .match-row:hover td {
                        background: rgba(255, 255, 255, 0.5);
                        transform: scale(1.002);
                    }

                    .match-section-scrollable {
                        max-height: 480px;
                        overflow-y: auto;
                        background: transparent;
                    }

                    /* Custom scrollbar for better look */
                    .match-section-scrollable::-webkit-scrollbar {
                        width: 6px;
                    }

                    .match-section-scrollable::-webkit-scrollbar-track {
                        background: #f1f5f9;
                    }

                    .match-section-scrollable::-webkit-scrollbar-thumb {
                        background: #cbd5e1;
                        border-radius: 3px;
                    }

                    .match-section-scrollable::-webkit-scrollbar-thumb:hover {
                        background: #94a3b8;
                    }

                    .match-section-empty {
                        text-align: center;
                        padding: 28px;
                        color: #94a3b8;
                        font-size: 0.9rem;
                    }

                    .match-section-empty i {
                        font-size: 1.6rem;
                        display: block;
                        margin-bottom: 8px;
                        opacity: .5;
                    }

                    .matches-no-results {
                        text-align: center;
                        padding: 40px 20px;
                        color: #94a3b8;
                    }

                    .matches-no-results i {
                        font-size: 2.5rem;
                        display: block;
                        margin-bottom: 12px;
                        opacity: .35;
                    }

                    .action-btns {
                        white-space: nowrap;
                    }

                    /* Range Master Selection Container Styles */
                    .rm-selection-wrapper {
                        border: 1px solid #e2e8f0;
                        border-radius: 10px;
                        background: #fff;
                        overflow: hidden;
                        margin-top: 5px;
                    }

                    .rm-search-box {
                        padding: 8px 12px;
                        border-bottom: 1px solid #f1f5f9;
                        background: #f8fafc;
                    }

                    .rm-search-input {
                        width: 100%;
                        padding: 6px 10px;
                        border: 1px solid #e2e8f0;
                        border-radius: 6px;
                        font-size: 0.85rem;
                        outline: none;
                    }

                    .rm-search-input:focus {
                        border-color: #1e3a8a;
                    }

                    .rm-list-container {
                        max-height: 180px;
                        overflow-y: auto;
                        padding: 5px;
                    }

                    .rm-list-item {
                        display: flex;
                        flex-direction: column;
                        padding: 8px 12px;
                        border-radius: 8px;
                        cursor: pointer;
                        transition: all 0.2s;
                        margin-bottom: 2px;
                        border: 1px solid transparent;
                    }

                    .rm-list-item:hover {
                        background: #f1f5f9;
                    }

                    .rm-list-item.selected {
                        background: #eff6ff;
                        border-color: #bfdbfe;
                        color: #1e3a8a;
                    }

                    .rm-item-name {
                        font-weight: 700;
                        font-size: 0.9rem;
                    }

                    .rm-item-info {
                        font-size: 0.75rem;
                        color: #64748b;
                        display: flex;
                        justify-content: space-between;
                        margin-top: 2px;
                    }

                    .rm-item.selected .rm-item-info {
                        color: #3b82f6;
                    }

                    .rm-role-badge {
                        font-size: 0.65rem;
                        background: #334155;
                        color: #fff;
                        padding: 1px 5px;
                        border-radius: 4px;
                    }
                </style>

                <!-- Filter Toolbar -->
                <div class="matches-filter-bar">

                    <!-- Date Picker (Daily) -->
                    <div id="dateWrapDaily"
                        style="position: relative; display: flex; align-items: center; gap: 5px; background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 0 10px; height: 42px;">
                        <i class="far fa-calendar-alt" style="color: #64748b; font-size: 0.9rem;"></i>
                        <input type="date" id="matchDatePicker" title="Filter by date" onchange="applyMatchFilters(true)"
                            style="border: none; background: transparent; padding: 10px 5px; font-size: 0.85rem; outline: none; color: #1e293b; cursor: pointer;">
                    </div>

                    <!-- View Mode Group -->
                    <div class="view-mode-group"
                        style="display: flex; gap: 8px; background: #f1f5f9; padding: 4px; border-radius: 10px; height: 42px; align-items: center;">
                        <div class="filter-tab active" id="tab-daily" onclick="setViewMode('daily')"
                            style="cursor:pointer; padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; color: #fff; background: var(--primary-color, #1e3a8a); font-weight: 500;">
                            Daily</div>
                        <div class="filter-tab" id="tab-weekly" onclick="setViewMode('weekly')"
                            style="cursor:pointer; padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; color: #64748b; background: transparent; font-weight: 500;">
                            Weekly</div>
                        <div class="filter-tab" id="tab-monthly" onclick="setViewMode('monthly')"
                            style="cursor:pointer; padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; color: #64748b; background: transparent; font-weight: 500;">
                            Monthly</div>
                        <div class="filter-tab" id="tab-yearly" onclick="setViewMode('yearly')"
                            style="cursor:pointer; padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; color: #64748b; background: transparent; font-weight: 500;">
                            Yearly</div>
                    </div>

                    <!-- Match Type Filter -->
                    <div
                        style="position: relative; display: flex; align-items: center; gap: 5px; background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 0 10px; height: 42px;">
                        <i class="fas fa-tag" style="color: #64748b; font-size: 0.9rem;"></i>
                        <select id="matchTypeFilter" onchange="applyMatchFilters(true)"
                            style="border: none; background: transparent; padding: 10px 30px 10px 5px; font-size: 0.85rem; outline: none; color: #1e293b; cursor: pointer; appearance: none; -webkit-appearance: none;">
                            <option value="all">All Types</option>
                            <option value="regular">Regular</option>
                            <option value="local">Local</option>
                            <option value="retroactive">Retroactive</option>
                        </select>
                        <i class="fas fa-chevron-down"
                            style="position: absolute; right: 12px; font-size: 0.7rem; color: #94a3b8; pointer-events: none;"></i>
                    </div>

                    <!-- Search Box -->
                    <div style="position: relative; flex: 1; min-width: 200px;">
                        <i class="fas fa-search"
                            style="position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: 0.9rem;"></i>
                        <input type="search" id="matchSearchInput"
                            placeholder="Search match name, location, RM, discipline…" oninput="applyMatchFilters(false)"
                            style="width: 100%; padding: 0 15px 0 40px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 0.9rem; outline: none; transition: all 0.2s; background: #fff; height: 42px;">
                    </div>

                    <!-- Clear button -->
                    <button class="matches-clear-btn" id="matchClearBtn" onclick="clearMatchFilters()"
                        style="height: 42px; border-radius: 12px;">
                        <i class="fas fa-times"></i> Clear
                    </button>

                    <button class="btn-primary"
                        style="margin: 0; width: auto; padding: 0 18px; height: 42px; font-size: 0.85rem; white-space: nowrap; border-radius: 12px; margin-left: auto;"
                        onclick="selectedMatchFiles['createMatchPreview'] = []; document.getElementById('createMatchPreview').innerHTML=''; document.getElementById('createMatchModal').classList.add('active')">
                        <i class="fas fa-plus"></i> Create Match
                    </button>
                </div>

                <div id="backToOverviewWrap" style="display: none; margin-bottom: 20px;">
                    <button onclick="backToOverview()" class="btn-secondary"
                        style="margin:0; width:auto; display: inline-flex; align-items:center; gap: 8px; padding: 8px 15px; border-radius: 10px;">
                        <i class="fas fa-chevron-left"></i> Back to <span id="backToOverviewText">Overview</span>
                    </button>
                </div>

                <!-- Group Selection Container -->
                <div id="groupsContainer" style="display:none; margin-bottom: 20px; padding: 0 10px;">
                    <div id="groupsGrid"
                        style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px;">
                    </div>
                </div>

                <!-- Matches Tables Wrapper -->
                <div id="matchesTablesWrapper">

                    <!-- Ongoing Matches Container -->
                    <div class="content-box" style="margin-bottom: 20px;" id="box-ongoing">
                        <div class="match-section-title" id="sec-title-ongoing">
                            <span><i class="fas fa-circle" style="color:#10b981; font-size:0.75rem; margin-right:8px;"></i>
                                Ongoing Matches <span id="sec-count-ongoing"
                                    style="font-size: 0.8rem; font-weight: 500; margin-left:5px; opacity:0.7;"></span></span>
                        </div>
                        <div class="table-responsive match-section-scrollable">
                            <table class="modern-table" id="table-ongoing">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Location</th>
                                        <th>RM</th>
                                        <th>Discipline</th>
                                        <th>Level</th>
                                        <th>RO Limit</th>
                                        <th>Area</th>
                                        <th>Schedule</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="tbody-ongoing">
                                    <?php if (empty($ongoingMatches)): ?>
                                        <tr class="no-data-row">
                                            <td colspan="10" class="match-section-empty">
                                                <i class="fas fa-calendar-check"></i>No ongoing matches at this time.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($ongoingMatches as $m): ?>
                                            <tr class="match-row" data-section="ongoing" data-id="<?php echo $m['id']; ?>"
                                                data-name="<?php echo strtolower(htmlspecialchars($m['match_name'] ?? '')); ?>"
                                                data-location="<?php echo strtolower(htmlspecialchars($m['location'] ?? '')); ?>"
                                                data-rm="<?php echo strtolower(htmlspecialchars($m['rm_name'] ?? '')); ?>"
                                                data-discipline="<?php echo strtolower(htmlspecialchars($m['range_master'] ?? '')); ?>"
                                                data-area="<?php echo strtolower(htmlspecialchars($m['creator_area_display'] ?? '')); ?>"
                                                data-type="<?php echo !empty($m['is_retroactive']) ? 'retroactive' : (!empty($m['is_local']) ? 'local' : 'regular'); ?>"
                                                data-start="<?php echo $m['start_date']; ?>"
                                                data-end="<?php echo $m['end_date']; ?>"
                                                onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'"
                                                style="cursor:pointer;">
                                                <td><?php echo htmlspecialchars($m['match_name']); ?></td>
                                                <td class="location-cell"><?php echo htmlspecialchars($m['location']); ?></td>
                                                <td><?php echo htmlspecialchars(capitalizeWords($m['rm_name'] ?? '---')); ?></td>
                                                <td><?php echo !empty($m['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($m['range_master'])) : '---'; ?>
                                                </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/', '', $m['match_level']); ?>
                                                    </div>
                                                </td>
                                                <td style="text-align:center;font-weight:600;color:#475569;">
                                                    <?php echo $m['ro_limit'] > 0 ? htmlspecialchars($m['ro_limit']) : '---'; ?>
                                                </td>
                                                <td style="text-align:center;">
                                                    <?php if (!empty($m['creator_area_display'])): ?>
                                                        <span
                                                            style="display:inline-block;background:#eff6ff;color:#1e3a8a;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #bfdbfe;"><?php echo htmlspecialchars($m['creator_area_display']); ?></span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#64748b; letter-spacing:0.5px;">
                                                            FOR:
                                                            <?php if (!empty($m['is_retroactive'])): ?>
                                                                <span style="color:#b45309;">Retroactive</span>
                                                                <i class="fas fa-lock"
                                                                    style="font-size:.6rem; color:#b45309; margin-left:2px;"></i>
                                                            <?php elseif (!empty($m['is_local'])): ?>
                                                                <span style="color:#16a34a;">Local</span>
                                                                <i class="fas fa-map-marker-alt"
                                                                    style="font-size:.6rem; color:#16a34a; margin-left:2px;"></i>
                                                            <?php else: ?>
                                                                <span style="color:#10b981;">Regular</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php else: ?>
                                                        <span
                                                            style="display:inline-block;background:#f8fafc;color:#64748b;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #e2e8f0;">N/A</span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#10b981; letter-spacing:0.5px;">
                                                            FOR: ALL</div>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="font-size:.85rem;">
                                                    <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                                </td>
                                                <td style="font-size:.85rem;line-height:1.4;">
                                                    <div style="font-weight:600;color:#475569;">
                                                        <?php echo ($m['creator_first_name'] && $m['creator_last_name']) ? htmlspecialchars(capitalizeWords($m['creator_last_name'] . ', ' . $m['creator_first_name'])) : '---'; ?>
                                                    </div>
                                                    <div style="color:#94a3b8;">
                                                        <?php echo isset($m['created_at']) ? date('M d, Y h:i A', strtotime($m['created_at'])) : '---'; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                        <?php if (!empty($m['attachments'])): ?>
                                                            <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                                onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                                title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                        <?php endif; ?>
                                                        <button class="icon-btn btn-edit"
                                                            onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                            title="Edit"><i class="fas fa-pen"></i></button>
                                                        <button class="icon-btn btn-reject"
                                                            onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                            title="Delete"><i class="fas fa-trash"></i></button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Upcoming Matches Container -->
                    <div class="content-box" style="margin-bottom: 20px;" id="box-upcoming">
                        <div class="match-section-title" id="sec-title-upcoming">
                            <span><i class="fas fa-clock" style="color:#f59e0b; font-size:0.75rem; margin-right:8px;"></i>
                                Upcoming Matches <span id="sec-count-upcoming"
                                    style="font-size: 0.8rem; font-weight: 500; margin-left:5px; opacity:0.7;"></span></span>
                        </div>
                        <div class="table-responsive match-section-scrollable">
                            <table class="modern-table" id="table-upcoming">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Location</th>
                                        <th>RM</th>
                                        <th>Discipline</th>
                                        <th>Level</th>
                                        <th>RO Limit</th>
                                        <th>Area</th>
                                        <th>Schedule</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="tbody-upcoming">
                                    <?php if (empty($upcomingMatches)): ?>
                                        <tr class="no-data-row">
                                            <td colspan="10" class="match-section-empty">
                                                <i class="fas fa-calendar-day"></i>No upcoming matches at this time.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($upcomingMatches as $m): ?>
                                            <tr class="match-row" data-section="upcoming" data-id="<?php echo $m['id']; ?>"
                                                data-name="<?php echo strtolower(htmlspecialchars($m['match_name'] ?? '')); ?>"
                                                data-location="<?php echo strtolower(htmlspecialchars($m['location'] ?? '')); ?>"
                                                data-rm="<?php echo strtolower(htmlspecialchars($m['rm_name'] ?? '')); ?>"
                                                data-discipline="<?php echo strtolower(htmlspecialchars($m['range_master'] ?? '')); ?>"
                                                data-area="<?php echo strtolower(htmlspecialchars($m['creator_area_display'] ?? '')); ?>"
                                                data-type="<?php echo !empty($m['is_retroactive']) ? 'retroactive' : (!empty($m['is_local']) ? 'local' : 'regular'); ?>"
                                                data-start="<?php echo $m['start_date']; ?>"
                                                data-end="<?php echo $m['end_date']; ?>"
                                                onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'"
                                                style="cursor:pointer;">
                                                <td><?php echo htmlspecialchars($m['match_name']); ?></td>
                                                <td class="location-cell"><?php echo htmlspecialchars($m['location']); ?></td>
                                                <td><?php echo htmlspecialchars(capitalizeWords($m['rm_name'] ?? '---')); ?></td>
                                                <td><?php echo !empty($m['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($m['range_master'])) : '---'; ?>
                                                </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/', '', $m['match_level']); ?>
                                                    </div>
                                                </td>
                                                <td style="text-align:center;font-weight:600;color:#475569;">
                                                    <?php echo $m['ro_limit'] > 0 ? htmlspecialchars($m['ro_limit']) : '---'; ?>
                                                </td>
                                                <td style="text-align:center;">
                                                    <?php if (!empty($m['creator_area_display'])): ?>
                                                        <span
                                                            style="display:inline-block;background:#eff6ff;color:#1e3a8a;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #bfdbfe;"><?php echo htmlspecialchars($m['creator_area_display']); ?></span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#64748b; letter-spacing:0.5px;">
                                                            FOR:
                                                            <?php if (!empty($m['is_retroactive'])): ?>
                                                                <span style="color:#b45309;">Retroactive</span>
                                                                <i class="fas fa-lock"
                                                                    style="font-size:.6rem; color:#b45309; margin-left:2px;"></i>
                                                            <?php elseif (!empty($m['is_local'])): ?>
                                                                <span style="color:#16a34a;">Local</span>
                                                                <i class="fas fa-map-marker-alt"
                                                                    style="font-size:.6rem; color:#16a34a; margin-left:2px;"></i>
                                                            <?php else: ?>
                                                                <span style="color:#10b981;">Regular</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php else: ?>
                                                        <span
                                                            style="display:inline-block;background:#f8fafc;color:#64748b;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #e2e8f0;">N/A</span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#10b981; letter-spacing:0.5px;">
                                                            FOR: ALL</div>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="font-size:.85rem;">
                                                    <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                                </td>
                                                <td style="font-size:.85rem;line-height:1.4;">
                                                    <div style="font-weight:600;color:#475569;">
                                                        <?php echo ($m['creator_first_name'] && $m['creator_last_name']) ? htmlspecialchars($m['creator_last_name'] . ', ' . $m['creator_first_name']) : '---'; ?>
                                                    </div>
                                                    <div style="color:#94a3b8;">
                                                        <?php echo isset($m['created_at']) ? date('M d, Y h:i A', strtotime($m['created_at'])) : '---'; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                        <?php if (!empty($m['attachments'])): ?>
                                                            <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                                onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                                title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                        <?php endif; ?>
                                                        <button class="icon-btn btn-edit"
                                                            onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                            title="Edit"><i class="fas fa-pen"></i></button>
                                                        <button class="icon-btn btn-reject"
                                                            onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                            title="Delete"><i class="fas fa-trash"></i></button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Completed Matches Container -->
                    <div class="content-box" style="margin-bottom: 20px;" id="box-completed">
                        <div class="match-section-title" id="sec-title-completed">
                            <span><i class="fas fa-check-circle"
                                    style="color:#64748b; font-size:0.75rem; margin-right:8px;"></i> Completed Matches <span
                                    id="sec-count-completed"
                                    style="font-size: 0.8rem; font-weight: 500; margin-left:5px; opacity:0.7;"></span></span>
                        </div>
                        <div class="table-responsive match-section-scrollable">
                            <table class="modern-table" id="table-completed">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Location</th>
                                        <th>RM</th>
                                        <th>Discipline</th>
                                        <th>Level</th>
                                        <th>RO Limit</th>
                                        <th>Area</th>
                                        <th>Schedule</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="tbody-completed">
                                    <?php if (empty($completedMatches)): ?>
                                        <tr class="no-data-row">
                                            <td colspan="10" class="match-section-empty">
                                                <i class="fas fa-check-circle"></i>No completed matches at this time.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($completedMatches as $m): ?>
                                            <tr class="match-row" data-section="completed" data-id="<?php echo $m['id']; ?>"
                                                data-name="<?php echo strtolower(htmlspecialchars($m['match_name'] ?? '')); ?>"
                                                data-location="<?php echo strtolower(htmlspecialchars($m['location'] ?? '')); ?>"
                                                data-rm="<?php echo strtolower(htmlspecialchars($m['rm_name'] ?? '')); ?>"
                                                data-discipline="<?php echo strtolower(htmlspecialchars($m['range_master'] ?? '')); ?>"
                                                data-area="<?php echo strtolower(htmlspecialchars($m['creator_area_display'] ?? '')); ?>"
                                                data-type="<?php echo !empty($m['is_retroactive']) ? 'retroactive' : (!empty($m['is_local']) ? 'local' : 'regular'); ?>"
                                                data-start="<?php echo $m['start_date']; ?>"
                                                data-end="<?php echo $m['end_date']; ?>" style="opacity:.75;cursor:pointer;"
                                                onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'">
                                                <td><?php echo htmlspecialchars($m['match_name']); ?></td>
                                                <td class="location-cell"><?php echo htmlspecialchars($m['location']); ?></td>
                                                <td><?php echo htmlspecialchars(capitalizeWords($m['rm_name'] ?? '---')); ?></td>
                                                <td><?php echo !empty($m['range_master']) ? str_replace(', ', '<br>', htmlspecialchars($m['range_master'])) : '---'; ?>
                                                </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/', '', $m['match_level']); ?>
                                                    </div>
                                                </td>
                                                <td style="text-align:center;font-weight:600;color:#475569;">
                                                    <?php echo $m['ro_limit'] > 0 ? htmlspecialchars($m['ro_limit']) : '---'; ?>
                                                </td>
                                                <td style="text-align:center;">
                                                    <?php if (!empty($m['creator_area_display'])): ?>
                                                        <span
                                                            style="display:inline-block;background:#eff6ff;color:#1e3a8a;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #bfdbfe;"><?php echo htmlspecialchars($m['creator_area_display']); ?></span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#64748b; letter-spacing:0.5px;">
                                                            FOR:
                                                            <?php if (!empty($m['is_retroactive'])): ?>
                                                                <span style="color:#b45309;">Retroactive</span>
                                                                <i class="fas fa-lock"
                                                                    style="font-size:.6rem; color:#b45309; margin-left:2px;"></i>
                                                            <?php elseif (!empty($m['is_local'])): ?>
                                                                <span style="color:#16a34a;">Local</span>
                                                                <i class="fas fa-map-marker-alt"
                                                                    style="font-size:.6rem; color:#16a34a; margin-left:2px;"></i>
                                                            <?php else: ?>
                                                                <span style="color:#10b981;">Regular</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php else: ?>
                                                        <span
                                                            style="display:inline-block;background:#f8fafc;color:#64748b;font-size:.78rem;font-weight:700;padding:3px 9px;border-radius:6px;border:1px solid #e2e8f0;">N/A</span>
                                                        <div
                                                            style="margin-top:4px; font-size:.7rem; font-weight:700; color:#10b981; letter-spacing:0.5px;">
                                                            FOR: ALL</div>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="font-size:.85rem;">
                                                    <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                                </td>
                                                <td style="font-size:.85rem;line-height:1.4;">
                                                    <div style="font-weight:600;color:#475569;">
                                                        <?php echo ($m['creator_first_name'] && $m['creator_last_name']) ? htmlspecialchars($m['creator_last_name'] . ', ' . $m['creator_first_name']) : '---'; ?>
                                                    </div>
                                                    <div style="color:#94a3b8;">
                                                        <?php echo isset($m['created_at']) ? date('M d, Y h:i A', strtotime($m['created_at'])) : '---'; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                        <?php if (!empty($m['attachments'])): ?>
                                                            <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                                onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                                title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                        <?php endif; ?>
                                                        <button class="icon-btn btn-edit"
                                                            onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                            title="Edit"><i class="fas fa-pen"></i></button>
                                                        <button class="icon-btn btn-reject"
                                                            onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                            title="Delete"><i class="fas fa-trash"></i></button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Global No Results -->
                        <div class="content-box" id="matchesNoResults"
                            style="display:none; text-align:center; margin-bottom: 20px;">
                            <div class="matches-no-results">
                                <i class="fas fa-search"></i>
                                <p>No matches found for your current filters.</p>
                            </div>
                        </div>

                    </div> <!-- End Matches Tables Wrapper -->

                    <script>
                        (function () {
                            let viewMode = 'daily'; // 'daily', 'weekly', 'monthly', 'yearly'
                            let filterDateStr = '';
                            let activeGroupStart = null;
                            let activeGroupEnd = null;

                            function toDate(s) { return s ? new Date(s + 'T00:00:00') : null; }
                            function overlaps(rowStart, rowEnd, rangeStart, rangeEnd) {
                                return rowStart <= rangeEnd && rowEnd >= rangeStart;
                            }

                            window.setViewMode = function (mode) {
                                viewMode = mode;
                                activeGroupStart = null;
                                activeGroupEnd = null;
                                document.getElementById('backToOverviewWrap').style.display = 'none';

                                document.querySelectorAll('.filter-tab').forEach(el => {
                                    el.style.background = 'transparent';
                                    el.style.color = '#64748b';
                                });
                                const tb = document.getElementById('tab-' + mode);
                                if (tb) {
                                    tb.style.background = 'var(--primary-color, #1e3a8a)';
                                    tb.style.color = '#fff';
                                }

                                if (mode === 'daily') {
                                    document.getElementById('groupsContainer').style.display = 'none';
                                    document.getElementById('matchesTablesWrapper').style.display = 'block';
                                    document.getElementById('dateWrapDaily').style.display = 'flex';
                                    applyMatchFilters(true);
                                } else {
                                    document.getElementById('matchesTablesWrapper').style.display = 'none';
                                    document.getElementById('dateWrapDaily').style.display = 'none';
                                    document.getElementById('groupsContainer').style.display = 'block';
                                    document.getElementById('matchesNoResults').style.display = 'none';
                                    renderGroups();
                                    applyMatchFilters(false); // To enable clear button if search exists
                                }
                            };

                            function renderGroups() {
                                const grid = document.getElementById('groupsGrid');
                                grid.innerHTML = '';

                                const q = document.getElementById('matchSearchInput').value.trim().toLowerCase();
                                const groups = {};

                                document.querySelectorAll('.match-row').forEach(row => {
                                    const name = row.dataset.name || '';
                                    const location = row.dataset.location || '';
                                    const rm = row.dataset.rm || '';
                                    const discipline = row.dataset.discipline || '';
                                    const areaSearch = row.dataset.area || '';
                                    const matchType = row.dataset.type || 'regular';
                                    const selectedType = document.getElementById('matchTypeFilter').value;

                                    const typeMatch = selectedType === 'all' || matchType === selectedType;
                                    const textMatch = !q || name.includes(q) || location.includes(q) || rm.includes(q) || discipline.includes(q) || areaSearch.includes(q);

                                    if (!textMatch || !typeMatch) return;

                                    const rowStart = toDate(row.dataset.start);
                                    if (!rowStart) return;

                                    let key, label, pStart, pEnd, icon;
                                    if (viewMode === 'monthly') {
                                        key = rowStart.getFullYear() + '-' + String(rowStart.getMonth() + 1).padStart(2, '0');
                                        label = rowStart.toLocaleString('default', { month: 'long', year: 'numeric' });
                                        pStart = new Date(rowStart.getFullYear(), rowStart.getMonth(), 1);
                                        pEnd = new Date(rowStart.getFullYear(), rowStart.getMonth() + 1, 0);
                                        icon = 'fa-calendar-alt';
                                    } else if (viewMode === 'yearly') {
                                        key = rowStart.getFullYear().toString();
                                        label = key;
                                        pStart = new Date(rowStart.getFullYear(), 0, 1);
                                        pEnd = new Date(rowStart.getFullYear(), 11, 31);
                                        icon = 'fa-calendar';
                                    } else if (viewMode === 'weekly') {
                                        const d = new Date(Date.UTC(rowStart.getFullYear(), rowStart.getMonth(), rowStart.getDate()));
                                        const dayNum = d.getUTCDay() || 7;
                                        d.setUTCDate(d.getUTCDate() + 4 - dayNum);
                                        const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
                                        const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
                                        key = d.getUTCFullYear() + '-W' + String(weekNo).padStart(2, '0');

                                        const wStart = new Date(rowStart); wStart.setDate(rowStart.getDate() - ((rowStart.getDay() + 6) % 7));
                                        const wEnd = new Date(wStart); wEnd.setDate(wStart.getDate() + 6);
                                        label = `Week ${weekNo} (${wStart.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} - ${wEnd.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })})`;
                                        pStart = wStart;
                                        pEnd = wEnd;
                                        icon = 'fa-layer-group';
                                    }

                                    if (!groups[key]) {
                                        groups[key] = { label, count: 0, start: pStart, end: pEnd, icon };
                                    }
                                    groups[key].count++;
                                });

                                const sortedKeys = Object.keys(groups).sort((a, b) => b.localeCompare(a));

                                if (sortedKeys.length === 0) {
                                    grid.innerHTML = '<div style="grid-column: 1/-1; text-align:center; padding: 40px; color:#64748b;"><i class="fas fa-folder-open" style="font-size: 2rem; display: block; margin-bottom: 15px; opacity: 0.5;"></i>No records found for this view mode.</div>';
                                    return;
                                }

                                sortedKeys.forEach(k => {
                                    const g = groups[k];
                                    const startStr = g.start.toISOString();
                                    const endStr = g.end.toISOString();

                                    const html = `
                                    <div onclick="selectGroup('${k}', '${startStr}', '${endStr}', '${g.label}')" 
                                        style="display: flex; flex-direction: column; padding: 20px; background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; cursor: pointer; transition: all 0.2s; border-left: 4px solid var(--primary-color, #1e3a8a);">
                                        <span style="font-weight: 700; color: #1e293b; font-size: 1rem; margin-bottom: 5px;"><i class="fas ${g.icon}" style="margin-right: 6px; color: var(--primary-color, #1e3a8a); opacity: 0.8;"></i> ${g.label}</span>
                                        <span style="margin-top: 10px; font-size: 0.85rem; color: var(--primary-color, #1e3a8a); font-weight: 600;">${g.count} match(es) <i class="fas fa-arrow-right" style="margin-left: 5px; font-size: 0.7rem;"></i></span>
                                    </div>
                                `;
                                    grid.insertAdjacentHTML('beforeend', html);
                                });
                            }

                            window.selectGroup = function (key, startIso, endIso, label) {
                                activeGroupStart = new Date(startIso);
                                activeGroupEnd = new Date(endIso);

                                document.getElementById('groupsContainer').style.display = 'none';
                                document.getElementById('matchesTablesWrapper').style.display = 'block';

                                document.getElementById('backToOverviewWrap').style.display = 'block';
                                document.getElementById('backToOverviewText').textContent = viewMode.charAt(0).toUpperCase() + viewMode.slice(1) + ' Overview';

                                applyMatchFilters(true);
                            };

                            window.backToOverview = function () {
                                setViewMode(viewMode);
                            };

                            window.clearMatchFilters = function () {
                                document.getElementById('matchSearchInput').value = '';
                                document.getElementById('matchDatePicker').value = '';
                                const typeFilter = document.getElementById('matchTypeFilter');
                                if (typeFilter) typeFilter.value = 'all';
                                if (viewMode !== 'daily') {
                                    setViewMode(viewMode);
                                } else {
                                    applyMatchFilters(true);
                                }
                            };

                            window.applyMatchFilters = function (applyDateFilter) {
                                const q = document.getElementById('matchSearchInput').value.trim().toLowerCase();
                                const typeFilterEl = document.getElementById('matchTypeFilter');
                                const selectedType = typeFilterEl ? typeFilterEl.value : 'all';

                                // If user is just typing in search while in group overview, we just re-render grid
                                if (viewMode !== 'daily' && !activeGroupStart && !applyDateFilter) {
                                    renderGroups();
                                    document.getElementById('matchClearBtn').style.display = (q || selectedType !== 'all') ? 'flex' : 'none';
                                    return;
                                }

                                // Compute date range
                                let pStart = null, pEnd = null;
                                if (viewMode === 'daily') {
                                    const dp = document.getElementById('matchDatePicker').value;
                                    if (dp) {
                                        pStart = new Date(dp + 'T00:00:00');
                                        pEnd = new Date(dp + 'T23:59:59');
                                    }
                                } else if (activeGroupStart && activeGroupEnd) {
                                    pStart = activeGroupStart;
                                    pEnd = activeGroupEnd;
                                }

                                let totalVisible = 0;
                                const sections = ['ongoing', 'upcoming', 'completed'];

                                sections.forEach(sec => {
                                    const rows = document.querySelectorAll('#tbody-' + sec + ' .match-row');
                                    let secVisible = 0;

                                    rows.forEach(row => {
                                        const name = row.dataset.name || '';
                                        const location = row.dataset.location || '';
                                        const rm = row.dataset.rm || '';
                                        const discipline = row.dataset.discipline || '';
                                        const areaSearch = row.dataset.area || '';

                                        const rowStart = toDate(row.dataset.start);
                                        const rowEnd = toDate(row.dataset.end);

                                        const matchType = row.dataset.type || 'regular';
                                        const textMatch = !q || name.includes(q) || location.includes(q) || rm.includes(q) || discipline.includes(q) || areaSearch.includes(q);
                                        const typeMatch = selectedType === 'all' || matchType === selectedType;

                                        let dateMatch = true;
                                        if (pStart && pEnd && rowStart && rowEnd) {
                                            dateMatch = overlaps(rowStart, rowEnd, pStart, pEnd);
                                        }

                                        const show = textMatch && typeMatch && dateMatch;
                                        row.style.display = show ? '' : 'none';
                                        if (show) { secVisible++; totalVisible++; }
                                    });

                                    const countEl = document.getElementById('sec-count-' + sec);
                                    if (countEl) {
                                        const hasFilter = q || (pStart && pEnd) || selectedType !== 'all';
                                        countEl.textContent = hasFilter ? '(' + secVisible + ' shown)' : '';
                                    }

                                    const noDataRow = document.querySelector('#tbody-' + sec + ' .no-data-row');
                                    if (noDataRow) {
                                        noDataRow.style.display = (secVisible === 0 && !(q || (pStart && pEnd) || selectedType !== 'all')) ? '' : 'none';
                                    }

                                    const sectionBox = document.getElementById('box-' + sec);
                                    if (sectionBox) {
                                        if ((q || (pStart && pEnd) || selectedType !== 'all') && secVisible === 0) {
                                            sectionBox.style.display = 'none';
                                        } else {
                                            sectionBox.style.display = '';
                                            // Auto-expand if matches found during filter
                                            if (q || (pStart && pEnd) || selectedType !== 'all') {
                                                const table = document.getElementById('table-' + sec);
                                                const chevron = document.getElementById('chevron-' + sec);
                                                if (table && secVisible > 0) {
                                                    table.classList.add('active');
                                                    if (chevron) chevron.style.transform = 'rotate(180deg)';
                                                }
                                            }
                                        }
                                    }
                                });

                                const hasFilter = !!(q || (pStart && pEnd) || selectedType !== 'all');
                                const allRows = document.querySelectorAll('.match-row');

                                if (allRows.length > 0) {
                                    const allHidden = [...allRows].every(r => r.style.display === 'none');
                                    document.getElementById('matchesNoResults').style.display = (hasFilter && allHidden) ? 'block' : 'none';
                                } else {
                                    document.getElementById('matchesNoResults').style.display = 'none';
                                }

                                document.getElementById('matchClearBtn').style.display = hasFilter ? 'flex' : 'none';
                            };

                            window.toggleMatchSection = function (section) {
                                // Retired - Sections are now scrollable containers
                            };

                            // Init
                            setViewMode('daily'); // Set default to daily mode
                        })();
                    </script>



                    <!-- Create Match Modal -->
                    <div id="createMatchModal" class="modal">
                        <div class="modal-content" style="max-width: 600px;">
                            <h3>Create New Match Schedule</h3>
                            <form method="POST" action="" enctype="multipart/form-data" id="createMatchForm"
                                onsubmit="return validateMatchForm(this, 'create');">
                                <input type="hidden" name="action" value="create_match">


                                <div style="display: grid; gap: 15px;">
                                    <?php if ($is_officer_role): ?>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                            <div
                                                style="background:#fffbeb; border:1px solid #fde68a; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_retroactive" value="1"
                                                        id="createMatchRetroactive"
                                                        onchange="handleMatchCheckboxChange('createMatchRetroactive', 'createMatchLocal')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#d97706;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#92400e;"><i
                                                                class="fas fa-lock" style="margin-right:5px;"></i>Retroactive
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#78350f; margin-top:3px;">If
                                                            checked, only users from your <strong>area</strong> can join, and
                                                            you can select <strong>previous dates</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                            <div
                                                style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_local" value="1" id="createMatchLocal"
                                                        onchange="handleMatchCheckboxChange('createMatchLocal', 'createMatchRetroactive')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#16a34a;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#166534;"><i
                                                                class="fas fa-map-marker-alt"
                                                                style="margin-right:5px;"></i>Local
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#14532d; margin-top:3px;">If
                                                            checked, this match is only visible and applicable to users from
                                                            your <strong>area</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                        </div>
                                        <div style="font-size: 0.75rem; color: #64748b; margin-top: -5px; text-align: center;">
                                            <i class="fas fa-info-circle"></i> If no checkbox is selected, this is considered a
                                            <strong>National/Regular Match</strong>.
                                        </div>
                                    <?php endif; ?>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                            Name</label>
                                        <input type="text" name="match_name" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Start
                                                Date</label>
                                            <input type="date" name="start_date" id="create_start_date" required
                                                min="<?php echo date('Y-m-d'); ?>"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">End
                                                Date</label>
                                            <input type="date" name="end_date" id="create_end_date" required
                                                min="<?php echo date('Y-m-d'); ?>"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                    </div>


                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Serving
                                                RO Limit</label>
                                            <input type="number" name="ro_limit" placeholder="Limit of participants"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Range
                                                Master Name</label>
                                            <div class="rm-selection-wrapper">
                                                <div class="rm-search-box">
                                                    <input type="text" id="create_rm_search" class="rm-search-input"
                                                        placeholder="Search Range Master..." autocomplete="off">
                                                </div>
                                                <div id="create_rm_list" class="rm-list-container">
                                                    <!-- Dynamic items -->
                                                </div>
                                                <input type="hidden" name="rm_name" id="create_rm_name">
                                                <input type="hidden" name="rm_id" id="create_rm_id">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                                Level</label>
                                            <select name="match_level" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                                <option value="" disabled selected>Select Level</option>
                                                <option value="Level 1">1</option>
                                                <option value="Level 2">2</option>
                                                <option value="Level 3">3</option>
                                                <option value="Level 4">4</option>
                                                <option value="Level 5">5</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Discipline</label>
                                            <div class="discipline-container"
                                                style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; max-height: 150px; overflow: auto; background: #fff;">
                                                <?php if (!empty($disciplines)): ?>
                                                    <?php foreach ($disciplines as $discipline): ?>
                                                        <label
                                                            style="display:flex; align-items:center; gap:8px; padding:6px 0; font-size:0.9rem;">
                                                            <input type="checkbox" name="disciplines[]"
                                                                value="<?php echo htmlspecialchars($discipline['name']); ?>">
                                                            <span><?php echo htmlspecialchars($discipline['name']); ?></span>
                                                        </label>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <div style="color:#64748b; font-size:0.85rem;">
                                                        No disciplines available. Please add disciplines in Management.
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-top: 6px;">
                                                You can select multiple disciplines.
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Location</label>
                                        <input type="text" name="location" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Attachments
                                            (Optional PDF/Images)</label>
                                        <input type="file" id="createMatchFileInput" name="attachments[]" multiple
                                            accept=".pdf,image/png,image/jpeg,image/jpg"
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;"
                                            onchange="previewFiles(this, 'createMatchPreview')">
                                        <div id="createMatchPreview"
                                            style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;"></div>
                                    </div>


                                </div>

                                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px;">
                                    <button type="button"
                                        onclick="closeAndClearModal('createMatchModal', 'createMatchPreview', 'createMatchFileInput')"
                                        style="background: none; border: none; color: #64748b; font-weight: 600; cursor: pointer;">Cancel</button>
                                    <button type="submit" class="btn-primary" style="width: auto; padding: 10px 25px;">Save
                                        Schedule</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Edit Match Modal -->
                    <div id="editMatchModal" class="modal">
                        <div class="modal-content" style="max-width: 600px;">
                            <h3>Edit Match Schedule</h3>
                            <form method="POST" enctype="multipart/form-data" id="editMatchForm"
                                onsubmit="return validateMatchForm(this, 'edit');">
                                <input type="hidden" name="action" value="update_match">
                                <input type="hidden" name="match_id" id="edit_match_id">


                                <div style="display: grid; gap: 15px;">
                                    <?php if ($is_officer_role): ?>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                            <div
                                                style="background:#fffbeb; border:1px solid #fde68a; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_retroactive" value="1"
                                                        id="editMatchRetroactive"
                                                        onchange="handleMatchCheckboxChange('editMatchRetroactive', 'editMatchLocal')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#d97706;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#92400e;"><i
                                                                class="fas fa-lock" style="margin-right:5px;"></i>Retroactive
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#78350f; margin-top:3px;">If
                                                            checked, only users from your <strong>area</strong> can join, and
                                                            you can select <strong>previous dates</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                            <div
                                                style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_local" value="1" id="editMatchLocal"
                                                        onchange="handleMatchCheckboxChange('editMatchLocal', 'editMatchRetroactive')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#16a34a;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#166534;"><i
                                                                class="fas fa-map-marker-alt"
                                                                style="margin-right:5px;"></i>Local
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#14532d; margin-top:3px;">If
                                                            checked, this match is only visible and applicable to users from
                                                            your <strong>area</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                        </div>
                                        <div style="font-size: 0.75rem; color: #64748b; margin-top: -5px; text-align: center;">
                                            <i class="fas fa-info-circle"></i> If no checkbox is selected, this is considered a
                                            <strong>National/Regular Match</strong>.
                                        </div>
                                    <?php endif; ?>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                            Name</label>
                                        <input type="text" name="match_name" id="edit_match_name" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Start
                                                Date</label>
                                            <input type="date" name="start_date" id="edit_start_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">End
                                                Date</label>
                                            <input type="date" name="end_date" id="edit_end_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                    </div>


                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Serving
                                                RO Limit</label>
                                            <input type="number" name="ro_limit" id="edit_ro_limit"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Range
                                                Master Name</label>
                                            <div class="rm-selection-wrapper">
                                                <div class="rm-search-box">
                                                    <input type="text" id="edit_rm_search" class="rm-search-input"
                                                        placeholder="Search Range Master..." autocomplete="off">
                                                </div>
                                                <div id="edit_rm_list" class="rm-list-container">
                                                    <!-- Dynamic items -->
                                                </div>
                                                <input type="hidden" name="rm_name" id="edit_rm_name">
                                                <input type="hidden" name="rm_id" id="edit_rm_id">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                                Level</label>
                                            <select name="match_level" id="edit_match_level" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                                <option value="" disabled selected>Select Level</option>
                                                <option value="Level 1">1</option>
                                                <option value="Level 2">2</option>
                                                <option value="Level 3">3</option>
                                                <option value="Level 4">4</option>
                                                <option value="Level 5">5</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Discipline</label>
                                            <div class="discipline-container"
                                                style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; max-height: 150px; overflow: auto; background: #fff;">
                                                <?php foreach ($disciplines as $discipline): ?>
                                                    <label
                                                        style="display:flex; align-items:center; gap:8px; padding:6px 0; font-size:0.9rem;">
                                                        <input type="checkbox" name="disciplines[]"
                                                            value="<?php echo htmlspecialchars($discipline['name']); ?>">
                                                        <span><?php echo htmlspecialchars($discipline['name']); ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-top: 6px;">
                                                You can select multiple disciplines.
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Location</label>
                                        <input type="text" name="location" id="edit_location" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Add
                                            Attachments (Optional PDF/Images)</label>
                                        <input type="file" id="editMatchFileInput" name="attachments[]" multiple
                                            accept=".pdf,image/png,image/jpeg,image/jpg"
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;"
                                            onchange="previewFiles(this, 'editMatchPreview')">
                                        <div id="editMatchPreview"
                                            style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;"></div>
                                        <div id="existingAttachments"
                                            style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; border-top: 1px solid #eee; padding-top: 10px;">
                                        </div>
                                        <div style="font-size: 0.75rem; color: #64748b; margin-top: 6px;">
                                            Newly uploaded files will be added to the match.
                                        </div>
                                    </div>
                                </div>

                                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px;">
                                    <button type="button"
                                        onclick="closeAndClearModal('editMatchModal', 'editMatchPreview', 'editMatchFileInput')"
                                        style="background: none; border: none; color: #64748b; font-weight: 600; cursor: pointer;">Cancel</button>
                                    <button type="submit" class="btn-primary"
                                        style="width: auto; padding: 10px 25px;">Update
                                        Schedule</button>
                                </div>
                            </form>
                        </div>
                    </div>

                <?php elseif (isset($_GET['view']) && $_GET['view'] == 'participants'): ?>
                    <?php
                    $match_id = $_GET['match_id'] ?? null;
                    if ($match_id) {
                        try {
                            // Fetch match details
                            $stmt = $pdo->prepare("SELECT * FROM match_schedules WHERE id = ?");
                            $stmt->execute([$match_id]);
                            $match = $stmt->fetch();
                            $isMatchEnded = false;
                            $isEditAllowed = false;
                            $editAvailableDate = null;
                            if ($match) {
                                // --- Area Restriction Check for AC/AAC ---
                                if (!$is_admin && $is_officer_role) {
                                    $matchArea = $match['creator_area'] ?? '';
                                    if ((($match['is_retroactive'] == 1 || $match['is_local'] == 1)) && $matchArea !== $userArea) {
                                        echo "<div class='content-box' style='padding:40px; text-align:center; color:#ef4444;'>
                                                <i class='fas fa-lock' style='font-size:3rem; margin-bottom:15px; opacity:0.5;'></i>
                                                <h3 style='margin:0;'>Access Restricted</h3>
                                                <p style='margin-top:10px; color:#64748b; font-weight:500;'>You do not have permission to view participants for this retroactive/local match from another area.</p>
                                                <div style='margin-top:20px;'><a href='matches.php' class='btn-primary' style='display:inline-block; width:auto; padding:8px 25px;'>Back to Matches</a></div>
                                              </div>";
                                        $match = null; // Prevent showing the rest
                                    }
                                }

                                if ($match) {
                                    $today = date('Y-m-d');
                                    $isMatchEnded = ($today > $match['end_date']);
                                    // Edit button only unlocks after 7 full days from end_date (on the 8th day)
                                    $endDt = new DateTime($match['end_date']);
                                    $editDt = clone $endDt;
                                    $editDt->modify('+8 days');
                                    $editAvailableDate = $editDt->format('F d, Y');
                                    $isEditAllowed = ($today >= $editDt->format('Y-m-d'));
                                }
                            }

                            // Fetch attachments
                            $stmtAtt = $pdo->prepare("SELECT file_name, file_path FROM match_attachments WHERE match_id = ?");
                            $stmtAtt->execute([$match_id]);
                            $attachments = $stmtAtt->fetchAll(PDO::FETCH_ASSOC);

                            // Ensure assignment tables exist to avoid crashing the participant query if one is missing
                            $assignment_types = ['states', 'chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master', 'deputy_range_master', 'match_director'];
                            foreach ($assignment_types as $type) {
                                $tableName = ($type === 'states') ? "match_states_assignments" : "match_{$type}_assignments";
                                $uniqueKeyName = "unique_match_user_{$type}";
                                $officerCol = ($type === 'states') ? "`states_number` VARCHAR(100) NOT NULL, `lro_name` VARCHAR(255) NULL," : "`officer_name` VARCHAR(255) NOT NULL,";

                                $pdo->exec("CREATE TABLE IF NOT EXISTS `$tableName` (
                                     `id` INT AUTO_INCREMENT PRIMARY KEY,
                                     `match_id` INT NOT NULL,
                                     $officerCol
                                     `role` VARCHAR(100) NULL,
                                     `rm_signature` VARCHAR(255) NULL,
                                     `submitted_by` INT NOT NULL,
                                     `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                     UNIQUE KEY `$uniqueKeyName` (`match_id`, `submitted_by`)
                                 )");
                            }

                            // Fetch participants
                            $stmt = $pdo->prepare("
                                 SELECT ms.status, ms.created_at, ms.reviewed_at, ms.is_extended, ms.is_rm_enabled, u.id as user_id, u.first_name, u.last_name, u.nroi_id, u.role, u.rank,
                                 u.match_assignment as profile_match_assignment, u.match_role as profile_match_role,
                                 COALESCE(
                                     (SELECT 'states' FROM match_states_assignments msa WHERE msa.match_id = ms.match_id AND msa.submitted_by = u.id LIMIT 1),
                                     (SELECT 'chrono' FROM match_chrono_assignments mca WHERE mca.match_id = ms.match_id AND mca.submitted_by = u.id LIMIT 1),
                                     (SELECT 'stats' FROM match_stats_assignments msa3 WHERE msa3.match_id = ms.match_id AND msa3.submitted_by = u.id LIMIT 1),
                                     (SELECT 'equipment_check' FROM match_equipment_check_assignments meca WHERE meca.match_id = ms.match_id AND meca.submitted_by = u.id LIMIT 1),
                                     (SELECT 'quarter_master' FROM match_quarter_master_assignments mqma WHERE mqma.match_id = ms.match_id AND mqma.submitted_by = u.id LIMIT 1),
                                     (SELECT 'range_master' FROM match_range_master_assignments mrma WHERE mrma.match_id = ms.match_id AND mrma.submitted_by = u.id LIMIT 1),
                                     (SELECT 'deputy_range_master' FROM match_deputy_range_master_assignments mdrma WHERE mdrma.match_id = ms.match_id AND mdrma.submitted_by = u.id LIMIT 1),
                                     (SELECT 'match_director' FROM match_match_director_assignments mmda WHERE mmda.match_id = ms.match_id AND mmda.submitted_by = u.id LIMIT 1)
                                 ) as db_assignment_type,
                                 COALESCE(
                                     (SELECT role FROM match_states_assignments msa WHERE msa.match_id = ms.match_id AND msa.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_chrono_assignments mca WHERE mca.match_id = ms.match_id AND mca.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_stats_assignments msa3 WHERE msa3.match_id = ms.match_id AND msa3.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_equipment_check_assignments meca WHERE meca.match_id = ms.match_id AND meca.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_quarter_master_assignments mqma WHERE mqma.match_id = ms.match_id AND mqma.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_range_master_assignments mrma WHERE mrma.match_id = ms.match_id AND mrma.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_deputy_range_master_assignments mdrma WHERE mdrma.match_id = ms.match_id AND mdrma.submitted_by = u.id LIMIT 1),
                                     (SELECT role FROM match_match_director_assignments mmda WHERE mmda.match_id = ms.match_id AND mmda.submitted_by = u.id LIMIT 1)
                                 ) as db_role,
                                 (SELECT states_number FROM match_states_assignments msa WHERE msa.match_id = ms.match_id AND msa.submitted_by = u.id LIMIT 1) as db_stage_number,
                                 (SELECT lro_name FROM match_states_assignments msa WHERE msa.match_id = ms.match_id AND msa.submitted_by = u.id LIMIT 1) as db_lro_name,
                                 COALESCE(
                                     (SELECT officer_name FROM match_chrono_assignments mca WHERE mca.match_id = ms.match_id AND mca.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_stats_assignments msa3 WHERE msa3.match_id = ms.match_id AND msa3.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_equipment_check_assignments meca WHERE meca.match_id = ms.match_id AND meca.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_quarter_master_assignments mqma WHERE mqma.match_id = ms.match_id AND mqma.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_range_master_assignments mrma WHERE mrma.match_id = ms.match_id AND mrma.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_deputy_range_master_assignments mdrma WHERE mdrma.match_id = ms.match_id AND mdrma.submitted_by = u.id LIMIT 1),
                                     (SELECT officer_name FROM match_match_director_assignments mmda WHERE mmda.match_id = ms.match_id AND mmda.submitted_by = u.id LIMIT 1)
                                 ) as db_officer_name,
                                 (SELECT COUNT(*) FROM match_points mp WHERE mp.user_id = u.id AND mp.match_id = ms.match_id) as has_points,
                                 COALESCE((SELECT SUM(mp2.points) FROM match_points mp2 WHERE mp2.user_id = u.id AND mp2.match_id = ms.match_id), 0) as match_points,
                                 (SELECT rm_signature FROM match_points mp3 WHERE mp3.user_id = u.id AND mp3.match_id = ms.match_id LIMIT 1) as rm_signature
                                 FROM match_significations ms
                                 JOIN users u ON ms.user_id = u.id
                                 WHERE ms.match_id = ? AND ms.status = 'approved'
                                 ORDER BY u.last_name ASC
                             ");
                            $stmt->execute([$match_id]);
                            $participants = $stmt->fetchAll();
                        } catch (Exception $e) {
                            $participants = [];
                            // Do not $match = null here; allows showing "0 participants" instead of "Match not found"
                        }
                    }
                    ?>

                    <?php if ($match): ?>
                        <div style="margin-bottom: 20px;">
                            <a href="matches.php"
                                style="display: inline-flex; align-items: center; gap: 8px; color: #64748b; text-decoration: none; font-weight: 600;">
                                <i class="fas fa-arrow-left"></i> Back to Matches
                            </a>
                        </div>

                        <div class="content-box">
                            <div class="table-header">
                                <h3>Range Officers for <?php echo htmlspecialchars($match['match_name']); ?></h3>
                            </div>

                            <?php if ($isMatchEnded): ?>
                                <div
                                    style="margin: 0 0 18px 0; padding: 14px 18px; border-radius: 10px; display: flex; align-items: center; gap: 12px;
                                    <?php echo $isEditAllowed ? 'background:#dcfce7; border:1.5px solid #86efac; color:#166534;' : 'background:#fff1ee; border:1.5px solid #f97316; color:#9a3412;'; ?>">
                                    <i class="fas <?php echo $isEditAllowed ? 'fa-check-circle' : 'fa-clock'; ?>"
                                        style="font-size:1rem; flex-shrink:0;"></i>
                                    <div style="font-size:0.9rem; font-weight:600;">
                                        <?php if ($isEditAllowed): ?>
                                            <strong>Editing is now available.</strong> Point card editing for incomplete users is
                                            currently enabled.
                                        <?php else: ?>
                                            Editing point cards of users only works after 7 days when the match ends. Available on
                                            <strong><?php echo $editAvailableDate; ?></strong>.
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if (empty($participants)): ?>
                                <p style="color: #64748b; font-style: italic; padding: 20px;">No participants found for this match.
                                </p>
                            <?php else: ?>
                                <table class="modern-table">
                                    <thead>
                                        <tr>
                                            <th>NROI ID</th>
                                            <th>Name</th>
                                            <th>Rank</th>
                                            <th>Dates</th>
                                            <th>Points</th>
                                            <th>Status</th>
                                            <th style="text-align: right;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($participants as $p):
                                            $isSigValid = ($p['has_points'] > 0 && !empty($p['rm_signature']) && $p['rm_signature'] !== 'DEMERIT' && file_exists('../' . $p['rm_signature']));
                                            $isIncomplete = !$isSigValid;
                                            ?>
                                            <tr onclick="window.location.href='member_points_summary.php?user_id=<?php echo $p['user_id']; ?>'"
                                                class="<?php echo $isIncomplete ? 'row-incomplete' : ''; ?>"
                                                style="cursor: pointer; transition: all 0.2s;"
                                                onmouseover="<?php echo !$isIncomplete ? "this.style.backgroundColor='#f8fafc'" : ""; ?>"
                                                onmouseout="<?php echo !$isIncomplete ? "this.style.backgroundColor='transparent'" : ""; ?>">
                                                <td><?php echo htmlspecialchars($p['nroi_id']); ?></td>
                                                <td style="font-weight: 600; color: #1e3a8a;">
                                                    <?php echo htmlspecialchars($p['last_name'] . ', ' . $p['first_name']); ?>
                                                </td>
                                                <td>
                                                    <div style="display: flex; flex-direction: column; gap: 4px;">
                                                        <span class="role-badge"
                                                            style="background: #f1f5f9; color: #64748b;"><?php echo (!empty($p['role']) && $p['role'] !== 'member') ? htmlspecialchars($p['role']) : 'R.O'; ?></span>
                                                        <?php
                                                        $displayRoleP = (!empty($p['role']) && $p['role'] !== 'member') ? $p['role'] : 'R.O';
                                                        if ($displayRoleP !== 'AC' && $displayRoleP !== 'AAC'):
                                                            ?>
                                                            <span style="font-size: 0.7rem; color: #64748b; font-weight: 500;">
                                                                <i class="fas fa-info-circle" style="font-size: 0.65rem; opacity: 0.5;"></i>
                                                                Status:
                                                                <?php echo htmlspecialchars(($p['rank'] === 'Regular' || $p['rank'] === 'OJT') ? $p['rank'] : 'Regular'); ?>
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td style="font-size: 0.85rem; color: #64748b; line-height: 1.4;">
                                                    <div><strong style="color: #475569;">Signified:</strong>
                                                        <?php echo date('M d, Y h:i A', strtotime($p['created_at'])); ?></div>
                                                    <div><strong style="color: #16a34a;">Approved:</strong>
                                                        <?php echo $p['reviewed_at'] ? date('M d, Y h:i A', strtotime($p['reviewed_at'])) : '---'; ?>
                                                    </div>
                                                </td>
                                                <td style="font-weight: 700; color: #1e3a8a; text-align: center;">
                                                    <?php echo $isSigValid ? number_format($p['match_points'], 2) : '—'; ?>
                                                </td>
                                                <td>
                                                    <?php if ($isSigValid): ?>
                                                        <span
                                                            style="background: #dcfce7; color: #166534; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600;">Served</span>
                                                    <?php else: ?>
                                                        <span
                                                            style="background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600;">Incomplete</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="padding: 16px; text-align: right; white-space: nowrap;"
                                                    onclick="event.stopPropagation()">
                                                    <?php if ($isMatchEnded && !$isSigValid): ?>
                                                        <?php if ($p['is_extended'] == 1): ?>
                                                            <button onclick="terminateReturnedPointCard(
                                                                 '<?php echo $p['user_id']; ?>', 
                                                                 '<?php echo $match_id; ?>', 
                                                                 '<?php echo addslashes($p['first_name'] . ' ' . $p['last_name']); ?>'
                                                             )"
                                                                style="background: #ef4444; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;"
                                                                onmouseover="this.style.background='#dc2626'"
                                                                onmouseout="this.style.background='#ef4444'">
                                                                <i class="fas fa-times-circle"></i> Terminate Returned Point Card
                                                            </button>
                                                        <?php elseif ($p['is_rm_enabled'] == 1): ?>
                                                            <button onclick="terminateRMSigning(
                                                                 '<?php echo $p['user_id']; ?>', 
                                                                 '<?php echo (int) $match['id']; ?>', 
                                                                 '<?php echo addslashes($p['first_name'] . ' ' . $p['last_name']); ?>'
                                                             )"
                                                                style="background: #ef4444; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;"
                                                                onmouseover="this.style.background='#dc2626'"
                                                                onmouseout="this.style.background='#ef4444'">
                                                                <i class="fas fa-user-shield"></i> Terminate RM Signing
                                                            </button>
                                                        <?php else: ?>
                                                            <?php
                                                            require_once '../config/points_config.php';
                                                            $calcPts = nroi_compute_match_points($match['match_level'] ?? '', $match['range_master'] ?? '');
                                                            ?>
                                                            <?php
                                                            $currentType = $p['db_assignment_type'] ?: $p['profile_match_assignment'];
                                                            $currentRole = $p['db_role'] ?: $p['profile_match_role'];
                                                            ?>
                                                            <?php if ($isEditAllowed): ?>
                                                                <button onclick="openPointCardEdit(
                                                                 <?php echo $p['user_id']; ?>,
                                                                 '<?php echo htmlspecialchars(addslashes($p['last_name'] . ', ' . $p['first_name'])); ?>',
                                                                 <?php echo (int) $match['id']; ?>,
                                                                 '<?php echo htmlspecialchars(addslashes($match['match_name'] ?? '')); ?>',
                                                                 <?php echo (int) $calcPts; ?>,
                                                                 '<?php echo htmlspecialchars(addslashes($match['match_level'] ?? '')); ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($match['range_master'] ?? '')); ?>',
                                                                 <?php echo (int) $p['is_rm_enabled']; ?>,
                                                                 '<?php echo $match['rm_id'] ?? ''; ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($currentType ?? '')); ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($currentRole ?? '')); ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($p['db_stage_number'] ?? '')); ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($p['db_lro_name'] ?? '')); ?>',
                                                                 '<?php echo htmlspecialchars(addslashes($p['db_officer_name'] ?? '')); ?>'
                                                             )"
                                                                    style="background: #2563eb; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;"
                                                                    onmouseover="this.style.background='#1d4ed8'"
                                                                    onmouseout="this.style.background='#2563eb'">
                                                                    <i class="fas fa-edit"></i> Edit
                                                                </button>
                                                            <?php else: ?>
                                                                <span title="Available on <?php echo $editAvailableDate; ?>"
                                                                    style="display:inline-flex; align-items:center; gap:5px; background:#f1f5f9; color:#94a3b8; padding:6px 12px; border-radius:6px; font-size:13px; font-weight:600; cursor:default;">
                                                                    <i class="fas fa-lock"></i> Locked
                                                                </span>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </td>
                                            </tr> <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div style="padding: 20px; color: #ef4444;">Match not found. <a href="matches.php">Go back</a></div>
                    <?php endif; ?>

                <?php elseif (!isset($_GET['view']) || $_GET['view'] == 'points'): ?>
                    <?php
                    // Fetch users with their total points
                    $area = $_SESSION['area'] ?? '';
                    $stmt = $pdo->prepare("
                SELECT u.*, COALESCE(SUM(mp.points), 0) as total_points 
                FROM users u 
                LEFT JOIN match_points mp ON u.id = mp.user_id 
                WHERE u.area = ? AND u.status = 'approved' 
                GROUP BY u.id 
                ORDER BY total_points DESC, last_name ASC
            ");
                    $stmt->execute([$area]);
                    $areaUsers = $stmt->fetchAll();
                    ?>
                    <div class="content-box">
                        <div class="table-header">
                            <h3>User Match Points</h3>
                            <div style="width: 300px;">
                                <input type="text" placeholder="Search user..."
                                    style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                            </div>
                        </div>

                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>NROI ID</th>
                                    <th>Name</th>
                                    <th>Rank</th>
                                    <th>Total Points</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($areaUsers)): ?>
                                    <tr>
                                        <td colspan="5" style="text-align:center; padding: 20px;">No users found in your area.
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($areaUsers as $u): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($u['nroi_id'] ?? 'N/A'); ?></td>
                                            <td style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($u['last_name'] . ', ' . $u['first_name']); ?>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 4px;">
                                                    <span class="role-badge"
                                                        style="background: #eff6ff; color: #1e40af;"><?php echo (!empty($u['role']) && $u['role'] !== 'member') ? htmlspecialchars($u['role']) : 'R.O'; ?></span>
                                                    <?php
                                                    $displayRoleU = (!empty($u['role']) && $u['role'] !== 'member') ? $u['role'] : 'R.O';
                                                    if ($displayRoleU !== 'AC' && $displayRoleU !== 'AAC'):
                                                        ?>
                                                        <span style="font-size: 0.7rem; color: #64748b; font-weight: 500;">
                                                            <i class="fas fa-info-circle" style="font-size: 0.65rem; opacity: 0.5;"></i>
                                                            Status:
                                                            <?php echo htmlspecialchars(($u['rank'] === 'Regular' || $u['rank'] === 'OJT') ? $u['rank'] : 'Regular'); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td style="font-weight: 700; color: #1e3a8a;">
                                                <?php echo number_format($u['total_points'], 2); ?>
                                            </td>
                                            <td>
                                                <a href="matches.php?view=history&user_id=<?php echo $u['id']; ?>"
                                                    class="btn-secondary"
                                                    style="padding: 5px 10px; font-size: 0.8rem; text-decoration: none; display: inline-block;">
                                                    View History
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php elseif (isset($_GET['view']) && $_GET['view'] == 'history'): ?>
                <?php
                $userId = $_GET['user_id'] ?? 0;
                $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $user = $stmt->fetch();

                if (!$user) {
                    echo "<div class='content-box'><p>User not found.</p></div>";
                } else {
                    $stmt = $pdo->prepare("
                    SELECT mp.*, m.match_name, m.match_level, m.start_date, m.range_master as scheduled_rm
                    FROM match_points mp
                    JOIN match_schedules m ON mp.match_id = m.id
                    WHERE mp.user_id = ?
                    ORDER BY m.start_date DESC
                ");
                    $stmt->execute([$userId]);
                    $history = $stmt->fetchAll();
                    ?>
                    <div class="content-box">
                        <div class="table-header">
                            <div style="display: flex; align-items: center; gap: 15px;">
                                <a href="matches.php?view=points" class="btn-secondary" style="padding: 8px 12px;"><i
                                        class="fas fa-arrow-left"></i></a>
                                <div>
                                    <h3 style="margin: 0;">
                                        <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>
                                    </h3>
                                    <p style="margin: 0; font-size: 0.85rem; color: #64748b;">Member Match History & Points</p>
                                </div>
                            </div>
                        </div>

                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Match Name</th>
                                    <th>Date</th>
                                    <th>Level</th>
                                    <th>Points</th>
                                    <th>RM Name and Signature</th>
                                    <th>Submitted On</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($history)): ?>
                                    <tr>
                                        <td colspan="6" style="text-align: center; padding: 30px; color: #64748b;">No match points
                                            recorded yet.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($history as $h): ?>
                                        <tr>
                                            <td style="font-weight: 600; color: #1e3a8a;">
                                                <?php echo htmlspecialchars($h['match_name']); ?>
                                            </td>
                                            <td><?php echo date('M d, Y', strtotime($h['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/', '', $h['match_level']); ?>
                                                </div>
                                            </td>
                                            <td style="font-weight: 700; color: #16a34a; font-size: 1.1rem;">
                                                +<?php echo number_format($h['points'], 2); ?></td>
                                            <td>
                                                <?php if (!empty($h['rm_signature'])): ?>
                                                    <div
                                                        style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 4px; padding: 5px; width: 140px; text-align: center;">
                                                        <img src="../<?php echo htmlspecialchars($h['rm_signature']); ?>"
                                                            style="width: 100%; height: auto; display: block; margin-bottom: 5px;"
                                                            alt="RM Signature"
                                                            onerror="this.parentElement.innerHTML='<span style=\'font-size:10px;color:#ef4444\'>Image Hidden/Deleted</span>'">
                                                        <div
                                                            style="font-size: 0.8rem; font-weight: 700; color: #1e293b; border-top: 1px solid #e2e8f0; padding-top: 2px;">
                                                            <?php echo htmlspecialchars($h['scheduled_rm'] ?? 'Range Master'); ?>
                                                        </div>
                                                        <div style="font-size: 0.75rem; color: #64748b; line-height: 1.2;">
                                                            <?php echo date('M d, Y', strtotime($h['created_at'])); ?><br>
                                                            <?php echo date('h:i A', strtotime($h['created_at'])); ?>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <span style="color: #94a3b8; font-style: italic; font-size: 0.8rem;">No signature</span>
                                                <?php endif; ?>
                                            </td>
                                            <td style="font-size: 0.8rem; color: #64748b;">
                                                <?php echo date('M d, Y h:i A', strtotime($h['created_at'])); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php
                }
                ?>
            <?php elseif (isset($_GET['view']) && $_GET['view'] == 'schedule'): ?>
                <?php
                try {
                    // The disciplines and rmUsersList are now fetched at the top of the file.
                    // $stmtDisc = $pdo->query("SELECT * FROM disciplines ORDER BY name ASC");
                    // $disciplines = $stmtDisc->fetchAll(PDO::FETCH_ASSOC);
            
                    // Fetch approved RM users for the Range Master Name field
                    // $stmtRM = $pdo->query("SELECT first_name, last_name FROM users WHERE role = 'RM' AND status = 'approved' ORDER BY last_name ASC");
                    // $rm_users = $stmtRM->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e) {
                    // $disciplines = []; // Already handled by global fetch
                    // $rm_users = []; // Already handled by global fetch
                }

                if (isset($error_message)) {
                    echo "<script>alert('Action failed: " . $error_message . "');</script>";
                }
                ?>

                <?php if (isset($_GET['success'])): ?>
                    <div class="success-banner"
                        style="background: #10b981; color: white; padding: 12px 20px; border-radius: 8px; margin: 20px; display: flex; justify-content: space-between; align-items: center; transition: opacity 0.5s ease;">
                        <span>
                            <i class="fas fa-check-circle"></i>
                            <?php
                            if ($_GET['success'] === 'created')
                                echo 'Match created successfully!';
                            elseif ($_GET['success'] === 'updated')
                                echo 'Match updated successfully!';
                            elseif ($_GET['success'] === 'deleted')
                                echo 'Match deleted successfully!';
                            ?>
                        </span>
                        <button onclick="this.parentElement.remove()"
                            style="background: none; border: none; color: white; cursor: pointer; font-size: 1.2rem;">&times;</button>
                    </div>
                    <script>                if (window.history.replaceState) {
                            const url = new URL(window.location.href);
                            url.searchParams.delete('success');
                            window.history.replaceState(null, null, url.pathname + url.search);
                        }
                    </script>
                <?php endif; ?>

                // Fetch Matches
                $userArea = $_SESSION['area'] ?? '';
                if ($is_admin) {
                $stmt = $pdo->query("SELECT *, (SELECT COUNT(*) FROM match_attachments ma WHERE ma.match_id = ms.id) as
                attachment_count FROM match_schedules ms ORDER BY start_date ASC");
                } else {
                $stmt = $pdo->prepare("SELECT *, (SELECT COUNT(*) FROM match_attachments ma WHERE ma.match_id = ms.id) as
                attachment_count FROM match_schedules ms WHERE ( (is_retroactive = 0 AND is_local = 0) OR creator_area = ? )
                ORDER BY start_date ASC");
                $stmt->execute([$userArea]);
                }
                $all_matches_raw = $stmt->fetchAll();

                // Fetch attachments for all these matches to have detail available
                $ids = array_column($all_matches_raw, 'id');
                $attachmentsMap = [];
                if (!empty($ids)) {
                $in = str_repeat('?,', count($ids) - 1) . '?';
                $stmtAtt = $pdo->prepare("SELECT * FROM match_attachments WHERE match_id IN ($in)");
                $stmtAtt->execute($ids);
                $allAtts = $stmtAtt->fetchAll(PDO::FETCH_ASSOC);
                foreach ($allAtts as $att) {
                $attachmentsMap[$att['match_id']][] = $att;
                }
                }

                $ongoing = [];
                $upcoming = [];
                $completed = [];
                $today = date('Y-m-d');

                foreach ($all_matches_raw as $m) {
                $m['attachments'] = $attachmentsMap[$m['id']] ?? [];
                if ($m['end_date'] < $today) { $completed[]=$m; } elseif ($m['start_date']> $today) {
                    $upcoming[] = $m;
                    } else {
                    $ongoing[] = $m;
                    }
                    }
                    ?>

                    <div style="display: flex; justify-content: flex-end; margin-bottom: 15px;">
                        <button class="btn-primary" style="width: auto; padding: 10px 25px;"
                            onclick="if(typeof selectedMatchFiles !== 'undefined') selectedMatchFiles['createMatchPreview'] = []; document.getElementById('createMatchModalSchedule').classList.add('active')">
                            <i class="fas fa-plus"></i> Create Match
                        </button>
                    </div>
                    <div class="content-box">
                        <div class="table-header">
                            <h3>Scheduled Matches</h3>
                        </div>

                        <!-- Ongoing Matches -->
                        <h4
                            style="color: #16a34a; margin: 20px 0 10px 0; border-bottom: 2px solid #dcfce7; padding-bottom: 5px;">
                            <i class="fas fa-play-circle"></i> Ongoing Matches
                        </h4>
                        <?php if (empty($ongoing)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No ongoing matches.</p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Level</th>
                                        <th>Dates</th>
                                        <th>Location</th>
                                        <th>Discipline</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($ongoing as $m): ?>
                                        <tr class="match-row" data-id="<?php echo $m['id']; ?>"
                                            data-name="<?php echo strtolower(htmlspecialchars($m['match_name'])); ?>"
                                            data-location="<?php echo strtolower(htmlspecialchars($m['location'])); ?>"
                                            onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'"
                                            style="cursor: pointer;">
                                            <td style="font-weight: 700; color: #1e3a8a;">
                                                <?php echo htmlspecialchars($m['match_name']); ?>
                                            </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/', '', $m['match_level']); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['location']); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['range_master']); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                    <?php if (!empty($m['attachments'])): ?>
                                                        <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                            onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                            title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                    <?php endif; ?>
                                                    <button class="icon-btn btn-edit"
                                                        onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                        title="Edit"><i class="fas fa-pen"></i></button>
                                                    <button class="icon-btn btn-reject"
                                                        onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                        title="Delete"><i class="fas fa-trash"></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Upcoming Matches -->
                        <h4
                            style="color: #ea580c; margin: 20px 0 10px 0; border-bottom: 2px solid #ffedd5; padding-bottom: 5px;">
                            <i class="fas fa-calendar-day"></i> Upcoming Matches
                        </h4>
                        <?php if (empty($upcoming)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No upcoming matches.</p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Level</th>
                                        <th>Dates</th>
                                        <th>Location</th>
                                        <th>Discipline</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($upcoming as $m): ?>
                                        <tr class="match-row" data-id="<?php echo $m['id']; ?>"
                                            data-name="<?php echo strtolower(htmlspecialchars($m['match_name'])); ?>"
                                            data-location="<?php echo strtolower(htmlspecialchars($m['location'])); ?>"
                                            onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'"
                                            style="cursor: pointer;">
                                            <td style="font-weight: 700; color: #1e3a8a;">
                                                <?php echo htmlspecialchars($m['match_name']); ?>
                                            </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/', '', $m['match_level']); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['location']); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['range_master']); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                    <?php if (!empty($m['attachments'])): ?>
                                                        <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                            onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                            title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                    <?php endif; ?>
                                                    <button class="icon-btn btn-edit"
                                                        onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                        title="Edit"><i class="fas fa-pen"></i></button>
                                                    <button class="icon-btn btn-reject"
                                                        onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                        title="Delete"><i class="fas fa-trash"></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Completed Matches -->
                        <h4
                            style="color: #64748b; margin: 20px 0 10px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 5px;">
                            <i class="fas fa-check-circle"></i> Completed Matches
                        </h4>
                        <?php if (empty($completed)): ?>
                            <p style="color: #64748b; font-style: italic;">No completed matches.</p>
                        <?php else: ?>
                            <table class="modern-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Level</th>
                                        <th>Dates</th>
                                        <th>Location</th>
                                        <th>Discipline</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($completed as $m): ?>
                                        <tr class="match-row" data-id="<?php echo $m['id']; ?>"
                                            data-name="<?php echo strtolower(htmlspecialchars($m['match_name'])); ?>"
                                            data-location="<?php echo strtolower(htmlspecialchars($m['location'])); ?>"
                                            style="opacity: 0.7; cursor: pointer;"
                                            onclick="window.location.href='matches.php?view=participants&match_id=<?php echo $m['id']; ?>'">
                                            <td style="font-weight: 600;">
                                                <?php echo htmlspecialchars($m['match_name']); ?>
                                            </td>
                                            <td><span class="role-badge" style="background: #f1f5f9; color: #64748b;">
                                                    <?php echo preg_replace('/\D/', '', $m['match_level']); ?>
                                                </span></td>
                                            <td>
                                                <?php echo date('M d', strtotime($m['start_date'])) . ' - ' . date('M d, Y', strtotime($m['end_date'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['location']); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($m['range_master']); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <div class="action-btns" style="display:flex;gap:5px;justify-content:center;">
                                                    <?php if (!empty($m['attachments'])): ?>
                                                        <button class="icon-btn" style="background:#0ea5e9; color:white;"
                                                            onclick="event.stopPropagation(); showMatchAttachments(<?php echo htmlspecialchars(json_encode($m['attachments'])); ?>)"
                                                            title="View Attachments"><i class="fas fa-paperclip"></i></button>
                                                    <?php endif; ?>
                                                    <button class="icon-btn btn-edit"
                                                        onclick='event.stopPropagation(); openEditMatch(<?php echo json_encode($m); ?>)'
                                                        title="Edit"><i class="fas fa-pen"></i></button>
                                                    <button class="icon-btn btn-reject"
                                                        onclick="event.stopPropagation(); deleteMatch(<?php echo $m['id']; ?>)"
                                                        title="Delete"><i class="fas fa-trash"></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>

                    <!-- RM Names Datalist -->
                    <datalist id="rm_names">
                        <?php foreach ($rm_users as $rm): ?>
                            <option
                                value="<?php echo htmlspecialchars(capitalizeWords($rm['last_name'] . ', ' . $rm['first_name'])); ?>">
                            <?php endforeach; ?>
                    </datalist>

                    <!-- Create Match Modal -->
                    <div id="createMatchModalSchedule" class="modal">
                        <div class="modal-content" style="max-width: 600px;">
                            <h3>Create New Match Schedule</h3>
                            <form method="POST" action="" id="createMatchFormSchedule"
                                onsubmit="return validateMatchForm(this, 'create');">
                                <input type="hidden" name="action" value="create_match">

                                <div style="display: grid; gap: 15px;">
                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                            Name</label>
                                        <input type="text" name="match_name" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Start
                                                Date</label>
                                            <input type="date" name="start_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">End
                                                Date</label>
                                            <input type="date" name="end_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Serving
                                                RO Limit</label>
                                            <input type="number" name="ro_limit" placeholder="Limit of participants"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Range
                                                Master Name</label>
                                            <div class="rm-selection-wrapper">
                                                <div class="rm-search-box">
                                                    <input type="text" id="create_rm_search_schedule"
                                                        class="rm-search-input" placeholder="Search Range Master..."
                                                        autocomplete="off">
                                                </div>
                                                <div id="create_rm_list_schedule" class="rm-list-container">
                                                    <!-- Dynamic items -->
                                                </div>
                                                <input type="hidden" name="rm_name" id="create_rm_name_schedule">
                                                <input type="hidden" name="rm_id" id="create_rm_id_schedule">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                                Level</label>
                                            <select name="match_level" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                                <option value="" disabled selected>Select Level</option>
                                                <option value="Level 1">1</option>
                                                <option value="Level 2">2</option>
                                                <option value="Level 3">3</option>
                                                <option value="Level 4">4</option>
                                                <option value="Level 5">5</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Discipline</label>
                                            <div class="discipline-container"
                                                style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; max-height: 150px; overflow: auto; background: #fff;">
                                                <?php if (!empty($disciplines)): ?>
                                                    <?php foreach ($disciplines as $discipline): ?>
                                                        <label
                                                            style="display:flex; align-items:center; gap:8px; padding:6px 0; font-size:0.9rem;">
                                                            <input type="checkbox" name="disciplines[]"
                                                                value="<?php echo htmlspecialchars($discipline['name']); ?>">
                                                            <span><?php echo htmlspecialchars($discipline['name']); ?></span>
                                                        </label>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <div style="color:#64748b; font-size:0.85rem;">
                                                        No disciplines available. Please add disciplines in Management.
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-top: 6px;">
                                                You can select multiple disciplines.
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Location</label>
                                        <input type="text" name="location" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>
                                </div>

                                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px;">
                                    <button type="button"
                                        onclick="closeAndClearModal('createMatchModalSchedule', 'createMatchPreview', 'createMatchFileInput')"
                                        style="background: none; border: none; color: #64748b; font-weight: 600; cursor: pointer;">Cancel</button>
                                    <button type="submit" class="btn-primary" style="width: auto; padding: 10px 25px;">Save
                                        Schedule</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Edit Match Modal -->
                    <div id="editMatchModal" class="modal">
                        <div class="modal-content" style="max-width: 600px;">
                            <h3>Edit Match Schedule</h3>
                            <form method="POST" id="editMatchFormSchedule"
                                onsubmit="return validateMatchForm(this, 'edit');">
                                <input type="hidden" name="action" value="update_match">
                                <input type="hidden" name="match_id" id="edit_match_id">

                                <div style="display: grid; gap: 15px;">
                                    <?php if ($is_officer_role): ?>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                            <div
                                                style="background:#fffbeb; border:1px solid #fde68a; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_retroactive" value="1"
                                                        id="editMatchRetroactiveSchedule"
                                                        onchange="handleMatchCheckboxChange('editMatchRetroactiveSchedule', 'editMatchLocalSchedule')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#d97706;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#92400e;"><i
                                                                class="fas fa-lock" style="margin-right:5px;"></i>Retroactive
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#78350f; margin-top:3px;">If
                                                            checked, only users from your <strong>area</strong> can join, and
                                                            you can select <strong>previous dates</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                            <div
                                                style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:10px; padding:12px 16px;">
                                                <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer;">
                                                    <input type="checkbox" name="is_local" value="1" id="editMatchLocalSchedule"
                                                        onchange="handleMatchCheckboxChange('editMatchLocalSchedule', 'editMatchRetroactiveSchedule')"
                                                        style="width:18px; height:18px; margin-top:2px; cursor:pointer; accent-color:#16a34a;">
                                                    <span>
                                                        <span
                                                            style="display:block; font-size:0.85rem; font-weight:700; color:#166534;"><i
                                                                class="fas fa-map-marker-alt"
                                                                style="margin-right:5px;"></i>Local
                                                            Match</span>
                                                        <span
                                                            style="display:block; font-size:0.75rem; color:#14532d; margin-top:3px;">If
                                                            checked, this match is only visible and applicable to users from
                                                            your <strong>area</strong>.</span>
                                                    </span>
                                                </label>
                                            </div>
                                        </div>
                                        <div style="font-size: 0.75rem; color: #64748b; margin-top: -5px; text-align: center;">
                                            <i class="fas fa-info-circle"></i> If no checkbox is selected, this is considered a
                                            <strong>National/Regular Match</strong>.
                                        </div>
                                    <?php endif; ?>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                            Name</label>
                                        <input type="text" name="match_name" id="edit_match_name" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Start
                                                Date</label>
                                            <input type="date" name="start_date" id="edit_start_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">End
                                                Date</label>
                                            <input type="date" name="end_date" id="edit_end_date" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Serving
                                                RO Limit</label>
                                            <input type="number" name="ro_limit" id="edit_ro_limit"
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Range
                                                Master Name</label>
                                            <div class="rm-selection-wrapper">
                                                <div class="rm-search-box">
                                                    <input type="text" id="edit_rm_search_schedule" class="rm-search-input"
                                                        placeholder="Search Range Master..." autocomplete="off">
                                                </div>
                                                <div id="edit_rm_list_schedule" class="rm-list-container">
                                                    <!-- Dynamic items -->
                                                </div>
                                                <input type="hidden" name="rm_name" id="edit_rm_name_schedule">
                                                <input type="hidden" name="rm_id" id="edit_rm_id_schedule">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Match
                                                Level</label>
                                            <select name="match_level" id="edit_match_level" required
                                                style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                                <option value="" disabled selected>Select Level</option>
                                                <option value="Level 1">1</option>
                                                <option value="Level 2">2</option>
                                                <option value="Level 3">3</option>
                                                <option value="Level 4">4</option>
                                                <option value="Level 5">5</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label
                                                style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Discipline</label>
                                            <div class="discipline-container"
                                                style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; max-height: 150px; overflow: auto; background: #fff;">
                                                <?php foreach ($disciplines as $discipline): ?>
                                                    <label
                                                        style="display:flex; align-items:center; gap:8px; padding:6px 0; font-size:0.9rem;">
                                                        <input type="checkbox" name="disciplines[]"
                                                            value="<?php echo htmlspecialchars($discipline['name']); ?>">
                                                        <span><?php echo htmlspecialchars($discipline['name']); ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-top: 6px;">
                                                You can select multiple disciplines.
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <label
                                            style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">Location</label>
                                        <input type="text" name="location" id="edit_location" required
                                            style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px;">
                                    </div>
                                </div>

                                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px;">
                                    <button type="button"
                                        onclick="closeAndClearModal('editMatchModal', 'editMatchPreview', 'editMatchFileInput')"
                                        style="background: none; border: none; color: #64748b; font-weight: 600; cursor: pointer;">Cancel</button>
                                    <button type="submit" class="btn-primary"
                                        style="width: auto; padding: 10px 25px;">Update
                                        Schedule</button>
                                </div>
                            </form>
                        </div>
                    </div>

                <?php elseif (isset($_GET['view']) && $_GET['view'] == 'signified'): ?>
                    <?php
                    // Handle Signification Actions (Approve, Decline, Standby)
                    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['signification_action'])) {
                        try {
                            $significationId = $_POST['signification_id'];
                            $action = $_POST['signification_action'];
                            $remarks = $_POST['remarks'] ?? '';

                            $status = '';
                            if ($action === 'approve') {
                                $status = 'approved';
                            } elseif ($action === 'decline') {
                                $status = 'declined';
                            } elseif ($action === 'standby') {
                                $status = 'standby';
                            } elseif ($action === 'approve_withdrawal') {
                                $status = 'withdrawn';
                            } elseif ($action === 'reject_withdrawal') {
                                // Restore previous status (assuming it was approved or pending)
                                // For simplicity, we'll set it back based on what it likely was, 
                                // but better to fetch current status. For now, let's just set to 'approved'
                                // as per "continue the user's signification".
                                $status = 'approved';
                            }

                            $stmt = $pdo->prepare("UPDATE match_significations SET status=?, officer_remarks=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?");
                            $stmt->execute([$status, $remarks, $_SESSION['user_id'], $significationId]);

                            echo "<script>alert('Signification " . ucfirst($status) . " successfully!'); location.href='matches.php?view=signified';</script>";
                        } catch (PDOException $e) {
                            echo "<script>alert('Action failed: " . $e->getMessage() . "');</script>";
                        }
                    }

                    // Fetch significations localized to the Officer's Area
                    $area = $_SESSION['area'] ?? '';
                    $stmt = $pdo->prepare("
                SELECT 
                    ms.*,
                    u.nroi_id, u.first_name, u.last_name, u.role, u.rank, u.area,
                    m.match_name, m.start_date, m.end_date, m.location, m.match_level,
                    reviewer.first_name as reviewer_first_name, reviewer.last_name as reviewer_last_name,
                    (SELECT al.performed_by_role FROM activity_logs al
                     WHERE al.reference_type = 'match_signification' AND al.reference_id = ms.id
                       AND al.performed_by_role IN ('AC','AAC','ADMIN','RM')
                     ORDER BY al.created_at DESC LIMIT 1) as reviewer_role
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                LEFT JOIN users reviewer ON ms.reviewed_by = reviewer.id
                WHERE u.area = ?
                ORDER BY ms.created_at DESC
            ");
                    $stmt->execute([$area]);
                    $significations = $stmt->fetchAll();

                    // Group by status
                    $pending = [];
                    $approved = [];
                    $declined = [];
                    $standby = [];
                    $withdrawals = [];

                    foreach ($significations as $s) {
                        if ($s['status'] === 'pending') {
                            $pending[] = $s;
                        } elseif ($s['status'] === 'approved') {
                            $approved[] = $s;
                        } elseif ($s['status'] === 'declined') {
                            $declined[] = $s;
                        } elseif ($s['status'] === 'standby') {
                            $standby[] = $s;
                        } elseif ($s['status'] === 'withdrawal_requested') {
                            $withdrawals[] = $s;
                        }
                    }
                    ?>

                    <div class="content-box">
                        <div class="table-header">
                            <h3>Match Significations</h3>
                            <div style="font-size: 0.85rem; color: #64748b;">
                                Review and manage user significations for matches
                            </div>
                        </div>

                        <!-- Withdrawal Requests -->
                        <h4
                            style="color: #ef4444; margin: 20px 0 10px 0; border-bottom: 2px solid #fee2e2; padding-bottom: 5px;">
                            <i class="fas fa-exclamation-triangle"></i> Withdrawal Requests
                            (<?php echo count($withdrawals); ?>)
                        </h4>
                        <?php if (empty($withdrawals)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No pending withdrawal requests.
                            </p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Match</th>
                                        <th>Level</th>
                                        <th>Withdrawal Reason</th>
                                        <th>Date</th>
                                        <th>Requested On</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($withdrawals as $s): ?>
                                        <tr>
                                            <td style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($s['last_name'] . ', ' . $s['first_name']); ?>
                                            </td>
                                            <td style="font-weight: 600; color: #1e3a8a;">
                                                <?php echo htmlspecialchars($s['match_name']); ?>
                                            </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/', '', $s['match_level']); ?>
                                                </div>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #92400e; max-width: 250px;">
                                                <div style="font-weight:600; font-size: 0.75rem; color:#64748b;">Member's Reason:</div>
                                                <?php echo htmlspecialchars($s['withdrawal_reason'] ?: '-'); ?>
                                            </td>
                                            <td style="font-size: 0.85rem;">
                                                <?php echo date('M d', strtotime($s['start_date'])) . ' - ' . date('M d, Y', strtotime($s['end_date'])); ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b;">
                                                <?php echo date('M d, Y h:i A', strtotime($s['created_at'])); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <button class="icon-btn"
                                                    style="background: #10b981; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "approve_withdrawal")'>
                                                    Approve Withdrawal
                                                </button>
                                                <button class="icon-btn btn-reject"
                                                    style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "reject_withdrawal")'>
                                                    Reject Withdrawal
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Pending Significations -->
                        <h4
                            style="color: #f59e0b; margin: 20px 0 10px 0; border-bottom: 2px solid #ffedd5; padding-bottom: 5px;">
                            <i class="fas fa-clock"></i> Pending Review (<?php echo count($pending); ?>)
                        </h4>
                        <?php if (empty($pending)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No pending significations.</p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>NROI ID</th>
                                        <th>Name</th>
                                        <th>Rank</th>
                                        <th>Match</th>
                                        <th>Level</th>
                                        <th>Date</th>
                                        <th>Signified On</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending as $s): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($s['nroi_id'] ?? 'N/A'); ?></td>
                                            <td style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($s['last_name'] . ', ' . $s['first_name']); ?>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 4px;">
                                                    <span class="role-badge" style="background: #eff6ff; color: #1e40af;">
                                                        <?php echo (!empty($s['role']) && $s['role'] !== 'member') ? htmlspecialchars($s['role']) : 'R.O'; ?>
                                                    </span>
                                                    <?php
                                                    $displayRoleS = (!empty($s['role']) && $s['role'] !== 'member') ? $s['role'] : 'R.O';
                                                    if ($displayRoleS !== 'AC' && $displayRoleS !== 'AAC'):
                                                        ?>
                                                        <span style="font-size: 0.7rem; color: #64748b; font-weight: 500;">
                                                            <i class="fas fa-info-circle" style="font-size: 0.65rem; opacity: 0.5;"></i>
                                                            Status:
                                                            <?php echo htmlspecialchars(($s['rank'] === 'Regular' || $s['rank'] === 'OJT') ? $s['rank'] : 'Regular'); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td style="font-weight: 600; color: #1e3a8a;">
                                                <?php echo htmlspecialchars($s['match_name']); ?>
                                            </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/', '', $s['match_level']); ?>
                                                </div>
                                            </td>
                                            <td style="font-size: 0.85rem;">
                                                <?php echo date('M d', strtotime($s['start_date'])) . ' - ' . date('M d, Y', strtotime($s['end_date'])); ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b;">
                                                <?php echo date('M d, Y h:i A', strtotime($s['created_at'])); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <button class="icon-btn" style="background: #10b981; color: white;"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "approve")'
                                                    title="Approve">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                                <button class="icon-btn" style="background: #f59e0b; color: white;"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "standby")'
                                                    title="Standby">
                                                    <i class="fas fa-pause"></i>
                                                </button>
                                                <button class="icon-btn btn-reject"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "decline")'
                                                    title="Decline">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Approved Significations -->
                        <h4
                            style="color: #10b981; margin: 20px 0 10px 0; border-bottom: 2px solid #d1fae5; padding-bottom: 5px;">
                            <i class="fas fa-check-circle"></i> Approved (<?php echo count($approved); ?>)
                        </h4>
                        <?php if (empty($approved)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No approved significations.</p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>NROI ID</th>
                                        <th>Name</th>
                                        <th>Match</th>
                                        <th>Reviewed By</th>
                                        <th>Reviewed On</th>
                                        <th>Remarks</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($approved as $s): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($s['nroi_id'] ?? 'N/A'); ?></td>
                                            <td style="font-weight: 600;">
                                                <?php echo htmlspecialchars($s['last_name'] . ', ' . $s['first_name']); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($s['match_name']); ?></td>
                                            <td style="font-size: 0.85rem;">
                                                <?php echo htmlspecialchars(($s['reviewer_last_name'] ?? '') . ', ' . ($s['reviewer_first_name'] ?? '')); ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b;">
                                                <?php echo $s['reviewed_at'] ? date('M d, Y h:i A', strtotime($s['reviewed_at'])) : 'N/A'; ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b; max-width: 250px;">
                                                <?php
                                                $uReason = trim($s['withdrawal_reason'] ?? '');
                                                $oNote = trim($s['officer_remarks'] ?? '');
                                                if ($uReason !== '' || $oNote !== ''):
                                                    ?>
                                                        <div style="font-size:0.82rem; color:#1e293b; line-height:1.5;">
                                                            <?php if ($uReason !== ''): ?>
                                                                    <div style="margin-bottom:4px;">
                                                                        <span style="font-weight:600; color:#92400e;">Member's Reason (Request to Withdraw):</span><br>
                                                                        <?php echo htmlspecialchars($uReason); ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                            <?php if ($oNote !== ''): ?>
                                                                    <?php
                                                                    $revRole = strtoupper(trim($s['reviewer_role'] ?? ''));
                                                                    $baseL = match ($revRole) {
                                                                        'AC' => 'AC note',
                                                                        'AAC' => 'AAC note',
                                                                        'ADMIN' => 'Admin note',
                                                                        'RM' => 'RM note',
                                                                        default => 'Officer note',
                                                                    };
                                                                    if ($s['status'] === 'standby') {
                                                                        $rLabel = $baseL . ' (Standby Reason):';
                                                                    } elseif ($s['status'] === 'approved' && $uReason !== '') {
                                                                        $rLabel = $baseL . ' (Rejected to Withdraw Reason):';
                                                                    } elseif (in_array($s['status'], ['declined', 'rejected'])) {
                                                                        $rLabel = $baseL . ' (Rejection/Decline Reason):';
                                                                    } else {
                                                                        $rLabel = $baseL . ':';
                                                                    }
                                                                    ?>
                                                                    <div>
                                                                        <span style="font-weight:600; color:#1e40af;"><?php echo $rLabel; ?></span><br>
                                                                        <?php echo htmlspecialchars($oNote); ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                        </div>
                                                    <?php else: ?>
                                                        -
                                                    <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Standby Significations -->
                        <h4
                            style="color: #f59e0b; margin: 20px 0 10px 0; border-bottom: 2px solid #ffedd5; padding-bottom: 5px;">
                            <i class="fas fa-pause-circle"></i> On Standby (<?php echo count($standby); ?>)
                        </h4>
                        <?php if (empty($standby)): ?>
                            <p style="color: #64748b; font-style: italic; margin-bottom: 20px;">No standby significations.</p>
                        <?php else: ?>
                            <table class="modern-table" style="margin-bottom: 30px;">
                                <thead>
                                    <tr>
                                        <th>NROI ID</th>
                                        <th>Name</th>
                                        <th>Match</th>
                                        <th>Reviewed By</th>
                                        <th>Reviewed On</th>
                                        <th>Remarks</th>
                                        <th style="text-align: right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($standby as $s): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($s['nroi_id'] ?? 'N/A'); ?></td>
                                            <td style="font-weight: 600;">
                                                <?php echo htmlspecialchars($s['last_name'] . ', ' . $s['first_name']); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($s['match_name']); ?></td>
                                            <td style="font-size: 0.85rem;">
                                                <?php echo htmlspecialchars(($s['reviewer_last_name'] ?? '') . ', ' . ($s['reviewer_first_name'] ?? '')); ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b;">
                                                <?php echo $s['reviewed_at'] ? date('M d, Y h:i A', strtotime($s['reviewed_at'])) : 'N/A'; ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b; max-width: 200px;">
                                                <?php echo htmlspecialchars($s['officer_remarks'] ?: '-'); ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <button class="icon-btn" style="background: #10b981; color: white;"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "approve")'
                                                    title="Approve">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                                <button class="icon-btn btn-reject"
                                                    onclick='openReviewModal(<?php echo json_encode($s); ?>, "decline")'
                                                    title="Decline">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>

                        <!-- Declined Significations -->
                        <h4
                            style="color: #ef4444; margin: 20px 0 10px 0; border-bottom: 2px solid #fee2e2; padding-bottom: 5px;">
                            <i class="fas fa-times-circle"></i> Declined (<?php echo count($declined); ?>)
                        </h4>
                        <?php if (empty($declined)): ?>
                            <p style="color: #64748b; font-style: italic;">No declined significations.</p>
                        <?php else: ?>
                            <table class="modern-table">
                                <thead>
                                    <tr>
                                        <th>NROI ID</th>
                                        <th>Name</th>
                                        <th>Match</th>
                                        <th>Reviewed By</th>
                                        <th>Reviewed On</th>
                                        <th>Remarks</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($declined as $s): ?>
                                        <tr style="opacity: 0.7;">
                                            <td><?php echo htmlspecialchars($s['nroi_id'] ?? 'N/A'); ?></td>
                                            <td style="font-weight: 600;">
                                                <?php echo htmlspecialchars($s['last_name'] . ', ' . $s['first_name']); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($s['match_name']); ?></td>
                                            <td style="font-size: 0.85rem;">
                                                <?php echo htmlspecialchars(($s['reviewer_last_name'] ?? '') . ', ' . ($s['reviewer_first_name'] ?? '')); ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b;">
                                                <?php echo $s['reviewed_at'] ? date('M d, Y h:i A', strtotime($s['reviewed_at'])) : 'N/A'; ?>
                                            </td>
                                            <td style="font-size: 0.85rem; color: #64748b; max-width: 200px;">
                                                <?php echo htmlspecialchars($s['officer_remarks'] ?: '-'); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>

                    <!-- Review Modal -->
                    <div id="reviewModal" class="modal">
                        <div class="modal-content" style="max-width: 500px;">
                            <h3 id="reviewModalTitle">Review Signification</h3>
                            <form method="POST">
                                <input type="hidden" name="signification_id" id="review_signification_id">
                                <input type="hidden" name="signification_action" id="review_action">

                                <div style="background: #f8fafc; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                                    <div style="display: grid; gap: 8px; font-size: 0.9rem;">
                                        <div><strong>Member:</strong> <span id="review_member_name"></span></div>
                                        <div><strong>Match:</strong> <span id="review_match_name"></span></div>
                                        <div><strong>Level:</strong> <span id="review_match_level"></span></div>
                                    </div>
                                </div>

                                <div id="remarksContainer">
                                    <label
                                        style="display:block; font-size: 0.8rem; font-weight: 700; color: #64748b; margin-bottom: 5px;">
                                        Remarks/Notes <span id="remarksRequired" style="color: #ef4444;">*</span>
                                    </label>
                                    <textarea name="remarks" id="review_remarks" rows="4"
                                        style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; font-family: 'Inter', sans-serif;"
                                        placeholder="Enter your remarks or notes here..."></textarea>
                                    <div style="font-size: 0.75rem; color: #64748b; margin-top: 5px;">
                                        <span id="remarksHint">Required when declining. Optional for approve/standby.</span>
                                    </div>
                                </div>

                                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px;">
                                    <button type="button"
                                        onclick="document.getElementById('reviewModal').classList.remove('active')"
                                        style="background: none; border: none; color: #64748b; font-weight: 600; cursor: pointer;">Cancel</button>
                                    <button type="submit" class="btn-primary" id="reviewSubmitBtn"
                                        style="width: auto; padding: 10px 25px;">
                                        Confirm
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                <?php endif; ?>
        </main>


        <script>
            const rmUsersData = <?php echo json_encode($rmUsersList); ?>;

            function validateMatchForm(form, type) {
                // Find all match rows to check for uniqueness
                const rows = document.querySelectorAll('.match-row');
                const matchNameInput = form.querySelector('[name="match_name"]');
                const locationInput = form.querySelector('[name="location"]');
                const levelInput = form.querySelector('[name="match_level"]');
                const disciplineContainer = form.querySelector('.discipline-container') || form.querySelector('div[style*="overflow: auto"]');
                const disciplineInputs = form.querySelectorAll('[name="disciplines[]"]');
                const matchIdInput = form.querySelector('[name="match_id"]');

                const matchName = (matchNameInput.value || '').trim().toLowerCase();
                const location = (locationInput.value || '').trim().toLowerCase();
                const matchId = matchIdInput ? matchIdInput.value : null;

                let isValid = true;

                // Reset errors
                form.querySelectorAll('.input-error').forEach(el => el.classList.remove('input-error'));
                form.querySelectorAll('.error-text').forEach(el => el.remove());
                form.querySelectorAll('label').forEach(el => el.classList.remove('error-label'));

                // 1. Check Match Level (Mandatory selection)
                if (!levelInput.value) {
                    isValid = false;
                    levelInput.classList.add('input-error');
                    const label = levelInput.previousElementSibling;
                    if (label) label.classList.add('error-label');

                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-text';
                    errorMsg.style.color = '#ef4444';
                    errorMsg.style.fontSize = '0.7rem';
                    errorMsg.style.marginTop = '4px';
                    errorMsg.style.fontWeight = '600';
                    errorMsg.textContent = 'Please select a match level.';
                    levelInput.parentElement.appendChild(errorMsg);
                }

                // 2. Check if at least one discipline is selected
                let disciplineChecked = false;
                disciplineInputs.forEach(input => {
                    if (input.checked) disciplineChecked = true;
                });

                if (!disciplineChecked) {
                    isValid = false;
                    if (disciplineContainer) {
                        disciplineContainer.classList.add('input-error');
                        const label = disciplineContainer.previousElementSibling;
                        if (label) label.classList.add('error-label');

                        const errorMsg = document.createElement('div');
                        errorMsg.className = 'error-text';
                        errorMsg.style.color = '#ef4444';
                        errorMsg.style.fontSize = '0.7rem';
                        errorMsg.style.marginTop = '4px';
                        errorMsg.style.fontWeight = '600';
                        errorMsg.textContent = 'Please select at least one discipline.';
                        disciplineContainer.parentElement.appendChild(errorMsg);
                    }
                }

                // 3. Check for unique Name and Location (case-insensitive)
                let isUnique = true;
                rows.forEach(row => {
                    const rowId = row.dataset.id;
                    const rowName = (row.dataset.name || '').toLowerCase();
                    const rowLocation = (row.dataset.location || '').toLowerCase();

                    // Skip if it's the same match we're editing
                    if (type === 'edit' && matchId && rowId == matchId) return;

                    if (rowName === matchName && rowLocation === location) {
                        isUnique = false;
                    }
                });

                if (!isUnique) {
                    isValid = false;
                    matchNameInput.classList.add('input-error');
                    locationInput.classList.add('input-error');

                    const nameLabel = matchNameInput.previousElementSibling;
                    if (nameLabel && nameLabel.tagName === 'LABEL') nameLabel.classList.add('error-label');

                    const locLabel = locationInput.previousElementSibling;
                    if (locLabel && locLabel.tagName === 'LABEL') locLabel.classList.add('error-label');

                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-text';
                    errorMsg.style.color = '#ef4444';
                    errorMsg.style.fontSize = '0.7rem';
                    errorMsg.style.marginTop = '4px';
                    errorMsg.style.fontWeight = '600';
                    errorMsg.textContent = 'A match with this name and location already exists.';

                    // Append near location input
                    if (locationInput.parentElement) {
                        locationInput.parentElement.appendChild(errorMsg);
                    }
                }
                // 4. Check Range Master Selection (Only name is required)
                const rmHiddenInput = form.querySelector('[name="rm_name"]');
                const rmSearchInput = form.querySelector('.rm-search-input');
                if (!rmHiddenInput || !rmHiddenInput.value) {
                    isValid = false;
                    if (rmSearchInput) {
                        rmSearchInput.classList.add('input-error');
                        const selectionWrapper = rmSearchInput.closest('.rm-selection-wrapper');
                        const label = selectionWrapper ? selectionWrapper.previousElementSibling : null;
                        if (label && label.tagName === 'LABEL') label.classList.add('error-label');

                        const errorMsg = document.createElement('div');
                        errorMsg.className = 'error-text';
                        errorMsg.style.color = '#ef4444';
                        errorMsg.style.fontSize = '0.7rem';
                        errorMsg.style.marginTop = '4px';
                        errorMsg.style.fontWeight = '600';
                        errorMsg.textContent = 'Please enter or select a Range Master.';
                        if (selectionWrapper) selectionWrapper.appendChild(errorMsg);
                    }
                }

                if (isValid) {
                    // Guard against double-submission
                    if (form.dataset.submitting === 'true') return false;
                    form.dataset.submitting = 'true';

                    const btn = form.querySelector('button[type="submit"]');
                    const cancelBtn = form.querySelector('button[type="button"]');
                    if (btn) {
                        btn.disabled = true;
                        btn.innerHTML = `<i class='fas fa-spinner fa-spin'></i> ${type === 'edit' ? 'Updating...' : 'Saving...'}`;
                        btn.style.opacity = '0.7';
                    }
                    if (cancelBtn) {
                        // Hide the cancel button while saving to prevent confusion
                        cancelBtn.style.display = 'none';
                    }
                    return true;
                }

                // Show generic error near save button
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    let errorBanner = form.querySelector('.form-error-banner');
                    if (!errorBanner) {
                        errorBanner = document.createElement('span');
                        errorBanner.className = 'form-error-banner';
                        errorBanner.style.color = '#ef4444';
                        errorBanner.style.fontSize = '0.75rem';
                        errorBanner.style.fontWeight = 'bold';
                        errorBanner.style.marginRight = '10px';
                        errorBanner.style.display = 'flex';
                        errorBanner.style.alignItems = 'center';
                        errorBanner.innerHTML = '<i class="fas fa-exclamation-circle" style="margin-right:5px;"></i> Please fix errors before saving.';
                        submitBtn.parentNode.insertBefore(errorBanner, submitBtn);
                    }
                }

                // Scroll to first error
                const firstError = form.querySelector('.input-error');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }

                return false;
            }

        </script>
        <script src="../assets/js/loader.js"></script>
        <script>
            let selectedMatchFiles = {
                'createMatchPreview': [],
                'editMatchPreview': []
            };
            const profileToggle = document.getElementById('profileToggle');
            const profileDropdown = document.getElementById('profileDropdown');
            if (profileToggle) {
                profileToggle.addEventListener('click', (e) => {
                    e.stopPropagation();
                    profileDropdown.classList.toggle('active');
                });
            }
            document.addEventListener('click', () => profileDropdown?.classList.remove('active'));

            function handleMatchCheckboxChange(activeId, otherId) {
                const activeCb = document.getElementById(activeId);
                const otherCb = document.getElementById(otherId);

                if (activeCb.checked) {
                    if (otherCb) otherCb.checked = false;
                }

                // Sync with retroactive logic (date restriction)
                if (activeId === 'createMatchRetroactive' || otherId === 'createMatchRetroactive') {
                    const retroCb = document.getElementById('createMatchRetroactive');
                    if (retroCb) toggleCreateRetroactive(retroCb);
                }
            }

            function toggleCreateRetroactive(cb) {
                const today = new Date().toISOString().split('T')[0];
                const startInput = document.getElementById('create_start_date');
                const endInput = document.getElementById('create_end_date');
                if (!startInput || !endInput) return;

                if (cb.checked) {
                    startInput.removeAttribute('min');
                    endInput.removeAttribute('min');
                } else {
                    startInput.min = today;
                    endInput.min = today;

                    // If current values are in the past, reset them
                    if (startInput.value && startInput.value < today) startInput.value = today;
                    if (endInput.value && endInput.value < today) endInput.value = today;
                }
            }

            // Range Master Selection Logic
            function initRMSelection(searchId, listId, hiddenNameId, hiddenIdId) {
                const searchInput = document.getElementById(searchId);
                const listContainer = document.getElementById(listId);
                const hiddenNameInput = document.getElementById(hiddenNameId);
                const hiddenIdInput = document.getElementById(hiddenIdId);

                if (!searchInput || !listContainer || !hiddenNameInput || !hiddenIdInput) return;

                function renderRMList(query = '') {
                    const q = query.toLowerCase().trim();
                    const filtered = rmUsersData.filter(u => {
                        const fullName = (u.first_name + ' ' + u.last_name).toLowerCase();
                        const nroiId = (u.nroi_id || '').toString().toLowerCase();
                        return fullName.includes(q) || nroiId.includes(q);
                    });

                    listContainer.innerHTML = '';

                    if (filtered.length === 0) {
                        listContainer.innerHTML = '<div style="padding:15px; text-align:center; color:#94a3b8; font-size:0.8rem;">No users found.</div>';
                        return;
                    }

                    filtered.forEach(u => {
                        const name = `${u.first_name} ${u.last_name}`;
                        const item = document.createElement('div');
                        item.className = 'rm-list-item';
                        if (hiddenIdInput.value == u.id) item.classList.add('selected');

                        item.innerHTML = `
                        <div class="rm-item-name">${name}</div>
                        <div class="rm-item-info">
                            <span>ID: ${u.nroi_id || '---'}</span>
                            <span class="rm-role-badge">${u.role || 'Member'}</span>
                        </div>
                    `;

                        item.onclick = () => {
                            listContainer.querySelectorAll('.rm-list-item').forEach(el => el.classList.remove('selected'));
                            item.classList.add('selected');
                            hiddenNameInput.value = name;
                            hiddenIdInput.value = u.id;
                            searchInput.value = name; // Auto-fill search with selected name
                        };

                        listContainer.appendChild(item);
                    });
                }

                searchInput.addEventListener('input', (e) => {
                    const val = e.target.value;
                    hiddenNameInput.value = val;
                    if (hiddenIdInput) hiddenIdInput.value = ''; // Always clear ID when user types, they must re-select if they want a linked user
                    renderRMList(val);
                });

                // Expose for external calls (like reset)
                return {
                    refresh: (name, id) => {
                        hiddenNameInput.value = name || '';
                        if (hiddenIdInput) hiddenIdInput.value = id || '';
                        searchInput.value = name || '';
                        renderRMList();
                    }
                };
            }

            let createRMUI, editRMUI, createRMSchedUI, editRMSchedUI;

            // Initialize UI
            document.addEventListener('DOMContentLoaded', () => {
                createRMUI = initRMSelection('create_rm_search', 'create_rm_list', 'create_rm_name', 'create_rm_id');
                editRMUI = initRMSelection('edit_rm_search', 'edit_rm_list', 'edit_rm_name', 'edit_rm_id');
                // These seem to be used in some other part of the UI or legacy code
                createRMSchedUI = initRMSelection('create_rm_search_schedule', 'create_rm_list_schedule', 'create_rm_name_schedule', 'create_rm_id_schedule');
                editRMSchedUI = initRMSelection('edit_rm_search_schedule', 'edit_rm_list_schedule', 'edit_rm_name_schedule', 'edit_rm_id_schedule');
            });

            function openEditMatch(match) {
                const today = new Date().toISOString().split('T')[0];
                const isRetro = parseInt(match.is_retroactive || 0) === 1;
                const isCompleted = match.end_date < today;

                const startDateInput = document.getElementById('edit_start_date');
                const endDateInput = document.getElementById('edit_end_date');

                // Reset inputs
                startDateInput.disabled = false;
                endDateInput.disabled = false;
                startDateInput.removeAttribute('min');
                endDateInput.removeAttribute('min');

                if (!isRetro) {
                    if (isCompleted) {
                        startDateInput.disabled = true;
                        endDateInput.disabled = true;
                    } else {
                        startDateInput.min = today;
                        endDateInput.min = today;
                    }
                }

                document.getElementById('edit_match_id').value = match.id;
                document.getElementById('edit_match_name').value = match.match_name;
                startDateInput.value = match.start_date;
                endDateInput.value = match.end_date;
                document.getElementById('edit_match_level').value = match.match_level;
                document.getElementById('edit_location').value = match.location;
                document.getElementById('edit_ro_limit').value = match.ro_limit || '';

                if (editRMUI) {
                    editRMUI.refresh(match.rm_name || '', match.rm_id || '');
                }
                if (editRMSchedUI) {
                    editRMSchedUI.refresh(match.rm_name || '', match.rm_id || '');
                }

                const retroCb = document.getElementById('editMatchRetroactive');
                const localCb = document.getElementById('editMatchLocal');
                if (retroCb) retroCb.checked = parseInt(match.is_retroactive || 0) === 1;
                if (localCb) localCb.checked = parseInt(match.is_local || 0) === 1;

                // Check the disciplines checkboxes based on stored string (comma-separated)
                const selected = (match.range_master || '')
                    .split(',')
                    .map(s => s.trim())
                    .filter(Boolean);
                document.querySelectorAll('#editMatchModal input[name="disciplines[]"]').forEach((cb) => {
                    cb.checked = selected.includes(cb.value);
                });

                if (document.getElementById('editMatchPreview')) document.getElementById('editMatchPreview').innerHTML = '';
                selectedMatchFiles['editMatchPreview'] = [];
                if (document.getElementById('editMatchFileInput')) document.getElementById('editMatchFileInput').value = '';

                document.querySelectorAll('#editMatchModal input[name="removed_attachments[]"]').forEach(el => el.remove());

                const existingContainer = document.getElementById('existingAttachments');
                existingContainer.innerHTML = '';
                if (match.attachments && match.attachments.length > 0) {
                    const title = document.createElement('div');
                    title.style.width = '100%';
                    title.style.fontSize = '0.75rem';
                    title.style.fontWeight = 'bold';
                    title.style.color = '#64748b';
                    title.textContent = 'EXISTING ATTACHMENTS:';
                    existingContainer.appendChild(title);

                    match.attachments.forEach(att => {
                        const div = document.createElement('div');
                        div.style.position = 'relative';
                        div.style.width = '80px';
                        div.style.height = '80px';
                        div.style.border = '1px solid #e2e8f0';
                        div.style.borderRadius = '8px';
                        div.style.overflow = 'hidden';
                        div.style.background = '#f8fafc';
                        div.style.display = 'flex';
                        div.style.alignItems = 'center';
                        div.style.justifyContent = 'center';

                        const isImg = att.file_type.includes('image') || /\.(jpg|jpeg|png|gif)$/i.test(att.file_name);

                        if (isImg) {
                            const img = document.createElement('img');
                            img.src = '../' + att.file_path;
                            img.style.width = '100%';
                            img.style.height = '100%';
                            img.style.objectFit = 'cover';
                            div.appendChild(img);
                        } else {
                            div.innerHTML = '<i class="fas fa-file-pdf" style="color: #ef4444; font-size: 2rem;"></i>';
                        }

                        // Add remove button for existing attachment
                        const removeBtn = document.createElement('div');
                        removeBtn.innerHTML = '&times;';
                        removeBtn.style.position = 'absolute';
                        removeBtn.style.top = '2px';
                        removeBtn.style.right = '2px';
                        removeBtn.style.width = '18px';
                        removeBtn.style.height = '18px';
                        removeBtn.style.background = '#ef4444';
                        removeBtn.style.color = 'white';
                        removeBtn.style.borderRadius = '50%';
                        removeBtn.style.display = 'flex';
                        removeBtn.style.alignItems = 'center';
                        removeBtn.style.justifyContent = 'center';
                        removeBtn.style.cursor = 'pointer';
                        removeBtn.style.fontSize = '12px';
                        removeBtn.style.fontWeight = 'bold';
                        removeBtn.style.zIndex = '10';
                        removeBtn.onclick = function (event) {
                            event.stopPropagation();
                            if (confirm('Are you sure you want to remove this existing attachment?')) {
                                const hiddenInput = document.createElement('input');
                                hiddenInput.type = 'hidden';
                                hiddenInput.name = 'removed_attachments[]';
                                hiddenInput.value = att.id;
                                document.querySelector('#editMatchModal form').appendChild(hiddenInput);
                                div.remove();
                            }
                        };
                        div.appendChild(removeBtn);

                        const name = document.createElement('div');
                        name.textContent = att.file_name;
                        name.style.position = 'absolute';
                        name.style.bottom = '0';
                        name.style.left = '0';
                        name.style.right = '0';
                        name.style.background = 'rgba(0,0,0,0.5)';
                        name.style.color = 'white';
                        name.style.fontSize = '8px';
                        name.style.padding = '2px 4px';
                        name.style.whiteSpace = 'nowrap';
                        name.style.overflow = 'hidden';
                        name.style.textOverflow = 'ellipsis';
                        div.appendChild(name);

                        existingContainer.appendChild(div);
                    });
                }

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

            function deleteMatch(id) {
                if (confirm('Are you sure you want to delete this scheduled match?')) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `<input type="hidden" name="action" value="delete_match"><input type="hidden" name="match_id" value="${id}">`;
                    document.body.appendChild(form);
                    form.submit();
                }
            }

            function openReviewModal(signification, action) {
                // Set hidden fields
                document.getElementById('review_signification_id').value = signification.id;
                document.getElementById('review_action').value = action;

                // Set display fields
                document.getElementById('review_member_name').textContent = signification.last_name + ', ' + signification.first_name;
                document.getElementById('review_match_name').textContent = signification.match_name;
                document.getElementById('review_match_level').textContent = (signification.match_level || '').replace(/\D/g, '');

                // Update modal title and button based on action
                const modalTitle = document.getElementById('reviewModalTitle');
                const submitBtn = document.getElementById('reviewSubmitBtn');
                const remarksRequired = document.getElementById('remarksRequired');
                const remarksHint = document.getElementById('remarksHint');
                const remarksField = document.getElementById('review_remarks');

                if (action === 'approve') {
                    modalTitle.textContent = 'Approve Signification';
                    submitBtn.textContent = 'Approve';
                    submitBtn.style.background = '#10b981';
                    document.getElementById('remarksContainer').style.display = 'none';
                    remarksField.required = false;
                } else if (action === 'decline') {
                    modalTitle.textContent = 'Decline Signification';
                    submitBtn.textContent = 'Decline';
                    submitBtn.style.background = '#ef4444';
                    document.getElementById('remarksContainer').style.display = 'block';
                    remarksRequired.style.display = 'inline';
                    remarksHint.textContent = 'Required: Please provide a reason for declining.';
                    remarksField.required = true;
                } else if (action === 'standby') {
                    modalTitle.textContent = 'Set to Standby';
                    submitBtn.textContent = 'Set Standby';
                    submitBtn.style.background = '#f59e0b';
                    document.getElementById('remarksContainer').style.display = 'block';
                    remarksRequired.style.display = 'inline';
                    remarksHint.textContent = 'Required: Please provide a reason for setting to standby.';
                    remarksField.required = true;
                } else if (action === 'approve_withdrawal') {
                    modalTitle.textContent = 'Approve Withdrawal Request';
                    submitBtn.textContent = 'Approve Withdrawal';
                    submitBtn.style.background = '#10b981';
                    document.getElementById('remarksContainer').style.display = 'none';
                    remarksField.required = false;
                } else if (action === 'reject_withdrawal') {
                    modalTitle.textContent = 'Reject Withdrawal Request';
                    submitBtn.textContent = 'Reject Withdrawal';
                    submitBtn.style.background = '#ef4444';
                    document.getElementById('remarksContainer').style.display = 'block';
                    remarksRequired.style.display = 'inline';
                    remarksHint.textContent = 'Required: Please provide a reason for rejecting the withdrawal.';
                    remarksField.required = true;
                }

                // Clear previous remarks
                remarksField.value = '';

                // Show modal
                document.getElementById('reviewModal').classList.add('active');
            }
        </script>

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


    <script>

        function closeAndClearModal(modalId, previewId, fileInputId) {
            // Abort any pending form submissions/loading if cancel is clicked
            window.stop();

            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.remove('active');
                // Find all forms in the modal and reset them
                const forms = modal.querySelectorAll('form');
                forms.forEach(form => {
                    form.reset();
                    // Restore buttons if they were in "Saving..." state
                    const submitBtn = form.querySelector('button[type="submit"]');
                    const cancelBtn = form.querySelector('button[type="button"]');
                    if (submitBtn) {
                        submitBtn.disabled = false;
                        const actionValue = form.querySelector('[name="action"]')?.value;
                        const isEdit = actionValue === 'update_match';
                        submitBtn.innerHTML = isEdit ? 'Update Match' : 'Save Schedule';
                        submitBtn.style.opacity = '1';
                    }
                    if (cancelBtn) {
                        cancelBtn.innerHTML = 'Cancel';
                        cancelBtn.style.color = '#64748b';
                        cancelBtn.style.display = 'block';
                    }
                    // Reset submission guard
                    form.dataset.submitting = 'false';

                    // Clear error classes and texts
                    form.querySelectorAll('.input-error').forEach(el => el.classList.remove('input-error'));
                    form.querySelectorAll('.error-text').forEach(el => el.remove());
                    form.querySelectorAll('.error-label').forEach(el => el.classList.remove('error-label'));
                    form.querySelectorAll('.form-error-banner').forEach(el => el.remove());
                });

                // Also refresh RM UI to clear selections/searches
                if (modalId === 'createMatchModal' && createRMUI) createRMUI.refresh();
                if (modalId === 'editMatchModal' && editRMUI) editRMUI.refresh();
                if (modalId === 'createMatchModalSchedule' && createRMSchedUI) createRMSchedUI.refresh();
                if (modalId === 'editMatchModal' && editRMSchedUI) editRMSchedUI.refresh(); // Handle overlapping ID if necessary
            }
            if (selectedMatchFiles[previewId]) {
                selectedMatchFiles[previewId] = [];
            }
            const preview = document.getElementById(previewId);
            if (preview) preview.innerHTML = '';
            const input = document.getElementById(fileInputId);
            if (input) input.value = '';
        }

        // Auto-dismiss success banners
        document.addEventListener('DOMContentLoaded', () => {
            const banners = document.querySelectorAll('.success-banner');
            banners.forEach(banner => {
                setTimeout(() => {
                    banner.style.opacity = '0';
                    setTimeout(() => banner.remove(), 500);
                }, 1500); // Reduce persistent time to 1.5s
            });
        });

        function previewFiles(input, previewId) {
            const files = Array.from(input.files);
            if (!selectedMatchFiles[previewId]) selectedMatchFiles[previewId] = [];

            files.forEach(file => {
                // Check if file is already in array
                const exists = selectedMatchFiles[previewId].some(
                    existingFile => existingFile.name === file.name && existingFile.size === file.size
                );
                if (!exists) {
                    selectedMatchFiles[previewId].push(file);
                }
            });

            syncInputFiles(input, previewId);
            renderMatchFilePreviews(previewId, input);
        }

        function syncInputFiles(input, previewId) {
            const dt = new DataTransfer();
            selectedMatchFiles[previewId].forEach(file => dt.items.add(file));
            input.files = dt.files;
        }

        function renderMatchFilePreviews(previewId, input) {
            const preview = document.getElementById(previewId);
            if (!preview) return;
            preview.innerHTML = '';

            if (selectedMatchFiles[previewId]) {
                selectedMatchFiles[previewId].forEach((file, index) => {
                    const div = document.createElement('div');
                    div.style.position = 'relative';
                    div.style.width = '80px';
                    div.style.height = '80px';
                    div.style.border = '1px solid #e2e8f0';
                    div.style.borderRadius = '8px';
                    div.style.overflow = 'hidden';
                    div.style.background = '#f8fafc';
                    div.style.display = 'flex';
                    div.style.alignItems = 'center';
                    div.style.justifyContent = 'center';

                    if (file.type.match('image.*')) {
                        const img = document.createElement('img');
                        img.src = URL.createObjectURL(file);
                        img.onload = () => URL.revokeObjectURL(img.src);
                        img.style.width = '100%';
                        img.style.height = '100%';
                        img.style.objectFit = 'cover';
                        div.appendChild(img);
                    } else if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) {
                        div.innerHTML = '<i class="fas fa-file-pdf" style="color: #ef4444; font-size: 2rem;"></i>';
                    } else {
                        div.innerHTML = '<i class="fas fa-file" style="color: #64748b; font-size: 2rem;"></i>';
                    }

                    // Add remove button
                    const removeBtn = document.createElement('div');
                    removeBtn.innerHTML = '&times;';
                    removeBtn.style.position = 'absolute';
                    removeBtn.style.top = '2px';
                    removeBtn.style.right = '2px';
                    removeBtn.style.width = '18px';
                    removeBtn.style.height = '18px';
                    removeBtn.style.background = '#ef4444';
                    removeBtn.style.color = 'white';
                    removeBtn.style.borderRadius = '50%';
                    removeBtn.style.display = 'flex';
                    removeBtn.style.alignItems = 'center';
                    removeBtn.style.justifyContent = 'center';
                    removeBtn.style.cursor = 'pointer';
                    removeBtn.style.fontSize = '12px';
                    removeBtn.style.fontWeight = 'bold';
                    removeBtn.style.zIndex = '10';
                    removeBtn.onclick = function (event) {
                        event.stopPropagation();
                        selectedMatchFiles[previewId].splice(index, 1);
                        syncInputFiles(input, previewId);
                        renderMatchFilePreviews(previewId, input);
                    };
                    div.appendChild(removeBtn);

                    const name = document.createElement('div');
                    name.textContent = file.name;
                    name.style.position = 'absolute';
                    name.style.bottom = '0';
                    name.style.left = '0';
                    name.style.right = '0';
                    name.style.background = 'rgba(0,0,0,0.5)';
                    name.style.color = 'white';
                    name.style.fontSize = '8px';
                    name.style.padding = '2px 4px';
                    name.style.whiteSpace = 'nowrap';
                    name.style.overflow = 'hidden';
                    name.style.textOverflow = 'ellipsis';
                    div.appendChild(name);

                    preview.appendChild(div);
                });
            }
        }
    </script>

    <!-- Attachment Modal (Global) -->
    <div id="attachmentModal" class="modal" style="z-index: 3000;">
        <div class="modal-content" style="max-width: 650px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0;">Match Attachments</h3>
                <button onclick="closeAttachmentModal()"
                    style="background: none; border: none; color: #64748b; font-size: 1.5rem; cursor: pointer;">&times;</button>
            </div>
            <div id="attachmentList"
                style="display: flex; flex-wrap: wrap; gap: 15px; justify-content: flex-start; padding: 10px; max-height: 400px; overflow-y: auto;">
                <!-- Attachments will be listed here -->
            </div>
            <div style="display: flex; justify-content: flex-end; margin-top: 25px;">
                <button onclick="closeAttachmentModal()" class="btn-primary"
                    style="width: auto; padding: 8px 20px;">Close</button>
            </div>
        </div>
    </div>

    <script>
        function showMatchAttachments(attachments) {
            const modal = document.getElementById('attachmentModal');
            const list = document.getElementById('attachmentList');
            if (!modal || !list) return;

            list.innerHTML = '';
            list.style.display = 'flex';
            list.style.flexDirection = 'row';
            list.style.flexWrap = 'wrap';
            list.style.gap = '15px';
            list.style.justifyContent = 'flex-start';
            list.style.padding = '10px';

            if (attachments && attachments.length > 0) {
                attachments.forEach(file => {
                    const isImg = file.file_type.startsWith('image/') || /\.(jpg|jpeg|png|gif)$/i.test(file.file_name);

                    const div = document.createElement('div');
                    div.style.position = 'relative';
                    div.style.width = '130px';
                    div.style.height = '130px';
                    div.style.border = '1px solid #e2e8f0';
                    div.style.borderRadius = '12px';
                    div.style.overflow = 'hidden';
                    div.style.background = '#f8fafc';
                    div.style.display = 'flex';
                    div.style.flexDirection = 'column';
                    div.style.cursor = 'pointer';
                    div.style.transition = 'all 0.2s';
                    div.onclick = () => window.open('../' + file.file_path, '_blank');

                    div.onmouseover = () => {
                        div.style.transform = 'translateY(-5px)';
                        div.style.boxShadow = '0 10px 15px -3px rgba(0,0,0,0.1)';
                        div.style.borderColor = '#1e3a8a';
                    };
                    div.onmouseout = () => {
                        div.style.transform = 'translateY(0)';
                        div.style.boxShadow = 'none';
                        div.style.borderColor = '#e2e8f0';
                    };

                    const previewArea = document.createElement('div');
                    previewArea.style.flexGrow = '1';
                    previewArea.style.display = 'flex';
                    previewArea.style.alignItems = 'center';
                    previewArea.style.justifyContent = 'center';
                    previewArea.style.position = 'relative';
                    previewArea.style.padding = '10px';

                    if (isImg) {
                        const img = document.createElement('img');
                        img.src = '../' + file.file_path;
                        img.style.width = '100%';
                        img.style.height = '100%';
                        img.style.objectFit = 'cover';
                        img.style.borderRadius = '4px';
                        previewArea.appendChild(img);
                    } else {
                        previewArea.innerHTML = '<i class="fas fa-file-pdf" style="color: #ef4444; font-size: 3rem;"></i>';
                    }
                    div.appendChild(previewArea);

                    const name = document.createElement('div');
                    name.textContent = file.file_name;
                    name.style.background = 'rgba(15, 23, 42, 0.8)';
                    name.style.color = 'white';
                    name.style.fontSize = '9px';
                    name.style.padding = '4px 8px';
                    name.style.textAlign = 'center';
                    name.style.whiteSpace = 'nowrap';
                    name.style.overflow = 'hidden';
                    name.style.textOverflow = 'ellipsis';
                    name.style.width = '100%';
                    name.title = file.file_name;
                    div.appendChild(name);

                    // Download button on top right
                    const dlBtn = document.createElement('a');
                    dlBtn.href = '../' + file.file_path;
                    dlBtn.download = file.file_name;
                    dlBtn.onclick = (e) => e.stopPropagation();
                    dlBtn.innerHTML = '<i class="fas fa-download"></i>';
                    dlBtn.style.position = 'absolute';
                    dlBtn.style.top = '5px';
                    dlBtn.style.right = '5px';
                    dlBtn.style.width = '26px';
                    dlBtn.style.height = '26px';
                    dlBtn.style.background = 'white';
                    dlBtn.style.color = '#1e3a8a';
                    dlBtn.style.borderRadius = '50%';
                    dlBtn.style.display = 'flex';
                    dlBtn.style.alignItems = 'center';
                    dlBtn.style.justifyContent = 'center';
                    dlBtn.style.fontSize = '11px';
                    dlBtn.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
                    dlBtn.style.zIndex = '20';
                    dlBtn.title = "Download";
                    div.appendChild(dlBtn);

                    list.appendChild(div);
                });
            } else {
                list.innerHTML = '<div style="text-align: center; padding: 40px; color: #64748b; width: 100%;"><i class="fas fa-folder-open" style="font-size: 2rem; display: block; margin-bottom: 10px; opacity: 0.5;"></i>No attachments found.</div>';
            }

            modal.classList.add('active');
        }

        function closeAttachmentModal() {
            const modal = document.getElementById('attachmentModal');
            if (modal) modal.classList.remove('active');
        }
    </script>

    <!-- ========== POINT CARD EDIT MODAL ========== -->
    <div id="pointCardEditModal"
        style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.55); z-index:9999; align-items:center; justify-content:center;">
        <div
            style="background:#fff; border-radius:18px; width:95%; max-width:540px; max-height:92vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,0.22); padding:0;">
            <!-- Header -->
            <div id="pcModalHeader"
                style="background:linear-gradient(135deg,#1e3a8a,#2563eb); border-radius:18px 18px 0 0; padding:22px 28px 18px; color:#fff;">
                <div style="font-size:0.72rem; font-weight:700; letter-spacing:1.5px; opacity:0.8; margin-bottom:4px;">
                    INPUT POINT CARD ASSIGNMENT</div>
                <div id="pcModalName" style="font-size:1.15rem; font-weight:800;"></div>
                <div id="pcModalMatch" style="font-size:0.82rem; opacity:0.75; margin-top:2px;"></div>
            </div>

            <!-- Step 1: Assignment Fields -->
            <div id="pcStep1" style="padding:26px 28px 22px;">

                <!-- Points Display -->
                <div
                    style="background:#eff6ff; border:1px solid #bfdbfe; border-radius:12px; padding:14px 18px; margin-bottom:22px; display:flex; align-items:center; justify-content:space-between;">
                    <div>
                        <div
                            style="font-size:0.68rem; font-weight:700; letter-spacing:1px; color:#1e40af; margin-bottom:2px;">
                            AUTO-CALCULATED POINTS</div>
                        <div id="pcPointsFormula" style="font-size:0.75rem; color:#3b82f6;"></div>
                    </div>
                    <div id="pcPointsValue" style="font-size:2rem; font-weight:900; color:#1e3a8a;"></div>
                </div>

                <!-- Assignment Type -->
                <div style="margin-bottom:18px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:8px;">CHOOSE
                        ASSIGNMENT</label>
                    <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:8px;" id="pcAssignmentGrid">
                        <?php
                        $iconMap = [
                            'Stage' => 'fa-layer-group',
                            'Chrono' => 'fa-clock',
                            'Stats' => 'fa-chart-bar',
                            'Equipment Check' => 'fa-tools',
                            'Quarter Master' => 'fa-box',
                            'Match Director' => 'fa-user-tie'
                        ];
                        foreach ($dynamicMatchAssignments as $ma):
                            $lowerName = strtolower(trim($ma['name']));
                            $aKey = ($lowerName === 'stage') ? 'states' : strtolower(str_replace(' ', '_', $ma['name']));
                            $icon = $iconMap[$ma['name']] ?? 'fa-clipboard-check';
                            ?>
                            <button type="button" class="pc-assign-btn" data-type="<?php echo $aKey; ?>"
                                onclick="pcSelectAssignment('<?php echo $aKey; ?>')"
                                style="padding:10px 6px; border:2px solid #e2e8f0; border-radius:10px; background:#f8fafc; cursor:pointer; display:flex; flex-direction:column; align-items:center; gap:5px; transition:all 0.18s; font-family:inherit;">
                                <i class="fas <?php echo $icon; ?>" style="font-size:1.1rem; color:#64748b;"></i>
                                <span
                                    style="font-size:0.68rem; font-weight:700; color:#475569; letter-spacing:0.5px; text-align:center;"><?php echo htmlspecialchars($ma['name']); ?></span>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Stage Number (only for Stage) -->
                <div id="pcStageFields" style="display:none; margin-bottom:18px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">STAGE
                        NUMBER</label>
                    <input type="text" id="pcStageNumber" placeholder="Enter stage number"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#e2e8f0'">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin:14px 0 6px;">NAME</label>
                    <input type="text" id="pcLroName" placeholder="Enter Name"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#e2e8f0'">
                </div>

                <!-- Officer Name (for non-Stage types) -->
                <div id="pcOfficerFields" style="display:none; margin-bottom:18px;">
                    <label id="pcOfficerLabel"
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">NAME</label>
                    <input type="text" id="pcOfficerName" placeholder="Enter Name"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#e2e8f0'">
                </div>

                <!-- Role -->
                <div style="margin-bottom:22px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">CHOOSE
                        ROLE</label>
                    <select id="pcRole"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.95rem; font-weight:600; outline:none; box-sizing:border-box; background:#fff; font-family:inherit; appearance:none; -webkit-appearance:none; cursor:pointer;"
                        onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#e2e8f0'">
                        <option value="">Select Role...</option>
                        <?php foreach ($dynamicMatchRoles as $mr): ?>
                            <option value="<?php echo htmlspecialchars($mr['name']); ?>">
                                <?php echo htmlspecialchars($mr['name']); ?>
                            </option>
                        <?php endforeach; ?>

                    </select>
                </div>

                <!-- Action Buttons Row 1 -->
                <div style="display:flex; gap:12px;">
                    <button type="button" onclick="closePCModal()"
                        style="flex:1; padding:12px; border:2px solid #1e3a8a; border-radius:12px; background:#fff; color:#1e3a8a; font-weight:700; font-size:0.9rem; cursor:pointer; letter-spacing:0.5px; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#fff'">
                        CANCEL
                    </button>
                    <button type="button" onclick="pcShowOptions()"
                        style="flex:1; padding:12px; border:none; border-radius:12px; background:#1e3a8a; color:#fff; font-weight:700; font-size:0.9rem; cursor:pointer; letter-spacing:0.5px; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#2563eb'" onmouseout="this.style.background='#1e3a8a'">
                        CONFIRM
                    </button>
                </div>
            </div>

            <!-- Step 1.5: Confirm Options -->
            <div id="pcStepOptions" style="display:none; padding:26px 28px 22px;">
                <div id="pcRmWarning"
                    style="display:none; margin-bottom:16px; background:#fff1f2; border:1px solid #fecaca; border-radius:12px; padding:12px; color:#991b1b; font-size:0.8rem; font-weight:600; line-height:1.4;">
                    <i class="fas fa-exclamation-triangle"></i> The Range Master assigned to this match is not an
                    official
                    user of the NROI Portal System. RM Signing is unavailable.
                </div>
                <div style="display:grid; grid-template-columns:1fr; gap:16px;">
                    <button type="button" onclick="pcSubmitReturn()"
                        style="padding:22px; border:2px solid #1e3a8a; border-radius:16px; background:#fff; color:#1e3a8a; cursor:pointer; display:flex; flex-direction:column; align-items:center; gap:10px; transition:all 0.2s;"
                        onmouseover="this.style.background='#eff6ff'; this.style.transform='translateY(-2px)'"
                        onmouseout="this.style.background='#fff'; this.style.transform='translateY(0)'">
                        <i class="fas fa-file-export" style="font-size:1.8rem;"></i>
                        <span style="font-size:1.1rem; font-weight:800; letter-spacing:0.5px;">Return Point Card</span>
                    </button>

                    <button type="button" id="pcRmToggleBtn" onclick="pcRmToggle()"
                        style="padding:22px; border:2px solid #1e3a8a; border-radius:16px; background:#fff; color:#1e3a8a; cursor:pointer; display:flex; flex-direction:column; align-items:center; gap:10px; transition:all 0.2s;"
                        onmouseover="this.style.background='#eff6ff'; this.style.transform='translateY(-2px)'"
                        onmouseout="this.style.background='#fff'; this.style.transform='translateY(0)'">
                        <i class="fas fa-user-shield" style="font-size:1.8rem;"></i>
                        <span id="pcRmToggleText"
                            style="font-size:1.1rem; font-weight:800; letter-spacing:0.5px;">RM</span>
                    </button>

                    <button type="button" onclick="pcBackToStep1FromOptions()"
                        style="margin-top:8px; background:none; border:none; color:#64748b; font-weight:700; font-size:0.85rem; cursor:pointer; text-decoration:underline; font-family:inherit;">
                        Go Back
                    </button>
                </div>
            </div>

            <!-- Step 2: RM Signature -->
            <div id="pcStep2" style="display:none; padding:26px 28px 22px;">
                <div style="margin-bottom:16px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
                        <label style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569;">RANGE
                            MASTER SIGNATURE</label>
                        <button type="button" onclick="pcClearSig()"
                            style="background:none; border:none; color:#ef4444; font-weight:600; font-size:0.82rem; cursor:pointer; font-family:inherit;">Clear</button>
                    </div>
                    <div
                        style="border:1.5px solid #e2e8f0; border-radius:12px; overflow:hidden; height:200px; cursor:crosshair; background:#fff;">
                        <canvas id="pcSigCanvas" width="480" height="200"
                            style="display:block; width:100%; height:200px;"></canvas>
                    </div>
                    <p style="font-size:0.72rem; color:#94a3b8; margin:8px 0 0;"><i class="fas fa-pen-nib"></i> Sign
                        above using your mouse or finger.</p>
                </div>
                <div style="display:flex; gap:12px;">
                    <button type="button" onclick="pcBackToStepOptions()"
                        style="flex:1; padding:12px; border:2px solid #1e3a8a; border-radius:12px; background:#fff; color:#1e3a8a; font-weight:700; font-size:0.9rem; cursor:pointer; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#fff'">
                        BACK
                    </button>
                    <button type="button" onclick="pcSubmit()" id="pcSubmitBtn"
                        style="flex:1; padding:12px; border:none; border-radius:12px; background:#10b981; color:#fff; font-weight:700; font-size:0.9rem; cursor:pointer; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#059669'" onmouseout="this.style.background='#10b981'">
                        SUBMIT
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Hidden form to POST the point card data -->
    <form id="pcSubmitForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="save_point_card_assignment">
        <input type="hidden" name="pc_match_id" id="pcFMatch">
        <input type="hidden" name="pc_redirect_match_id" id="pcFRedirectMatch">
        <input type="hidden" name="pc_user_id" id="pcFUser">
        <input type="hidden" name="pc_assignment_type" id="pcFType">
        <input type="hidden" name="pc_role" id="pcFRole">
        <input type="hidden" name="pc_officer_name" id="pcFOfficer">
        <input type="hidden" name="pc_stage_number" id="pcFStage">
        <input type="hidden" name="pc_rm_signature" id="pcFSig">
    </form>

    <!-- Hidden form to POST the return point card data -->
    <form id="rpSubmitForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="return_point_card">
        <input type="hidden" name="rp_match_id" id="rpFMatch">
        <input type="hidden" name="rp_redirect_match_id" id="rpFRedirectMatch">
        <input type="hidden" name="rp_user_id" id="rpFUser">
        <input type="hidden" name="rp_assignment_type" id="rpFType">
        <input type="hidden" name="rp_role" id="rpFRole">
        <input type="hidden" name="rp_officer_name" id="rpFOfficer">
        <input type="hidden" name="rp_stage_number" id="rpFStage">
        <input type="hidden" name="rp_lro_name" id="rpFLro">
    </form>

    <!-- Hidden form to POST the terminate action -->
    <form id="terminateSubmitForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="terminate_returned_point_card">
        <input type="hidden" name="match_id" id="termFMatch">
        <input type="hidden" name="user_id" id="termFUser">
    </form>

    <form id="rmToggleSubmitForm" method="POST" style="display:none;">
        <input type="hidden" name="action" id="rmFAction" value="request_rm_signing">
        <input type="hidden" name="match_id" id="rmFMatch">
        <input type="hidden" name="user_id" id="rmFUser">
        <input type="hidden" name="assignment_type" id="rmFType">
        <input type="hidden" name="role" id="rmFRole">
        <input type="hidden" name="officer_name" id="rmFOfficer">
        <input type="hidden" name="stage_number" id="rmFStage">
        <input type="hidden" name="lro_name" id="rmFLro">
    </form>

    <!-- Return Point Card Modal -->
    <div id="returnPointCardModal"
        style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:9999; align-items:center; justify-content:center; padding:16px;">
        <div
            style="background:#fff; border-radius:20px; width:100%; max-width:480px; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
            <!-- Header -->
            <div
                style="background:linear-gradient(135deg,#f59e0b,#d97706); padding:22px 24px 16px; border-radius:20px 20px 0 0;">
                <div
                    style="color:#fff; font-size:0.72rem; font-weight:700; letter-spacing:1.2px; opacity:0.85; margin-bottom:4px;">
                    RETURN POINT CARD</div>
                <div id="rpModalName" style="color:#fff; font-size:1.15rem; font-weight:800;"></div>
                <div id="rpModalMatch" style="color:rgba(255,255,255,0.8); font-size:0.85rem; margin-top:2px;"></div>
                <div
                    style="margin-top:10px; background:rgba(0,0,0,0.15); border-radius:10px; padding:8px 12px; font-size:0.75rem; color:#fff; opacity:0.9;">
                    <i class="fas fa-info-circle"></i> This will delete the existing point card and re-display the Fill
                    Point Card on the user&rsquo;s app dashboard. The user&rsquo;s RM must re-sign.
                </div>
            </div>

            <!-- Step 1: Assignment Details -->
            <div id="rpStep1" style="padding:26px 28px 22px;">
                <!-- Assignment Type -->
                <div style="margin-bottom:20px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:10px;">ASSIGNMENT
                        TYPE</label>
                    <div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px;">
                        <?php
                        $iconMapRP = [
                            'Stage' => 'fa-flag',
                            'Chrono' => 'fa-stopwatch',
                            'Stats' => 'fa-chart-bar',
                            'Equipment Check' => 'fa-tools',
                            'Quarter Master' => 'fa-box',
                            'Match Director' => 'fa-user-tie'
                        ];
                        foreach ($dynamicMatchAssignments as $ma):
                            $lowerNameRP = strtolower(trim($ma['name']));
                            $aKey = ($lowerNameRP === 'stage') ? 'states' : strtolower(str_replace(' ', '_', $ma['name']));
                            $icon = $iconMapRP[$ma['name']] ?? 'fa-clipboard-check';
                            ?>
                            <button type="button" class="rp-assign-btn" data-type="<?php echo $aKey; ?>"
                                style="padding:10px 6px; border:2px solid #e2e8f0; border-radius:12px; background:#f8fafc; cursor:pointer; display:flex; flex-direction:column; align-items:center; gap:5px; transition:all 0.18s; font-family:inherit;"
                                onclick="rpSelectAssignment('<?php echo $aKey; ?>')">
                                <i class="fas <?php echo $icon; ?>" style="font-size:1.2rem; color:#64748b;"></i>
                                <span
                                    style="font-size:0.68rem; font-weight:700; color:#475569;"><?php echo strtoupper(htmlspecialchars($ma['name'])); ?></span>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Stage Fields -->
                <div id="rpStageFields" style="display:none; margin-bottom:18px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">STAGE
                        NUMBER</label>
                    <input type="text" id="rpStageNumber" placeholder="Enter stage number"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#f59e0b'" onblur="this.style.borderColor='#e2e8f0'">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin:14px 0 6px;">NAME</label>
                    <input type="text" id="rpLroName" placeholder="Enter Name"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#f59e0b'" onblur="this.style.borderColor='#e2e8f0'">
                </div>

                <!-- Officer Name (non-Stage) -->
                <div id="rpOfficerFields" style="display:none; margin-bottom:18px;">
                    <label id="rpOfficerLabel"
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">NAME</label>
                    <input type="text" id="rpOfficerName" placeholder="Enter Name"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:1rem; font-weight:600; outline:none; box-sizing:border-box; font-family:inherit;"
                        onfocus="this.style.borderColor='#f59e0b'" onblur="this.style.borderColor='#e2e8f0'">
                </div>

                <!-- Role -->
                <div style="margin-bottom:22px;">
                    <label
                        style="font-size:0.72rem; font-weight:700; letter-spacing:1px; color:#475569; display:block; margin-bottom:6px;">CHOOSE
                        ROLE</label>
                    <select id="rpRole"
                        style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.95rem; font-weight:600; outline:none; box-sizing:border-box; background:#fff; font-family:inherit; appearance:none; -webkit-appearance:none; cursor:pointer;"
                        onfocus="this.style.borderColor='#f59e0b'" onblur="this.style.borderColor='#e2e8f0'">
                        <option value="">Select Role...</option>
                        <?php foreach ($dynamicMatchRoles as $mr): ?>
                            <option value="<?php echo htmlspecialchars($mr['name']); ?>">
                                <?php echo htmlspecialchars($mr['name']); ?>
                            </option>
                        <?php endforeach; ?>

                    </select>
                </div>

                <!-- Action Buttons -->
                <div style="display:flex; gap:12px;">
                    <button type="button" onclick="closeRPModal()"
                        style="flex:1; padding:12px; border:2px solid #64748b; border-radius:12px; background:#fff; color:#64748b; font-weight:700; font-size:0.9rem; cursor:pointer; letter-spacing:0.5px; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='#fff'">
                        CANCEL
                    </button>
                    <button type="button" onclick="rpConfirm()"
                        style="flex:1; padding:12px; border:none; border-radius:12px; background:#f59e0b; color:#fff; font-weight:700; font-size:0.9rem; cursor:pointer; letter-spacing:0.5px; font-family:inherit; transition:background 0.18s;"
                        onmouseover="this.style.background='#d97706'" onmouseout="this.style.background='#f59e0b'">
                        RETURN POINT CARD
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // ---- Point Card Edit Modal Logic ----
        let _pcUserId = null, _pcMatchId = null, _pcType = null, _pcIsRmEnabled = 0, _pcMatchRmId = null;
        let _pcSigDrawing = false, _pcSigCtx = null, _pcSigCanvas = null, _pcHasSig = false;

        function openPointCardEdit(userId, userName, matchId, matchName, pts, level, disciplines, isRmEnabled, matchRmId, currentType, currentRole, stageNum, lroName, officerName) {
            _pcUserId = userId;
            _pcMatchId = matchId;
            _pcType = null;
            _pcIsRmEnabled = isRmEnabled;
            _pcMatchRmId = matchRmId;

            document.getElementById('pcModalName').textContent = userName;
            document.getElementById('pcModalMatch').textContent = matchName;
            document.getElementById('pcPointsValue').textContent = pts;
            document.getElementById('pcPointsFormula').textContent = level + ' × ' + (disciplines || '1 discipline');

            // Reset
            document.querySelectorAll('.pc-assign-btn').forEach(b => {
                b.style.borderColor = '#e2e8f0'; b.style.background = '#f8fafc';
                b.querySelector('i').style.color = '#64748b';
                b.querySelector('span').style.color = '#475569';
            });
            document.getElementById('pcStageFields').style.display = 'none';
            document.getElementById('pcOfficerFields').style.display = 'none';

            // Pre-fill existing data
            if (currentType) {
                // Map "Stage" profile text to "states" internal key if needed
                let typeKey = currentType.toLowerCase();
                if (typeKey === 'stage') typeKey = 'states';
                pcSelectAssignment(typeKey);
            }

            document.getElementById('pcStageNumber').value = stageNum || '';
            document.getElementById('pcLroName').value = lroName || '';
            document.getElementById('pcOfficerName').value = officerName || '';
            document.getElementById('pcRole').value = currentRole || '';
            document.getElementById('pcStep1').style.display = 'block';
            document.getElementById('pcStepOptions').style.display = 'none';
            document.getElementById('pcStep2').style.display = 'none';

            // RM Toggle UI
            const rmText = document.getElementById('pcRmToggleText');
            const rmBtn = document.getElementById('pcRmToggleBtn');
            if (_pcIsRmEnabled == 1) {
                rmText.textContent = 'Terminate RM Signing';
                rmBtn.style.background = '#fee2e2';
                rmBtn.style.color = '#991b1b';
                rmBtn.style.borderColor = '#991b1b';
            } else {
                rmText.textContent = 'RM';
                rmBtn.style.background = '#fff';
                rmBtn.style.color = '#1e3a8a';
                rmBtn.style.borderColor = '#1e3a8a';
            }

            // Handle Non-System RM Warning
            const rmWarning = document.getElementById('pcRmWarning');
            if (!_pcMatchRmId || _pcMatchRmId == 0 || _pcMatchRmId == '0' || _pcMatchRmId == 'null') {
                rmBtn.style.display = 'none';
                rmWarning.style.display = 'block';
            } else {
                rmBtn.style.display = 'flex';
                rmWarning.style.display = 'none';
            }

            const modal = document.getElementById('pointCardEditModal');
            modal.style.display = 'flex';
        }

        function pcRmToggle() {
            const action = (_pcIsRmEnabled == 1) ? 'terminate_rm_signing' : 'request_rm_signing';
            const confirmMsg = (_pcIsRmEnabled == 1)
                ? 'Are you sure you want to terminate RM signing for this user? This record will disappear from the RM app dashboard.'
                : 'Are you sure you want to request RM signing for this user? This record will be displayed on the RM app dashboard for signing.';

            if (!confirm(confirmMsg)) return;

            if (action === 'request_rm_signing') {
                const role = document.getElementById('pcRole').value;
                if (!_pcType) { alert('Please choose an assignment type.'); return; }
                if (!role) { alert('Please choose a role.'); return; }

                document.getElementById('rmFType').value = _pcType;
                document.getElementById('rmFRole').value = role;

                if (_pcType === 'states') {
                    const stage = document.getElementById('pcStageNumber').value.trim();
                    const lro = document.getElementById('pcLroName').value.trim();
                    if (!stage || !lro) { alert('Stage number and LRO name are required.'); return; }
                    document.getElementById('rmFStage').value = stage;
                    document.getElementById('rmFLro').value = lro;
                    document.getElementById('rmFOfficer').value = '';
                } else {
                    const officer = document.getElementById('pcOfficerName').value.trim();
                    if (!officer) { alert('Officer name is required.'); return; }
                    document.getElementById('rmFOfficer').value = officer;
                    document.getElementById('rmFStage').value = '';
                    document.getElementById('rmFLro').value = '';
                }
            }

            document.getElementById('rmFAction').value = action;
            document.getElementById('rmFMatch').value = _pcMatchId;
            document.getElementById('rmFUser').value = _pcUserId;
            document.getElementById('rmToggleSubmitForm').submit();
        }

        function closePCModal() {
            document.getElementById('pointCardEditModal').style.display = 'none';
        }

        function pcSelectAssignment(type) {
            _pcType = type;
            document.querySelectorAll('.pc-assign-btn').forEach(b => {
                const isActive = b.dataset.type === type;
                b.style.borderColor = isActive ? '#2563eb' : '#e2e8f0';
                b.style.background = isActive ? '#eff6ff' : '#f8fafc';
                b.querySelector('i').style.color = isActive ? '#2563eb' : '#64748b';
                b.querySelector('span').style.color = isActive ? '#1e3a8a' : '#475569';
            });
            const stageF = document.getElementById('pcStageFields');
            const officerF = document.getElementById('pcOfficerFields');
            if (type === 'states') {
                stageF.style.display = 'block';
                officerF.style.display = 'none';
            } else {
                stageF.style.display = 'none';
                officerF.style.display = 'block';
                const labels = {
                    chrono: 'CHRONO',
                    stats: 'STATS',
                    equipment_check: 'EQUIPMENT CHECK',
                    quarter_master: 'QUARTER MASTER'
                };
                const placeholders = {
                    chrono: 'Enter Name',
                    stats: 'Enter Name',
                    equipment_check: 'Enter Name',
                    quarter_master: 'Enter Name'
                };
                // Add dynamic types
                <?php foreach ($dynamicMatchAssignments as $ma):
                    $key = strtolower(str_replace(' ', '_', $ma['name']));
                    ?>
                    labels['<?php echo $key; ?>'] = '<?php echo strtoupper(addslashes($ma['name'])); ?>';
                    placeholders['<?php echo $key; ?>'] = 'Enter Name';
                <?php endforeach; ?>

                document.getElementById('pcOfficerLabel').textContent = labels[type] || type.replace(/_/g, ' ').toUpperCase();
                document.getElementById('pcOfficerName').placeholder = placeholders[type] || 'Enter Name';
            }
        }

        function pcShowOptions() {
            if (!_pcType) { alert('Please choose an assignment type.'); return; }
            const role = document.getElementById('pcRole').value;
            if (!role) { alert('Please choose a role.'); return; }
            if (_pcType === 'states') {
                if (!document.getElementById('pcStageNumber').value.trim()) { alert('Stage number is required.'); return; }
                if (!document.getElementById('pcLroName').value.trim()) { alert('LRO name is required.'); return; }
            } else {
                if (!document.getElementById('pcOfficerName').value.trim()) { alert('Officer name is required.'); return; }
            }
            document.getElementById('pcStep1').style.display = 'none';
            document.getElementById('pcStepOptions').style.display = 'block';
            document.getElementById('pcStep2').style.display = 'none';
        }

        function pcBackToStep1FromOptions() {
            document.getElementById('pcStep1').style.display = 'block';
            document.getElementById('pcStepOptions').style.display = 'none';
        }

        function pcGoToSignature() {
            document.getElementById('pcStepOptions').style.display = 'none';
            document.getElementById('pcStep2').style.display = 'block';
            pcInitSig();
        }

        function pcBackToStepOptions() {
            document.getElementById('pcStepOptions').style.display = 'block';
            document.getElementById('pcStep2').style.display = 'none';
        }

        function pcInitSig() {
            _pcSigCanvas = document.getElementById('pcSigCanvas');
            // Resize canvas to actual display size
            _pcSigCanvas.width = _pcSigCanvas.offsetWidth || 480;
            _pcSigCanvas.height = _pcSigCanvas.offsetHeight || 200;
            _pcSigCtx = _pcSigCanvas.getContext('2d');
            _pcSigCtx.strokeStyle = '#1e3a8a';
            _pcSigCtx.lineWidth = 3;
            _pcSigCtx.lineCap = 'round';
            _pcHasSig = false;

            // Mouse
            _pcSigCanvas.onmousedown = (e) => { _pcSigDrawing = true; _pcSigCtx.beginPath(); _pcSigCtx.moveTo(...pcPos(e)); };
            _pcSigCanvas.onmousemove = (e) => { if (!_pcSigDrawing) return; _pcSigCtx.lineTo(...pcPos(e)); _pcSigCtx.stroke(); _pcHasSig = true; };
            _pcSigCanvas.onmouseup = _pcSigCanvas.onmouseleave = () => _pcSigDrawing = false;
            // Touch
            _pcSigCanvas.ontouchstart = (e) => { e.preventDefault(); _pcSigDrawing = true; _pcSigCtx.beginPath(); _pcSigCtx.moveTo(...pcPos(e.touches[0])); };
            _pcSigCanvas.ontouchmove = (e) => { e.preventDefault(); if (!_pcSigDrawing) return; _pcSigCtx.lineTo(...pcPos(e.touches[0])); _pcSigCtx.stroke(); _pcHasSig = true; };
            _pcSigCanvas.ontouchend = () => _pcSigDrawing = false;
        }
        function pcPos(e) {
            const r = _pcSigCanvas.getBoundingClientRect();
            const scX = _pcSigCanvas.width / r.width;
            const scY = _pcSigCanvas.height / r.height;
            return [(e.clientX - r.left) * scX, (e.clientY - r.top) * scY];
        }
        function pcClearSig() {
            if (_pcSigCtx) _pcSigCtx.clearRect(0, 0, _pcSigCanvas.width, _pcSigCanvas.height);
            _pcHasSig = false;
        }

        function pcSubmit() {
            if (!_pcHasSig) { alert('Please provide the Range Master\'s signature.'); return; }
            const sigData = _pcSigCanvas.toDataURL('image/png');
            const btn = document.getElementById('pcSubmitBtn');
            btn.textContent = 'Saving...';
            btn.disabled = true;

            document.getElementById('pcFMatch').value = _pcMatchId;
            document.getElementById('pcFRedirectMatch').value = _pcMatchId;
            document.getElementById('pcFUser').value = _pcUserId;
            document.getElementById('pcFType').value = _pcType;
            document.getElementById('pcFRole').value = document.getElementById('pcRole').value;
            document.getElementById('pcFSig').value = sigData;
            if (_pcType === 'states') {
                document.getElementById('pcFStage').value = document.getElementById('pcStageNumber').value.trim();
                document.getElementById('pcFOfficer').value = document.getElementById('pcLroName').value.trim();
            } else {
                document.getElementById('pcFStage').value = '';
                document.getElementById('pcFOfficer').value = document.getElementById('pcOfficerName').value.trim();
            }
            document.getElementById('pcSubmitForm').submit();
        }

        function pcSubmitReturn() {
            if (!_pcType) { alert('Please choose an assignment type.'); return; }
            const role = document.getElementById('pcRole').value;
            if (!role) { alert('Please choose a role.'); return; }

            const isStage = (_pcType === 'states');
            let stageNum = '', lroName = '', officerName = '';

            if (isStage) {
                stageNum = document.getElementById('pcStageNumber').value.trim();
                lroName = document.getElementById('pcLroName').value.trim();
                if (!stageNum) { alert('Stage number is required.'); return; }
                if (!lroName) { alert('LRO name is required.'); return; }
            } else {
                officerName = document.getElementById('pcOfficerName').value.trim();
                if (!officerName) { alert('Officer name is required.'); return; }
            }
            if (!confirm('This will provide official assignment details and show the Fill Point Card on the user dashboard. Continue?')) return;

            document.getElementById('rpFMatch').value = _pcMatchId;
            document.getElementById('rpFRedirectMatch').value = _pcMatchId;
            document.getElementById('rpFUser').value = _pcUserId;
            document.getElementById('rpFType').value = _pcType;
            document.getElementById('rpFRole').value = role;

            if (isStage) {
                document.getElementById('rpFStage').value = stageNum;
                document.getElementById('rpFLro').value = lroName;
                document.getElementById('rpFOfficer').value = '';
            } else {
                document.getElementById('rpFOfficer').value = officerName;
                document.getElementById('rpFStage').value = '';
                document.getElementById('rpFLro').value = '';
            }

            document.getElementById('rpSubmitForm').submit();
        }

        // Close modal on outside click
        document.getElementById('pointCardEditModal').addEventListener('click', function (e) {
            if (e.target === this) closePCModal();
        });

        // ---- Return Point Card Modal Logic ----
        let _rpUserId = null, _rpMatchId = null, _rpType = null;

        function openReturnPointCard(userId, userName, matchId, matchName) {
            _rpUserId = userId;
            _rpMatchId = matchId;
            _rpType = null;

            document.getElementById('rpModalName').textContent = userName;
            document.getElementById('rpModalMatch').textContent = matchName;

            // Reset form state
            document.querySelectorAll('.rp-assign-btn').forEach(b => {
                b.style.borderColor = '#e2e8f0';
                b.style.background = '#f8fafc';
                const ic = b.querySelector('i');
                const sp = b.querySelector('span');
                if (ic) ic.style.color = '#64748b';
                if (sp) sp.style.color = '#475569';
            });
            document.getElementById('rpStageFields').style.display = 'none';
            document.getElementById('rpOfficerFields').style.display = 'none';
            document.getElementById('rpStageNumber').value = '';
            document.getElementById('rpLroName').value = '';
            document.getElementById('rpOfficerName').value = '';
            document.getElementById('rpRole').value = '';

            const modal = document.getElementById('returnPointCardModal');
            modal.style.display = 'flex';
        }

        function closeRPModal() {
            document.getElementById('returnPointCardModal').style.display = 'none';
        }

        function rpSelectAssignment(type) {
            _rpType = type;

            // Highlight selected button
            document.querySelectorAll('.rp-assign-btn').forEach(b => {
                const isSelected = b.dataset.type === type;
                b.style.borderColor = isSelected ? '#f59e0b' : '#e2e8f0';
                b.style.background = isSelected ? '#fffbeb' : '#f8fafc';
                const ic = b.querySelector('i');
                const sp = b.querySelector('span');
                if (ic) ic.style.color = isSelected ? '#f59e0b' : '#64748b';
                if (sp) sp.style.color = isSelected ? '#92400e' : '#475569';
            });

            // Show/hide appropriate fields
            const isStage = (type === 'states');
            document.getElementById('rpStageFields').style.display = isStage ? 'block' : 'none';
            document.getElementById('rpOfficerFields').style.display = !isStage ? 'block' : 'none';

            // Update officer label
            const labelMap = {
                'chrono': 'CHRONO OFFICER NAME',
                'stats': 'STATS OFFICER NAME',
                'equipment_check': 'EQUIPMENT CHECK OFFICER NAME',
                'quarter_master': 'QUARTER MASTER NAME',
                'range_master': 'DEPUTY/RANGE MASTER NAME',
            };
            // Add dynamic types
            <?php foreach ($dynamicMatchAssignments as $ma):
                $key = strtolower(str_replace(' ', '_', $ma['name']));
                ?>
                labelMap['<?php echo $key; ?>'] = '<?php echo strtoupper(addslashes($ma['name'])); ?> OFFICER NAME';
            <?php endforeach; ?>

            const lbl = document.getElementById('rpOfficerLabel');
            if (lbl) lbl.textContent = labelMap[type] || (type.replace(/_/g, ' ').toUpperCase() + ' NAME');
        }

        function rpConfirm() {
            if (!_rpType) { alert('Please select an assignment type.'); return; }
            if (!document.getElementById('rpRole').value) { alert('Please select a role.'); return; }

            const isStage = (_rpType === 'states');
            if (isStage) {
                if (!document.getElementById('rpStageNumber').value.trim()) { alert('Please enter stage number.'); return; }
                if (!document.getElementById('rpLroName').value.trim()) { alert('Please enter LRO name.'); return; }
            } else {
                if (!document.getElementById('rpOfficerName').value.trim()) { alert('Please enter officer name.'); return; }
            }
            if (!confirm('This will provide official assignment details and show the Fill Point Card on the user dashboard. Continue?')) return;

            document.getElementById('rpFMatch').value = _rpMatchId;
            document.getElementById('rpFRedirectMatch').value = _rpMatchId;
            document.getElementById('rpFUser').value = _rpUserId;
            document.getElementById('rpFType').value = _rpType;
            document.getElementById('rpFRole').value = document.getElementById('rpRole').value;

            if (isStage) {
                document.getElementById('rpFStage').value = document.getElementById('rpStageNumber').value.trim();
                document.getElementById('rpFLro').value = document.getElementById('rpLroName').value.trim();
                document.getElementById('rpFOfficer').value = '';
            } else {
                document.getElementById('rpFOfficer').value = document.getElementById('rpOfficerName').value.trim();
                document.getElementById('rpFStage').value = '';
                document.getElementById('rpFLro').value = '';
            }

            document.getElementById('rpSubmitForm').submit();
        }

        // Terminate function
        function terminateReturnedPointCard(userId, matchId, userName) {
            if (!confirm(`Are you sure you want to terminate the returned point card for ${userName}? This will remove it from their dashboard.`)) return;
            document.getElementById('termFMatch').value = matchId;
            document.getElementById('termFUser').value = userId;
            document.getElementById('terminateSubmitForm').submit();
        }

        function terminateRMSigning(userId, matchId, userName) {
            if (!confirm(`Are you sure you want to terminate RM signing for ${userName}? This record will disappear from the RM app dashboard.`)) return;
            document.getElementById('rmFAction').value = 'terminate_rm_signing';
            document.getElementById('rmFMatch').value = matchId;
            document.getElementById('rmFUser').value = userId;
            document.getElementById('rmToggleSubmitForm').submit();
        }

        // Close return modal on outside click
        document.getElementById('returnPointCardModal').addEventListener('click', function (e) {
            if (e.target === this) closeRPModal();
        });
    </script>
</body>

</html>