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

$is_admin = isset($_SESSION['admin_id']);
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
$is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
$is_officer_role = $is_ac || $is_aac;

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

// Allow admin and AC/AAC only
if (!$is_admin && !$is_officer_role) {
    if ($is_special) {
        header("Location: ../officer/dashboard.php");
    } else {
        header("Location: ../index.php");
    }
    exit;
}

// Status display
function status_display_label($status)
{
    $s = strtolower(trim((string) ($status ?? '')));
    $labels = [
        'pending' => 'Pending',
        'approved' => 'Approved',
        'standby' => 'Standby/Waiting',
        'rejected' => 'Rejected/Declined',
        'declined' => 'Rejected/Declined',
        'withdrawn' => 'Withdrawn',
        'deactivated' => 'Withdrawn'
    ];
    return $labels[$s] ?? ucfirst($status);
}

// Helper function to log activities
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]);
}

// Helper function to get history for a signification
function getSignificationHistory($pdo, $significationId)
{
    if (!$significationId)
        return '';

    $stmt = $pdo->prepare("
        SELECT description, created_at, performed_by_role, status 
        FROM activity_logs 
        WHERE reference_type = 'match_signification' AND reference_id = ? 
        ORDER BY created_at ASC
    ");
    $stmt->execute([$significationId]);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $historyHtml = '';
    foreach ($logs as $log) {
        $timestamp = date('M d, Y h:i A', strtotime($log['created_at']));
        $displayText = htmlspecialchars(trim(preg_replace('/\s+for[:\s].*/si', '', $log['description'])));

        $historyHtml .= "<div style='font-size: 0.75rem; color: #475569; margin-bottom: 4px; line-height: 1.2;'>
                            <i class='far fa-clock' style='font-size: 0.65rem; opacity: 0.6;'></i> $displayText at $timestamp
                         </div>";
    }
    return $historyHtml;
}

// Helper function to get user total points
function getUserTotalPoints($pdo, $userId)
{
    $stmt = $pdo->prepare("
        SELECT 
            (SELECT COALESCE(SUM(mp.points), 0) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = ?) + 
            (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = ?) as total_points
    ");
    $stmt->execute([$userId, $userId]);
    return (float) $stmt->fetchColumn();
}

// Handle request actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        $reviewedBy = $is_admin ? null : $_SESSION['user_id'];
        $performedByRole = $is_admin ? 'ADMIN' : ($is_ac ? 'AC' : ($is_aac ? 'AAC' : 'UNKNOWN'));
        $performedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
        $performedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;
        $performerName = $is_admin ? 'System Admin' : ($_SESSION['name'] ?? 'Officer');

        if ($_POST['action'] === 'approve_withdrawal') {
            $significationId = $_POST['signification_id'];
            $deductionPoints = isset($_POST['deduction_points']) ? (float) $_POST['deduction_points'] : 0;

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location,
                       (SELECT 1 FROM match_points mp WHERE mp.match_id = ms.match_id AND mp.user_id = ms.user_id AND mp.rm_signature IS NOT NULL AND mp.rm_signature != '') as is_served
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            if (!empty($sigInfo['is_served'])) {
                $_SESSION['error_msg'] = "Cannot approve withdrawal: Member has already served this match.";
                header("Location: request.php?tab=withdrawed");
                exit;
            }

            $pdo->beginTransaction();
            $stmt = $pdo->prepare("UPDATE match_significations SET status='withdrawn', reviewed_by=?, reviewed_at=NOW() WHERE id=?");
            $stmt->execute([$reviewedBy, $significationId]);

            // Handle point deduction (demerit)
            if ($deductionPoints > 0) {
                $negativePoints = -$deductionPoints;
                $stmtPts = $pdo->prepare("INSERT INTO match_points (match_id, user_id, points, rm_signature) VALUES (?, ?, ?, 'DEMERIT') ON DUPLICATE KEY UPDATE points = points + ?");
                $stmtPts->execute([$sigInfo['match_id'], $sigInfo['user_id'], $negativePoints, $negativePoints]);
            }
            $pdo->commit();

            // Log activity
            $description = "Approved withdrawal by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, 'withdrawn', $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                // Include the user's original withdrawal reason in the email
                $withdrawalReason = trim($sigInfo['withdrawal_reason'] ?? '');

                // Get remaining points for email
                $remainingPoints = getUserTotalPoints($pdo, $sigInfo['user_id']);

                sendMatchNotification($sigInfo['email'], $fullName, 'Withdrawn', $sigInfo['match_name'], $schedule, $sigInfo['location'], $withdrawalReason, $performedByRole, $deductionPoints, $remainingPoints);
            }

            header("Location: request.php?tab=signified&success=withdrawn&match_id=" . ($sigInfo['match_id'] ?? ''));
            exit;
        } elseif ($_POST['action'] === 'reject_withdrawal') {
            $significationId = $_POST['signification_id'];
            $remarks = $_POST['remarks'] ?? '';

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location 
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            // Return to previous status or default to approved if not set
            $prevStatus = $sigInfo['previous_status'] ?? 'approved';

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

            // Log activity
            $description = "Rejected withdrawal by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, $prevStatus, $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                // Pass officer rejection reason, role, and restored status to email
                sendMatchNotification($sigInfo['email'], $fullName, 'Withdrawal Rejected', $sigInfo['match_name'], $schedule, $sigInfo['location'], $remarks, $performedByRole, 0, null, $prevStatus);
            }

            header("Location: request.php?tab=withdrawed&success=rejected");
            exit;
        } elseif ($_POST['action'] === 'approve_signification') {
            $significationId = $_POST['signification_id'];
            $remarks = $_POST['remarks'] ?? '';

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location, m.is_local, m.is_retroactive 
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            // Server-side guard: AC/AAC cannot approve a regular match signification
            $isRegular = !($sigInfo['is_local'] || $sigInfo['is_retroactive']);
            if ($is_officer_role && $isRegular) {
                $_SESSION['error_msg'] = 'You are not authorized to approve regular match significations. Only the assigned Range Master can do this.';
                header('Location: request.php?tab=signified');
                exit;
            }

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

            // Log activity
            $description = "Approved by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, 'approved', $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                sendMatchNotification($sigInfo['email'], $fullName, 'Approved', $sigInfo['match_name'], $schedule, $sigInfo['location']);
            }

            header("Location: request.php?tab=signified&success=approved");
            exit;
        } elseif ($_POST['action'] === 'standby_signification') {
            $significationId = $_POST['signification_id'];
            $remarks = $_POST['remarks'] ?? '';

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location, m.is_local, m.is_retroactive 
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            // Server-side guard: AC/AAC cannot set standby for a regular match signification
            $isRegular = !($sigInfo['is_local'] || $sigInfo['is_retroactive']);
            if ($is_officer_role && $isRegular) {
                $_SESSION['error_msg'] = 'You are not authorized to set standby for regular match significations. Only the assigned Range Master can do this.';
                header('Location: request.php?tab=signified');
                exit;
            }

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

            // Log activity
            $description = "Standby by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, 'standby', $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                sendMatchNotification($sigInfo['email'], $fullName, 'Standby', $sigInfo['match_name'], $schedule, $sigInfo['location']);
            }

            header("Location: request.php?tab=signified&success=standby");
            exit;
        } elseif ($_POST['action'] === 'reject_signification') {
            $significationId = $_POST['signification_id'];
            $remarks = $_POST['remarks'] ?? '';

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location, m.is_local, m.is_retroactive 
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            // Server-side guard: AC/AAC cannot reject a regular match signification
            $isRegular = !($sigInfo['is_local'] || $sigInfo['is_retroactive']);
            if ($is_officer_role && $isRegular) {
                $_SESSION['error_msg'] = 'You are not authorized to reject regular match significations. Only the assigned Range Master can do this.';
                header('Location: request.php?tab=signified');
                exit;
            }

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

            // Log activity
            $description = "Rejected by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, 'declined', $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification — include reject reason and who rejected
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                sendMatchNotification($sigInfo['email'], $fullName, 'Declined', $sigInfo['match_name'], $schedule, $sigInfo['location'], $remarks, $performedByRole);
            }

            header("Location: request.php?tab=signified&success=rejected");
            exit;
        } elseif ($_POST['action'] === 'direct_withdraw') {
            $significationId = $_POST['signification_id'];
            $remarks = $_POST['remarks'] ?? 'Directly withdrawn by officer';
            $deductionPoints = isset($_POST['deduction_points']) ? (float) $_POST['deduction_points'] : 0;

            // Get signification info for logging and email
            $stmtInfo = $pdo->prepare("
                SELECT ms.*, u.first_name, u.last_name, u.nroi_id, u.email, m.match_name, m.start_date, m.end_date, m.location,
                       (SELECT 1 FROM match_points mp WHERE mp.match_id = ms.match_id AND mp.user_id = ms.user_id AND mp.rm_signature IS NOT NULL AND mp.rm_signature != '') as is_served
                FROM match_significations ms
                JOIN users u ON ms.user_id = u.id
                JOIN match_schedules m ON ms.match_id = m.id
                WHERE ms.id = ?
            ");
            $stmtInfo->execute([$significationId]);
            $sigInfo = $stmtInfo->fetch(PDO::FETCH_ASSOC);

            if (!empty($sigInfo['is_served'])) {
                $_SESSION['error_msg'] = "Cannot withdraw member: Member has already served this match.";
                header("Location: request.php?tab=signified");
                exit;
            }

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

            // Handle point deduction (demerit)
            if ($deductionPoints > 0) {
                $negativePoints = -$deductionPoints;
                $stmtPts = $pdo->prepare("INSERT INTO match_points (match_id, user_id, points, rm_signature) VALUES (?, ?, ?, 'DEMERIT') ON DUPLICATE KEY UPDATE points = points + ?");
                $stmtPts->execute([$sigInfo['match_id'], $sigInfo['user_id'], $negativePoints, $negativePoints]);
            }
            $pdo->commit();

            // Log activity
            $description = "Withdrawn by $performerName ($performedByRole)";
            logActivity($pdo, 'match_signification', $significationId, $description, 'withdrawn', $performedByRole, $performedByUserId, $performedByAdminId);

            // Send Email Notification
            if (!empty($sigInfo['email'])) {
                $fullName = trim(($sigInfo['first_name'] ?? '') . ' ' . ($sigInfo['last_name'] ?? ''));
                $sDate = strtotime($sigInfo['start_date']);
                $eDate = strtotime($sigInfo['end_date']);
                $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                    ? date('M d, Y', $sDate)
                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

                // Pass officer's manual withdrawal reason and role to email
                $withdrawalReason = $remarks;

                // Get remaining points for email
                $remainingPoints = getUserTotalPoints($pdo, $sigInfo['user_id']);

                sendMatchNotification($sigInfo['email'], $fullName, 'Withdrawn', $sigInfo['match_name'], $schedule, $sigInfo['location'], $withdrawalReason, $performedByRole, $deductionPoints, $remainingPoints);
            }

            header("Location: request.php?tab=signified&success=withdrawn&match_id=" . ($sigInfo['match_id'] ?? ''));
            exit;
        }
    } catch (PDOException $e) {
        $_SESSION['error_msg'] = "Action failed: " . $e->getMessage();
        header("Location: request.php");
        exit;
    }
}

// Get active tab from URL. Default to signified.
$activeTab = $_GET['tab'] ?? 'signified';
if (!in_array($activeTab, ['signified', 'withdrawed'], true)) {
    $activeTab = 'signified';
}

// Check for missing columns in match_schedules to prevent crashes
$columns = $pdo->query("DESCRIBE match_schedules")->fetchAll(PDO::FETCH_COLUMN);
$hasRmName = in_array('rm_name', $columns);
$hasRoLimit = in_array('ro_limit', $columns);

$rmSelect = $hasRmName ? "m.rm_name" : "'' as rm_name";
$roSelect = $hasRoLimit ? "m.ro_limit" : "0 as ro_limit";

// Fetch signified matches
if ($is_admin) {
    $stmt = $pdo->prepare("
        SELECT 
            ms.*,
            u.nroi_id, u.first_name, u.last_name, u.role, u.rank, u.area,
            m.id as match_id, m.match_name, m.start_date, m.end_date, m.location, m.match_level, m.range_master, m.is_local, m.is_retroactive, $rmSelect, $roSelect,
            (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,
            (SELECT COUNT(*) FROM match_significations WHERE match_id = m.id AND status = 'approved') as approved_count,
            (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
            CASE 
                WHEN mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' THEN 'served'
                WHEN ms.status != 'approved' THEN NULL
                ELSE 'incomplete'
            END as match_completion_status
        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 match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
        WHERE ms.status IN ('pending', 'approved', 'standby', 'declined', 'rejected') AND m.end_date >= CURDATE()
        ORDER BY 
            m.match_name ASC, 
            CASE ms.status 
                WHEN 'pending' THEN 1 
                WHEN 'approved' THEN 2 
                WHEN 'standby' THEN 3 
                WHEN 'reject' THEN 4
                WHEN 'declined' THEN 4
                ELSE 5 
            END ASC,
            ms.created_at DESC
    ");
    $stmt->execute();
} else {
    $area = trim($_SESSION['area'] ?? '');
    $officerUserId = (int) ($_SESSION['user_role'] === 'AC' ? 0 : ($_SESSION['user_id'] ?? 0)); // AC might not need to exclude self if role filter handles it, but keep it safe

    $roleFilter = "";
    if ($is_ac || $is_aac) {
        $roleFilter = " AND (u.role IN ('AC', 'AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member') OR u.role IS NULL OR u.role = '')";
    }

    // For AC/AAC: show local/retroactive (all statuses) AND regular match significations that are 'approved' (for withdrawal only)
    $stmt = $pdo->prepare("
        SELECT 
            ms.*,
            u.nroi_id, u.first_name, u.last_name, u.role, u.rank, u.area,
            m.id as match_id, m.match_name, m.start_date, m.end_date, m.location, m.match_level, m.range_master, m.is_local, m.is_retroactive, $rmSelect, $roSelect,
            (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,
            (SELECT COUNT(*) FROM match_significations WHERE match_id = m.id AND status = 'approved') as approved_count,
            (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
            CASE 
                WHEN mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' THEN 'served'
                WHEN ms.status != 'approved' THEN NULL
                ELSE 'incomplete'
            END as match_completion_status
        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 match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
        WHERE TRIM(COALESCE(u.area, '')) = ? 
          $roleFilter
          AND m.end_date >= CURDATE()
          AND (
            -- For local/retroactive: show all statuses
            ((m.is_local = 1 OR m.is_retroactive = 1) AND ms.status IN ('pending', 'approved', 'standby', 'declined', 'rejected'))
            OR
            -- For regular matches: only show 'approved' ones (AC/AAC can only withdraw)
            ((m.is_local = 0 AND m.is_retroactive = 0) AND ms.status = 'approved')
          )
        ORDER BY 
            m.match_name ASC, 
            CASE ms.status 
                WHEN 'pending' THEN 1 
                WHEN 'approved' THEN 2 
                WHEN 'standby' THEN 3 
                WHEN 'reject' THEN 4
                WHEN 'declined' THEN 4
                ELSE 5 
            END ASC,
            ms.created_at DESC
    ");
    $stmt->execute([$area]);
}
$signifiedMatches = $stmt->fetchAll();

// Verify signatures exist on disk
foreach ($signifiedMatches as &$match) {
    if ($match['match_completion_status'] === 'served' && !empty($match['rm_signature'])) {
        $sigPath = '../' . $match['rm_signature'];
        if (!file_exists($sigPath)) {
            $match['match_completion_status'] = 'incomplete';
        }
    }
}
unset($match);

$groupedSignified = [];
foreach ($signifiedMatches as $match) {
    $matchId = $match['match_id'];
    if (!isset($groupedSignified[$matchId])) {
        $groupedSignified[$matchId] = [
            'match_info' => [
                'match_id' => $match['match_id'],
                'match_name' => $match['match_name'],
                'start_date' => $match['start_date'],
                'end_date' => $match['end_date'],
                'location' => $match['location'],
                'match_level' => $match['match_level'],
                'range_master' => $match['range_master'],
                'rm_name' => $match['rm_name'],
                'ro_limit' => $match['ro_limit'],
                'approved_count' => $match['approved_count'],
                'is_local' => $match['is_local'],
                'is_retroactive' => $match['is_retroactive']
            ],
            'significations' => []
        ];
    }
    $groupedSignified[$matchId]['significations'][] = $match;
}

// Fetch withdrawal requests
if ($is_admin) {
    $stmt = $pdo->prepare("
        SELECT 
            ms.*,
            u.nroi_id, u.first_name, u.last_name, u.role, u.rank, u.area,
            m.id as match_id, m.match_name, m.start_date, m.end_date, m.location, m.match_level, m.range_master, m.is_local, m.is_retroactive, $rmSelect,
            (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,
            (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
            CASE 
                WHEN mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' THEN 'served'
                WHEN ms.status != 'approved' AND ms.status != 'withdrawal_requested' THEN NULL
                ELSE 'incomplete'
            END as match_completion_status
        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 match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
        WHERE ms.status IN ('withdrawal_requested', 'withdrawn') AND m.end_date >= CURDATE()
        ORDER BY 
            m.match_name ASC, 
            CASE ms.status 
                WHEN 'withdrawal_requested' THEN 1 
                WHEN 'withdrawn' THEN 2 
                ELSE 3 
            END ASC,
            ms.created_at DESC
    ");
    $stmt->execute();
} else {
    $area = trim($_SESSION['area'] ?? '');

    $roleFilter = "";
    if ($is_ac || $is_aac) {
        $roleFilter = " AND (u.role IN ('AC', 'AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member') OR u.role IS NULL OR u.role = '')";
    }

    // AC/AAC: manage withdrawal requests for ALL match types (local, retroactive, AND regular)
    $stmt = $pdo->prepare("
        SELECT 
            ms.*,
            u.nroi_id, u.first_name, u.last_name, u.role, u.rank, u.area,
            m.id as match_id, m.match_name, m.start_date, m.end_date, m.location, m.match_level, m.range_master, m.is_local, m.is_retroactive, $rmSelect,
            (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,
            (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
            CASE 
                WHEN mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' THEN 'served'
                WHEN ms.status != 'approved' AND ms.status != 'withdrawal_requested' THEN NULL
                ELSE 'incomplete'
            END as match_completion_status
        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 match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
        WHERE ms.status IN ('withdrawal_requested', 'withdrawn') 
          AND TRIM(COALESCE(u.area, '')) = ? 
          $roleFilter
          AND m.end_date >= CURDATE()
        ORDER BY 
            m.match_name ASC, 
            CASE ms.status 
                WHEN 'withdrawal_requested' THEN 1 
                WHEN 'withdrawn' THEN 2 
                ELSE 3 
            END ASC,
            ms.created_at DESC
    ");
    $stmt->execute([$area]);
}
$withdrawalRequests = $stmt->fetchAll();

// Verify signatures exist on disk
foreach ($withdrawalRequests as &$req) {
    if ($req['match_completion_status'] === 'served' && !empty($req['rm_signature'])) {
        $sigPath = '../' . $req['rm_signature'];
        if (!file_exists($sigPath)) {
            $req['match_completion_status'] = 'incomplete';
        }
    }
}
unset($req);

$groupedWithdrawals = [];
foreach ($withdrawalRequests as $req) {
    $matchId = $req['match_id'];
    if (!isset($groupedWithdrawals[$matchId])) {
        $groupedWithdrawals[$matchId] = [
            'match_info' => [
                'match_id' => $req['match_id'],
                'match_name' => $req['match_name'],
                'start_date' => $req['start_date'],
                'end_date' => $req['end_date'],
                'location' => $req['location'],
                'match_level' => $req['match_level'],
                'range_master' => $req['range_master'],
                'rm_name' => $req['rm_name'],
            ],
            'significations' => []
        ];
    }
    $groupedWithdrawals[$matchId]['significations'][] = $req;
}

// Approved members for the modal list logic (needed for the JS but mostly moved out)
$approvedInArea = [];
if (!$is_admin && ($is_ac || $is_aac)) {
    $officerArea = trim($_SESSION['area'] ?? '');
    $stmt = $pdo->prepare("SELECT * FROM users WHERE area = ? AND status = 'active' ORDER BY last_name ASC");
    $stmt->execute([$officerArea]);
    $approvedInArea = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Requests | 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>
        .match-group-container {
            margin-bottom: 20px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            background: #fff;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .match-group-header {
            padding: 20px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            user-select: none;
        }

        .match-group-header:hover {
            background: #f1f5f9;
        }

        .match-group-header.active {
            background: #eff6ff;
            border-bottom-color: #dbeafe;
        }

        .match-info-main {
            flex: 1;
        }

        .match-title {
            margin: 0;
            font-size: 1.15rem;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .match-meta-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 12px;
            margin-top: 12px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.85rem;
            color: #64748b;
        }

        .meta-item i {
            width: 16px;
            color: #94a3b8;
        }

        .level-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: #e0f2fe;
            color: #0369a1;
            padding: 2px 8px;
            border-radius: 6px;
            font-weight: 700;
            font-size: 0.75rem;
            border: 1px solid #bae6fd;
        }

        .match-group-content {
            display: none;
            padding: 0;
            animation: slideDown 0.3s ease-out;
        }

        .match-group-content.active {
            display: block;
        }

        .chevron-icon {
            transition: transform 0.3s ease;
            color: #94a3b8;
        }

        .match-group-header.active .chevron-icon {
            transform: rotate(180deg);
            color: #2563eb;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .slots-indicator {
            padding: 4px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
            white-space: nowrap;
        }
    </style>
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>
    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($is_admin)
                    echo 'ADMIN';
                elseif ($is_ac)
                    echo 'A.C';
                elseif ($is_aac)
                    echo 'A.A.C';
                elseif ($is_special)
                    echo htmlspecialchars(strtoupper($_SESSION['user_role'] ?? 'OFFICER'));
                ?>
            </div>
        </div>
        <ul class="sidebar-menu">
            <?php if ($is_admin): ?>
                <li class="sidebar-item"><a href="../admin/dashboard.php" class="sidebar-link"><i
                            class="fas fa-th-large"></i> Overview</a></li>
                <li class="sidebar-item"><a href="users.php" class="sidebar-link"><i class="fas fa-user-friends"></i>
                        Accounts</a></li>
                <li class="sidebar-item"><a href="../admin/management.php" class="sidebar-link"><i class="fas fa-cog"></i>
                        Management</a></li>
                <li class="sidebar-item"><a href="matches.php" class="sidebar-link"><i class="fas fa-trophy"></i>
                        Matches</a></li>
                <li class="sidebar-item"><a href="request.php" class="sidebar-link active"><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>
                    <li class="sidebar-item">
                        <a href="users.php" class="sidebar-link">
                            <i class="fas fa-user-friends"></i> Accounts
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="request.php" class="sidebar-link active">
                            <i class="fas fa-inbox"></i> For Approval
                        </a>
                    </li>
                <?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>
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">
                    <?php
                    if ($is_admin)
                        echo 'AD';
                    elseif ($is_ac)
                        echo 'AC';
                    elseif ($is_aac)
                        echo 'AA';
                    elseif ($is_special)
                        echo strtoupper(substr($_SESSION['user_role'] ?? 'OF', 0, 2));
                    ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">
                        <?php echo $is_admin ? 'Administrator' : capitalizeWords($_SESSION['name'] ?? 'Officer'); ?>
                    </div>
                    <div class="sidebar-user-role">
                        <?php
                        if ($is_admin)
                            echo 'System Admin';
                        elseif ($is_ac)
                            echo 'A.C Account';
                        elseif ($is_aac)
                            echo 'A.A.C Account';
                        elseif ($is_special)
                            echo htmlspecialchars(strtoupper($_SESSION['user_role'] ?? 'OFFICER')) . ' Account';
                        ?>
                    </div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>
                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="<?php echo $is_admin ? '../admin/profile.php' : '../officer/profile.php'; ?>"
                        class="dropdown-item"><i class="far fa-user-circle"></i> My Profile</a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </div>
            </div>
        </div>
    </aside>

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

            <?php
            // Check if we should show standby selection
            $showStandbyModal = false;
            $standbyUsersForMatch = [];
            $affectedMatchName = '';

            if (isset($_GET['success']) && $_GET['success'] === 'withdrawn' && isset($_GET['match_id'])) {
                $mId = (int) $_GET['match_id'];

                // Check if slots are available
                $stmtM = $pdo->prepare("
                    SELECT match_name, ro_limit, 
                    (SELECT COUNT(*) FROM match_significations WHERE match_id = m.id AND status = 'approved') as approved_count 
                    FROM match_schedules m WHERE id = ?
                ");
                $stmtM->execute([$mId]);
                $mDetails = $stmtM->fetch(PDO::FETCH_ASSOC);

                if ($mDetails && ($mDetails['ro_limit'] == 0 || $mDetails['approved_count'] < $mDetails['ro_limit'])) {
                    // Fetch standby users for this match
                    $areaFilter = "";
                    $params = [$mId];
                    if (!$is_admin) {
                        $areaFilter = " AND u.area = ?";
                        $params[] = trim($_SESSION['area'] ?? '');
                    }

                    $stmtS = $pdo->prepare("
                        SELECT ms.id, u.first_name, u.last_name, u.nroi_id, u.role, u.rank
                        FROM match_significations ms
                        JOIN users u ON ms.user_id = u.id
                        WHERE ms.match_id = ? AND ms.status = 'standby' $areaFilter
                        ORDER BY ms.created_at ASC
                    ");
                    $stmtS->execute($params);
                    $standbyUsersForMatch = $stmtS->fetchAll(PDO::FETCH_ASSOC);

                    if (!empty($standbyUsersForMatch)) {
                        $showStandbyModal = true;
                        $affectedMatchName = $mDetails['match_name'];
                    }
                }
            }
            ?>
            <div style="display: flex; gap: 10px; margin: 20px; border-bottom: 2px solid #e2e8f0;">
                <a href="request.php?tab=signified"
                    style="padding: 12px 24px; text-decoration: none; color: <?php echo $activeTab === 'signified' ? '#2563eb' : '#64748b'; ?>; font-weight: <?php echo $activeTab === 'signified' ? '700' : '500'; ?>; border-bottom: 2px solid <?php echo $activeTab === 'signified' ? '#2563eb' : 'transparent'; ?>; margin-bottom: -2px; transition: all 0.2s;"><i
                        class="fas fa-check-circle"></i> Call-Up</a>
                <a href="request.php?tab=withdrawed"
                    style="padding: 12px 24px; text-decoration: none; color: <?php echo $activeTab === 'withdrawed' ? '#2563eb' : '#64748b'; ?>; font-weight: <?php echo $activeTab === 'withdrawed' ? '700' : '500'; ?>; border-bottom: 2px solid <?php echo $activeTab === 'withdrawed' ? '#2563eb' : 'transparent'; ?>; margin-bottom: -2px; transition: all 0.2s;"><i
                        class="fas fa-undo"></i> Withdrawn</a>
            </div>

            <?php if (isset($_SESSION['success_msg'])): ?>
                <div class="alert alert-success"
                    style="padding: 15px; background: #dcfce7; color: #16a34a; border-radius: 12px; margin: 20px; border: 1px solid #bbf7d0; display: flex; align-items: center; gap: 10px; animation: slideInFromRight 0.5s ease; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                    <i class="fas fa-check-circle"></i>
                    <span><?php echo $_SESSION['success_msg'];
                    unset($_SESSION['success_msg']); ?></span>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['error_msg'])): ?>
                <div class="alert alert-danger"
                    style="padding: 15px; background: #fee2e2; color: #dc2626; border-radius: 12px; margin: 20px; border: 1px solid #fecaca; display: flex; align-items: center; gap: 10px; animation: slideInFromRight 0.5s ease; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo $_SESSION['error_msg'];
                    unset($_SESSION['error_msg']); ?></span>
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['success'])): ?>
                <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; ?>

            <!-- Filters (Type & Search) -->
            <div style="display: flex; gap: 15px; margin: 0 20px 20px 20px; align-items: center; flex-wrap: wrap;">
                <!-- 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="requestTypeFilter" onchange="applyRequestFilters()"
                        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 Match 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: 250px;">
                    <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="requestSearchInput"
                        placeholder="Search match name, location, RM, discipline..." oninput="applyRequestFilters()"
                        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 onclick="clearRequestFilters()"
                    style="height: 42px; padding: 0 20px; border-radius: 12px; border: 1px solid #e2e8f0; background: #fff; color: #dc2626; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px; transition: all 0.2s;">
                    <i class="fas fa-times"></i> Clear
                </button>
            </div>

            <!-- No Results Feedback -->
            <div id="requestNoResults"
                style="display: none; text-align: center; padding: 60px 20px; color: #64748b; background: #fff; border: 1px dashed #e2e8f0; border-radius: 16px; margin: 20px;">
                <i class="fas fa-search"
                    style="font-size: 3rem; opacity: 0.3; margin-bottom: 15px; display: block;"></i>
                <p>No matches found matching your filters.</p>
            </div>

            <?php if ($activeTab === 'signified'): ?>
                    <?php if (isset($_GET['success'])): ?>
                            <div
                                style="background: #10b981; color: white; padding: 12px 20px; border-radius: 8px; margin: 20px; display: flex; justify-content: space-between; align-items: center;">
                                <span><i class="fas fa-check-circle"></i> <?php echo ucfirst($_GET['success']); ?> successful!</span>
                                <button onclick="this.parentElement.remove()"
                                    style="background: none; border: none; color: white; cursor: pointer; font-size: 1.2rem;">&times;</button>
                            </div>
                    <?php endif; ?>
                    <div>
                        <div class="table-header" style="margin-bottom: 20px;">
                            <h3>Match Call-up</h3>
                            <p style="margin:0; font-size:0.85rem; color:#64748b;">manage match call-up(s)</p>
                        </div>
                        <?php if (empty($groupedSignified)): ?>
                                <div class="content-box">
                                    <div style="text-align: center; padding: 60px 20px; color: #64748b;"><i class="fas fa-check-circle"
                                            style="font-size: 3rem; opacity: 0.3; margin-bottom: 15px; display: block;"></i>
                                        <p>No significations at this time.</p>
                                    </div>
                                </div>
                        <?php else: ?>
                                <?php foreach ($groupedSignified as $matchGroup):
                                    $mInfo = $matchGroup['match_info'];
                                    $approved = $mInfo['approved_count'];
                                    $limit = $mInfo['ro_limit'];
                                    $isFull = ($limit > 0 && $approved >= $limit);
                                    ?>
                                        <div class="match-group-container" style="border-left: 4px solid #2563eb;"
                                            data-type="<?php echo $mInfo['is_retroactive'] ? 'retroactive' : ($mInfo['is_local'] ? 'local' : 'regular'); ?>"
                                            data-name="<?php echo strtolower(htmlspecialchars($mInfo['match_name'] ?? '')); ?>"
                                            data-location="<?php echo strtolower(htmlspecialchars($mInfo['location'] ?? '')); ?>"
                                            data-rm="<?php echo strtolower(htmlspecialchars($mInfo['rm_name'] ?? '')); ?>"
                                            data-discipline="<?php echo strtolower(htmlspecialchars($mInfo['range_master'] ?? '')); ?>">
                                            <div class="match-group-header" onclick="toggleMatchGroup(this)">
                                                <div class="match-info-main">
                                                    <h4 class="match-title">
                                                        <?php echo htmlspecialchars($mInfo['match_name']); ?>
                                                        <span class="level-badge">Level:
                                                            <?php echo preg_replace('/\D/', '', $mInfo['match_level']); ?></span>
                                                    </h4>
                                                    <div class="match-meta-grid">
                                                        <div class="meta-item">
                                                            <i class="far fa-calendar-alt"></i>
                                                            <span>
                                                                <?php
                                                                $sDate = strtotime($mInfo['start_date']);
                                                                $eDate = strtotime($mInfo['end_date']);
                                                                echo (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                                                                    ? date('M d, Y', $sDate)
                                                                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);
                                                                ?>
                                                            </span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-map-marker-alt"></i>
                                                            <span><?php echo htmlspecialchars($mInfo['location']); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-user-tie"></i>
                                                            <span>RM: <?php echo htmlspecialchars($mInfo['rm_name'] ?: '---'); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-bullseye"></i>
                                                            <span>Discipline:
                                                                <?php echo htmlspecialchars($mInfo['range_master'] ?: '---'); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-tag"></i>
                                                            <span>Type:
                                                                <?php
                                                                if ($mInfo['is_local'])
                                                                    echo '<span style="color:#2563eb; font-weight:600;">Local Match</span>';
                                                                elseif ($mInfo['is_retroactive'])
                                                                    echo '<span style="color:#f59e0b; font-weight:600;">Retroactive Match</span>';
                                                                else
                                                                    echo '<span style="color:#10b981; font-weight:600;">Regular Match</span>';
                                                                ?>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div style="display: flex; align-items: center; gap: 15px;">
                                                    <span class="slots-indicator"
                                                        style="background: <?php echo $isFull ? '#fef2f2' : '#f0fdf4'; ?>; color: <?php echo $isFull ? '#ef4444' : '#10b981'; ?>; border: 1px solid <?php echo $isFull ? '#fecaca' : '#bbf7d0'; ?>;">
                                                        <?php echo $approved; ?> / <?php echo $limit > 0 ? $limit : '∞'; ?> Slots
                                                    </span>
                                                    <i class="fas fa-chevron-down chevron-icon"></i>
                                                </div>
                                            </div>
                                            <div class="match-group-content">
                                                <table class="modern-table" style="margin-bottom: 0;">
                                                    <thead>
                                                        <tr>
                                                            <th>Name</th>
                                                            <th>NROI ID</th>
                                                            <th>Rank</th>
                                                            <th>Status</th>
                                                            <th>Reason / Remarks</th>
                                                            <th>TIMESTAMP</th>
                                                            <th style="text-align: right;">Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($matchGroup['significations'] as $match): ?>
                                                                <tr>
                                                                    <td style="font-weight: 600; color: #1e293b;">
                                                                        <?php echo htmlspecialchars(capitalizeWords($match['last_name'] . ', ' . $match['first_name'])); ?>
                                                                        <span
                                                                            style="font-size: 0.72rem; color: <?php echo ($match['withdraw_count'] ?? 0) > 10 ? '#ef4444' : '#64748b'; ?>; font-weight: 500; margin-left: 5px;">
                                                                            (W: <?php echo $match['withdraw_count'] ?? 0; ?>)
                                                                        </span>
                                                                    </td>
                                                                    <td><?php echo htmlspecialchars($match['nroi_id'] ?? 'N/A'); ?></td>
                                                                    <td>
                                                                        <div style="display: flex; flex-direction: column; gap: 4px;">
                                                                            <span class="role-badge"
                                                                                style="background: #eff6ff; color: #1e40af;"><?php echo (!empty($match['role']) && $match['role'] !== 'member') ? htmlspecialchars($match['role']) : 'R.O'; ?></span>
                                                                            <?php
                                                                            $displayRoleMatch = (!empty($match['role']) && $match['role'] !== 'member') ? $match['role'] : 'R.O';
                                                                            if ($displayRoleMatch !== 'AC' && $displayRoleMatch !== '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(($match['rank'] === 'Regular' || $match['rank'] === 'OJT') ? $match['rank'] : 'Regular'); ?>
                                                                                    </span>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </td>
                                                                    <td><span
                                                                            class="status-badge status-<?php echo htmlspecialchars($match['status']); ?>"><?php echo status_display_label($match['status']); ?></span>
                                                                    </td>
                                                                    <td>
                                                                        <?php
                                                                        $userReason = trim($match['withdrawal_reason'] ?? '');
                                                                        $officerNote = trim($match['officer_remarks'] ?? '');
                                                                        if ($userReason !== '' || $officerNote !== ''):
                                                                            ?>
                                                                                <div style="font-size:0.82rem; color:#1e293b; line-height:1.5;">
                                                                                    <?php if ($userReason !== ''): ?>
                                                                                            <div style="margin-bottom:4px;">
                                                                                                <span style="font-weight:600; color:#92400e;">User's Reason (Request to Withdraw):</span><br>
                                                                                                <?php echo htmlspecialchars($userReason); ?>
                                                                                            </div>
                                                                                    <?php endif; ?>
                                                                                    <?php if ($officerNote !== ''): ?>
                                                                                            <?php
                                                                                            // Find reviewer role from logs if possible, or fallback
                                                                                            $rRole = strtoupper(trim($match['reviewer_role'] ?? ''));
                                                                                            $baseLabel = match ($rRole) {
                                                                                                'AC' => 'AC note',
                                                                                                'AAC' => 'AAC note',
                                                                                                'ADMIN' => 'Admin note',
                                                                                                'RM' => 'RM note',
                                                                                                default => 'Officer note',
                                                                                            };
                                                                                            if ($match['status'] === 'standby') {
                                                                                                $roleLabel = $baseLabel . ' (Standby Note):';
                                                                                            } elseif ($match['status'] === 'approved' && $userReason !== '') {
                                                                                                $roleLabel = $baseLabel . ' (Rejected to Withdraw Note):';
                                                                                            } elseif (in_array($match['status'], ['declined', 'rejected'])) {
                                                                                                $roleLabel = $baseLabel . ' (Rejection/Decline Note):';
                                                                                            } elseif ($match['status'] === 'withdrawn') {
                                                                                                $roleLabel = $baseLabel . ' (Withdrawal Note):';
                                                                                            } else {
                                                                                                $roleLabel = $baseLabel . ':';
                                                                                            }
                                                                                            ?>
                                                                                            <div>
                                                                                                <span style="font-weight:600; color:#1e40af;"><?php echo $roleLabel; ?></span><br>
                                                                                                <?php echo htmlspecialchars($officerNote); ?>
                                                                                            </div>
                                                                                    <?php endif; ?>
                                                                                </div>
                                                                        <?php else: ?>
                                                                                <span style="color: #94a3b8; font-size: 0.8rem;">—</span>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                    <td>
                                                                        <?php echo getSignificationHistory($pdo, $match['id']); ?>
                                                                    </td>
                                                                    <td style="text-align: right;">
                                                                        <div class="action-btns"
                                                                            style="display: flex; gap: 5px; justify-content: flex-end;">
                                                                            <?php
                                                                            $isServed = ($match['match_completion_status'] === 'served');
                                                                            $isRegularMatch = !($mInfo['is_local'] || $mInfo['is_retroactive']);
                                                                            $isAcAac = !$is_admin && ($is_ac || $is_aac);

                                                                            if ($isServed): ?>
                                                                                    <span
                                                                                        style="font-size: 0.75rem; color: #059669; font-weight: 700; background: #ecfdf5; padding: 5px 12px; border-radius: 6px; border: 1px solid #a7f3d0; letter-spacing: 0.5px;">SERVED</span>
                                                                            <?php elseif ($isRegularMatch && $isAcAac):
                                                                                // AC/AAC on regular match: can ONLY withdraw approved members
                                                                                if ($match['status'] === 'approved'): ?>
                                                                                            <button class="icon-btn"
                                                                                                style="background: #ef4444; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                                onclick="directWithdraw(<?php echo $match['id']; ?>, <?php echo $match['withdraw_count'] ?? 0; ?>)">
                                                                                                Withdraw
                                                                                            </button>
                                                                                    <?php else: ?>
                                                                                            <span style="font-size: 0.8rem; color: #64748b;">—</span>
                                                                                    <?php endif; ?>
                                                                            <?php elseif ($match['status'] === 'pending'): ?>
                                                                                    <button class="icon-btn"
                                                                                        style="background: <?php echo $isFull ? '#cbd5e1' : '#10b981'; ?>; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem; <?php echo $isFull ? 'cursor: not-allowed;' : ''; ?>"
                                                                                        onclick="<?php echo $isFull ? "showMessageModal('This match is already full. You cannot approve more members.')" : "handleSignificationAction(" . $match['id'] . ", 'approve')"; ?>"
                                                                                        <?php echo $isFull ? 'disabled' : ''; ?>>
                                                                                        Approved
                                                                                    </button>
                                                                                    <button class="icon-btn"
                                                                                        style="background: #f59e0b; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                        onclick="handleSignificationAction(<?php echo $match['id']; ?>, 'standby')">Standby</button>
                                                                                    <button class="icon-btn btn-reject"
                                                                                        style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                        onclick="rejectSignification(<?php echo $match['id']; ?>)">Reject</button>
                                                                            <?php elseif ($match['status'] === 'standby'): ?>
                                                                                    <button class="icon-btn"
                                                                                        style="background: <?php echo $isFull ? '#cbd5e1' : '#10b981'; ?>; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem; <?php echo $isFull ? 'cursor: not-allowed;' : ''; ?>"
                                                                                        onclick="<?php echo $isFull ? "showMessageModal('This match is already full. You cannot approve more members.')" : "handleSignificationAction(" . $match['id'] . ", 'approve')"; ?>"
                                                                                        <?php echo $isFull ? 'disabled' : ''; ?>>
                                                                                        Approved
                                                                                    </button>
                                                                                    <button class="icon-btn btn-reject"
                                                                                        style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                        onclick="rejectSignification(<?php echo $match['id']; ?>)">Reject</button>
                                                                            <?php elseif ($match['status'] === 'approved'): ?>
                                                                                    <button class="icon-btn"
                                                                                        style="background: #ef4444; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                        onclick="directWithdraw(<?php echo $match['id']; ?>, <?php echo $match['withdraw_count'] ?? 0; ?>)">
                                                                                        Withdraw
                                                                                    </button>
                                                                            <?php else: ?>
                                                                                    <span style="font-size: 0.8rem; color: #64748b;">—</span>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
            <?php endif; ?>

            <?php if ($activeTab === 'withdrawed'): ?>
                    <div>
                        <div class="table-header" style="margin-bottom: 20px;">
                            <h3>Withdrawal Requests</h3>
                            <p style="margin:0; font-size:0.85rem; color:#64748b;">Manage match withdrawal requests</p>
                        </div>
                        <?php if (empty($groupedWithdrawals)): ?>
                                <div class="content-box">
                                    <div style="text-align: center; padding: 60px 20px; color: #64748b;"><i class="fas fa-undo"
                                            style="font-size: 3rem; opacity: 0.3; margin-bottom: 15px; display: block;"></i>
                                        <p>No withdrawal requests.</p>
                                    </div>
                                </div>
                        <?php else: ?>
                                <?php foreach ($groupedWithdrawals as $matchGroup):
                                    $mInfo = $matchGroup['match_info'];
                                    ?>
                                        <div class="match-group-container" style="border-left: 4px solid #ef4444;"
                                            data-type="<?php echo ($mInfo['is_retroactive'] ?? false) ? 'retroactive' : (($mInfo['is_local'] ?? false) ? 'local' : 'regular'); ?>"
                                            data-name="<?php echo strtolower(htmlspecialchars($mInfo['match_name'] ?? '')); ?>"
                                            data-location="<?php echo strtolower(htmlspecialchars($mInfo['location'] ?? '')); ?>"
                                            data-rm="<?php echo strtolower(htmlspecialchars($mInfo['rm_name'] ?? '')); ?>"
                                            data-discipline="<?php echo strtolower(htmlspecialchars($mInfo['range_master'] ?? '')); ?>">
                                            <div class="match-group-header" onclick="toggleMatchGroup(this)">
                                                <div class="match-info-main">
                                                    <h4 class="match-title">
                                                        <?php echo htmlspecialchars($mInfo['match_name']); ?>
                                                        <span class="level-badge"
                                                            style="background: #fee2e2; color: #991b1b; border-color: #fecaca;">Level:
                                                            <?php echo preg_replace('/\D/', '', $mInfo['match_level'] ?? ''); ?></span>
                                                    </h4>
                                                    <div class="match-meta-grid">
                                                        <div class="meta-item">
                                                            <i class="far fa-calendar-alt"></i>
                                                            <span style="color: #991b1b; opacity: 0.8;">
                                                                <?php
                                                                $sDate = strtotime($mInfo['start_date']);
                                                                $eDate = strtotime($mInfo['end_date']);
                                                                echo (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
                                                                    ? date('M d, Y', $sDate)
                                                                    : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);
                                                                ?>
                                                            </span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-map-marker-alt"></i>
                                                            <span><?php echo htmlspecialchars($mInfo['location']); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-user-tie"></i>
                                                            <span>RM: <?php echo htmlspecialchars($mInfo['rm_name'] ?: '---'); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-bullseye"></i>
                                                            <span>Discipline:
                                                                <?php echo htmlspecialchars($mInfo['range_master'] ?: '---'); ?></span>
                                                        </div>
                                                        <div class="meta-item">
                                                            <i class="fas fa-tag"></i>
                                                            <span>Type:
                                                                <?php
                                                                if ($mInfo['is_local'] ?? false)
                                                                    echo '<span style="color:#ef4444; font-weight:600;">Local Match</span>';
                                                                elseif ($mInfo['is_retroactive'] ?? false)
                                                                    echo '<span style="color:#f59e0b; font-weight:600;">Retroactive Match</span>';
                                                                else
                                                                    echo '<span style="color:#10b981; font-weight:600;">Regular Match</span>';
                                                                ?>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div style="display: flex; align-items: center; gap: 15px;">
                                                    <i class="fas fa-chevron-down chevron-icon"></i>
                                                </div>
                                            </div>
                                            <div class="match-group-content">
                                                <table class="modern-table" style="margin-bottom: 0;">
                                                    <thead>
                                                        <tr>
                                                            <th>Name</th>
                                                            <th>Area</th>
                                                            <th>NROI ID</th>
                                                            <th>Status</th>
                                                            <th>Withdrawal Reason</th>
                                                            <th>TIMESTAMP</th>
                                                            <th style="text-align: right;">Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($matchGroup['significations'] as $req): ?>
                                                                <tr>
                                                                    <td style="font-weight: 600; color: #1e293b;">
                                                                        <?php echo htmlspecialchars(capitalizeWords($req['last_name'] . ', ' . $req['first_name'])); ?>
                                                                        <span
                                                                            style="font-size: 0.72rem; color: <?php echo ($req['withdraw_count'] ?? 0) > 10 ? '#ef4444' : '#64748b'; ?>; font-weight: 500; margin-left: 5px;">
                                                                            (W: <?php echo $req['withdraw_count'] ?? 0; ?>)
                                                                        </span>
                                                                    </td>
                                                                    <td style="font-weight: 500;"><?php echo htmlspecialchars($req['area'] ?: 'N/A'); ?>
                                                                    </td>
                                                                    <td><?php echo htmlspecialchars($req['nroi_id'] ?? 'N/A'); ?></td>
                                                                    <td><span
                                                                            class="status-badge status-<?php echo htmlspecialchars($req['status']); ?>"><?php echo status_display_label($req['status']); ?></span>
                                                                    </td>
                                                                    <td>
                                                                        <?php
                                                                        $userReason = trim($req['withdrawal_reason'] ?? '');
                                                                        $officerNote = trim($req['officer_remarks'] ?? '');
                                                                        if ($userReason !== '' || $officerNote !== ''):
                                                                            ?>
                                                                                <div style="font-size:0.82rem; color:#1e293b; line-height:1.5;">
                                                                                    <?php if ($userReason !== ''): ?>
                                                                                            <div style="margin-bottom:4px;">
                                                                                                <span style="font-weight:600; color:#92400e;">User's Reason (Request to Withdraw):</span><br>
                                                                                                <?php echo htmlspecialchars($userReason); ?>
                                                                                            </div>
                                                                                    <?php endif; ?>
                                                                                    <?php if ($officerNote !== ''): ?>
                                                                                            <?php
                                                                                            $rRole = strtoupper(trim($req['reviewer_role'] ?? ''));
                                                                                            $baseLabel = match ($rRole) {
                                                                                                'AC' => 'AC note',
                                                                                                'AAC' => 'AAC note',
                                                                                                'ADMIN' => 'Admin note',
                                                                                                'RM' => 'RM note',
                                                                                                default => 'Officer note',
                                                                                            };
                                                                                            if ($req['status'] === 'standby') {
                                                                                                $roleLabel = $baseLabel . ' (Standby Note):';
                                                                                            } elseif ($req['status'] === 'approved' && $userReason !== '') {
                                                                                                $roleLabel = $baseLabel . ' (Rejected to Withdraw Note):';
                                                                                            } elseif (in_array($req['status'], ['declined', 'rejected'])) {
                                                                                                $roleLabel = $baseLabel . ' (Rejection/Decline Note):';
                                                                                            } elseif ($req['status'] === 'withdrawn') {
                                                                                                $roleLabel = $baseLabel . ' (Withdrawal Note):';
                                                                                            } else {
                                                                                                $roleLabel = $baseLabel . ':';
                                                                                            }
                                                                                            ?>
                                                                                            <div>
                                                                                                <span
                                                                                                    style="font-weight:600; color:#1e40af;"><?php echo $roleLabel; ?></span><br>
                                                                                                <?php echo htmlspecialchars($officerNote); ?>
                                                                                            </div>
                                                                                    <?php endif; ?>
                                                                                </div>
                                                                        <?php else: ?>
                                                                                <span style="color:#94a3b8; font-size:0.8rem;">—</span>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                    <td>
                                                                        <?php echo getSignificationHistory($pdo, $req['id']); ?>
                                                                    </td>
                                                                    <td style="text-align: right;">
                                                                        <div class="action-btns"
                                                                            style="display: flex; gap: 5px; justify-content: flex-end;">
                                                                            <?php if ($req['status'] === 'withdrawal_requested'): ?>
                                                                                    <?php if (($req['match_completion_status'] ?? '') === 'served'): ?>
                                                                                            <span
                                                                                                style="font-size: 0.75rem; color: #059669; font-weight: 700; background: #ecfdf5; padding: 5px 12px; border-radius: 6px; border: 1px solid #a7f3d0; letter-spacing: 0.5px;">SERVED</span>
                                                                                    <?php else: ?>
                                                                                            <button class="icon-btn"
                                                                                                style="background: #10b981; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                                onclick="approveWithdrawal(<?php echo $req['id']; ?>, <?php echo $req['withdraw_count'] ?? 0; ?>)">Approve</button>
                                                                                            <button class="icon-btn btn-reject"
                                                                                                style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                                                onclick="rejectWithdrawal(<?php echo $req['id']; ?>)">Reject</button>
                                                                                    <?php endif; ?>
                                                                            <?php else: ?>
                                                                                    <span style="font-size: 0.8rem; color: #64748b;">—</span>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
            <?php endif; ?>

            <!-- Management Footer Indicator -->
            <footer
                style="margin-top: 50px; padding: 20px 0; border-top: 1px dashed #e2e8f0; display: flex; align-items: center; gap: 10px; justify-content: center;">
                <?php if ($is_admin): ?>
                        <i class="fas fa-shield-halved" style="color: #94a3b8; font-size: 0.9rem;"></i>
                        <span style="font-size: 0.8rem; color: #64748b; font-weight: 500;">
                            <strong>System Authority:</strong> You can handle all type (Retroactive, Local, Regular) of matches
                        </span>
                <?php elseif ($is_ac || $is_aac): ?>
                        <i class="fas fa-info-circle" style="color: #94a3b8; font-size: 0.9rem;"></i>
                        <span style="font-size: 0.8rem; color: #64748b; font-weight: 500;">
                            <strong>Management Note:</strong> Retroactive and Local Matches are under your management. Regular
                            Matches are handled by Range Masters assigned to it.
                        </span>
                <?php endif; ?>
            </footer>
        </main>
    </div>

    <div id="approveWithdrawalModal" class="modal">
        <div class="modal-content" style="max-width: 420px; padding: 25px;">
            <p style="color:#1e293b; font-size:0.9rem; font-weight: 600; margin-bottom: 12px;">Approve Withdrawal</p>
            <p style="color:#64748b; font-size:0.85rem; margin-bottom: 15px;">Mark this signification as withdrawn?</p>
            <div id="withdraw_count_info" style="margin-bottom: 15px; font-weight: 600; font-size: 0.85rem;"></div>
            <div id="demerit_section"
                style="display:none; margin-bottom: 20px; padding: 15px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
                <p style="color: #b91c1c; font-size: 0.85rem; margin-top: 0;"><strong>Warning:</strong> Beyond
                    10-withdrawal limit. A demerit is required.</p>
                <label class="form-label" style="color: #b91c1c; font-size: 0.8rem;">Points to Deduct</label>
                <input type="number" id="deduction_points_approve" class="form-input" placeholder="0.00" step="0.5"
                    min="0" style="padding: 8px; font-size: 0.85rem;">
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 10px;">
                <button onclick="closeModals()" style="background: #f1f5f9; border: none; color: #64748b; font-weight: 700; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 0.85rem;">Cancel</button>
                <button id="approveWithdrawalConfirmBtn" class="btn-primary" style="padding: 8px 16px; font-size: 0.85rem; border-radius: 6px;">Approve</button>
            </div>
        </div>
    </div>
    <!-- Dynamic Action Remarks Modal (Reject/Standby) -->
    <div id="actionRemarksModal" class="modal">
        <div class="modal-content" style="max-width: 420px; padding: 25px;">
            <p id="action_remarks_hint" style="color:#64748b; font-size:0.85rem; margin-bottom: 20px; font-weight: 500;">
                Please provide a reason for this action.
            </p>
            <form method="POST" id="actionRemarksForm">
                <input type="hidden" name="action" id="modal_action" value="reject_signification">
                <input type="hidden" name="signification_id" id="modal_signification_id">
                <label class="form-label" id="action_remarks_label" style="font-size: 0.85rem; margin-bottom: 8px; display: block;">Reason <span style="color: #ef4444;">*</span></label>
                <textarea name="remarks" id="modal_remarks" rows="3" required
                    style="width: 100%; padding: 10px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-family: 'Inter', sans-serif; resize: vertical; min-height: 80px; box-sizing: border-box; margin-bottom: 10px; font-size: 0.9rem; background: #f8fafc;"
                    placeholder="Provide reason..."></textarea>
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 15px;">
                    <button type="button" onclick="closeModals()"
                        style="background: #f1f5f9; border: none; color: #64748b; cursor: pointer; font-weight: 700; padding: 8px 16px; border-radius: 6px; font-size: 0.85rem;">
                        Cancel
                    </button>
                    <button type="submit" id="modal_submit_btn" class="btn-secondary"
                        style="margin: 0; width: auto; padding: 8px 20px; background: #dc2626; color: #ffffff; border: none; border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 0.85rem;">
                        Confirm
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="directWithdrawModal" class="modal">
        <div class="modal-content" style="max-width: 420px; padding: 25px;">
            <p style="color:#64748b; font-size:0.85rem; margin-bottom: 15px; font-weight: 500;">
                Are you sure you want to withdraw this member? They will be moved to the withdrawn list automatically.
            </p>
            <div id="direct_withdraw_count_info" style="margin-bottom: 15px; font-weight: 600; font-size: 0.85rem;"></div>
            <form method="POST">
                <input type="hidden" name="action" value="direct_withdraw">
                <input type="hidden" name="signification_id" id="direct_withdraw_id">

                <div id="direct_demerit_section"
                    style="display:none; margin-bottom: 20px; padding: 15px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
                    <p style="color: #b91c1c; font-size: 0.85rem; margin-top: 0;"><strong>Warning:</strong> Beyond
                        10-withdrawal limit. A demerit will be applied.</p>
                    <label class="form-label" style="color: #b91c1c; font-size: 0.8rem;">Points to Deduct</label>
                    <input type="number" name="deduction_points" id="deduction_points_direct" class="form-input"
                        placeholder="0.00" step="0.5" min="0" style="padding: 8px; font-size: 0.85rem;">
                </div>

                <label class="form-label" style="font-size: 0.85rem; margin-bottom: 8px; display: block;">Reason for Withdrawal <span style="color: #ef4444;">*</span></label>
                <textarea name="remarks" required
                    style="width: 100%; padding: 10px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-family: 'Inter', sans-serif; resize: vertical; min-height: 80px; box-sizing: border-box; margin-bottom: 10px; font-size: 0.9rem; background: #f8fafc;"
                    placeholder="Explain withdrawal..."></textarea>
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 15px;">
                    <button type="button" onclick="closeModals()" style="background: #f1f5f9; border: none; color: #64748b; font-weight: 700; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 0.85rem;">Cancel</button>
                    <button type="submit" class="btn-secondary" style="margin: 0; width: auto; padding: 8px 20px; background: #dc2626; color: #ffffff; border: none; border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 0.85rem;">Withdraw</button>
                </div>
            </form>
        </div>
    </div>

    <div id="standbySelectionModal" class="modal <?php echo $showStandbyModal ? 'active' : ''; ?>">
        <div class="modal-content" style="max-width: 600px;">
            <h3 style="margin-top:0;">Available Slots in Match</h3>
            <p style="color:#64748b; font-size:0.9rem; margin-bottom: 20px;">
                The match <strong><?php echo htmlspecialchars($affectedMatchName); ?></strong> has available slots.
                Would you like to insert one of the following standby members?
            </p>
            <div
                style="max-height: 300px; overflow-y: auto; margin-bottom: 20px; border: 1px solid #e2e8f0; border-radius: 8px;">
                <table class="modern-table" style="margin: 0;">
                    <thead>
                        <tr>
                            <th>Member</th>
                            <th>ID</th>
                            <th>Rank</th>
                            <th style="text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($standbyUsersForMatch as $su): ?>
                                <tr>
                                    <td style="font-weight: 600;">
                                        <?php echo htmlspecialchars(capitalizeWords(($su['last_name'] ?? '') . ', ' . ($su['first_name'] ?? ''))); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($su['nroi_id'] ?? '---'); ?></td>
                                    <td>
                                        <div style="display: flex; flex-direction: column; gap: 4px;">
                                            <span class="role-badge"
                                                style="background: #eff6ff; color: #1e40af;"><?php echo (!empty($su['role']) && $su['role'] !== 'member' && $su['role'] !== '---') ? htmlspecialchars($su['role']) : 'R.O'; ?></span>
                                            <?php
                                            $displayRoleSu = (!empty($su['role']) && $su['role'] !== 'member' && $su['role'] !== '---') ? $su['role'] : 'R.O';
                                            if ($displayRoleSu !== 'AC' && $displayRoleSu !== '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(($su['rank'] === 'Regular' || $su['rank'] === 'OJT') ? $su['rank'] : 'Regular'); ?>
                                                    </span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td style="text-align: right;">
                                        <button class="icon-btn"
                                            style="background: #10b981; color: white; padding: 5px 12px; font-size: 0.75rem;"
                                            onclick="approveStandbyMember(<?php echo $su['id']; ?>)">
                                            Insert
                                        </button>
                                    </td>
                                </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div style="display: flex; justify-content: flex-end;">
                <button type="button" onclick="closeModals()"
                    style="background: #64748b; color: white; border: none; padding: 10px 18px; border-radius: 8px; font-weight: 600; cursor: pointer;">
                    Cancel
                </button>
            </div>
        </div>
    </div>

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

        let pendingWID = null, pendingSID = null, pendingSTID = null;

        function approveWithdrawal(id, currentCount = 0) {
            pendingWID = id;
            const info = document.getElementById('withdraw_count_info');
            const demerit = document.getElementById('demerit_section');
            info.innerHTML = `Current Withdrawal Count: <span style="color: ${currentCount > 10 ? '#ef4444' : '#1e3a8a'}">${currentCount}</span>`;
            demerit.style.display = currentCount >= 10 ? 'block' : 'none';
            document.getElementById('approveWithdrawalModal').classList.add('active');
        }
        document.getElementById('approveWithdrawalConfirmBtn').addEventListener('click', () => {
            const deduction = document.getElementById('deduction_points_approve').value;
            const f = document.createElement('form'); f.method = 'POST';
            f.innerHTML = `
                <input type="hidden" name="action" value="approve_withdrawal">
                <input type="hidden" name="signification_id" value="${pendingWID}">
                <input type="hidden" name="deduction_points" value="${deduction || 0}">
            `;
            document.body.appendChild(f); f.submit();
        });

        function rejectWithdrawal(id) { 
            openActionModal(id, 'reject_withdrawal');
        }
        function handleSignificationAction(id, action) {
            if (action === 'approve') { 
                pendingSID = id; 
                document.getElementById('approveSignificationModal').classList.add('active'); 
            }
            else if (action === 'standby') { 
                openActionModal(id, 'standby_signification');
            }
        }
        document.getElementById('approveSignificationConfirmBtn').addEventListener('click', () => {
            const f = document.createElement('form'); f.method = 'POST';
            f.innerHTML = `<input type="hidden" name="action" value="approve_signification"><input type="hidden" name="signification_id" value="${pendingSID}"><input type="hidden" name="remarks" value="">`;
            document.body.appendChild(f); f.submit();
        });
        function openActionModal(significationId, action) {
            const modal = document.getElementById('actionRemarksModal');
            const hint = document.getElementById('action_remarks_hint');
            const label = document.getElementById('action_remarks_label');
            const actionInput = document.getElementById('modal_action');
            const idInput = document.getElementById('modal_signification_id');
            const submitBtn = document.getElementById('modal_submit_btn');
            const textarea = document.getElementById('modal_remarks');

            idInput.value = significationId;
            actionInput.value = action;
            textarea.value = '';

            if (action === 'reject_withdrawal') {
                hint.textContent = 'Please provide a reason for rejecting this withdrawal request.';
                label.innerHTML = 'Reason for Rejection <span style="color: #ef4444;">*</span>';
                submitBtn.textContent = 'Reject';
                submitBtn.style.background = '#dc2626';
            } else if (action === 'reject_signification') {
                hint.textContent = 'Please provide a reason for rejecting this signification request.';
                label.innerHTML = 'Reason for Rejection <span style="color: #ef4444;">*</span>';
                submitBtn.textContent = 'Reject';
                submitBtn.style.background = '#dc2626';
            } else if (action === 'standby_signification') {
                hint.textContent = 'Please provide a reason for setting this signification to standby.';
                label.innerHTML = 'Reason for Standby <span style="color: #ef4444;">*</span>';
                submitBtn.textContent = 'Set Standby';
                submitBtn.style.background = '#f59e0b';
            }

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

        function toggleMatchGroup(header) {
            header.classList.toggle('active');
            const content = header.nextElementSibling;
            if (content.style.display === 'block') {
                content.style.display = 'none';
            } else {
                content.style.display = 'block';
            }
        }
        function rejectSignification(id) { 
            openActionModal(id, 'reject_signification');
        }
        function directWithdraw(id, currentCount = 0) {
            document.getElementById('direct_withdraw_id').value = id;
            const info = document.getElementById('direct_withdraw_count_info');
            const demerit = document.getElementById('direct_demerit_section');
            info.innerHTML = `Current Withdrawal Count: <span style="color: ${currentCount > 10 ? '#ef4444' : '#1e3a8a'}">${currentCount}</span>`;
            demerit.style.display = currentCount >= 10 ? 'block' : 'none';
            document.getElementById('directWithdrawModal').classList.add('active');
        }
        function approveStandbyMember(significationId) {
            if (confirm('Are you sure you want to insert this member into the match?')) {
                const f = document.createElement('form');
                f.method = 'POST';
                f.innerHTML = `
                    <input type="hidden" name="action" value="approve_signification">
                    <input type="hidden" name="signification_id" value="${significationId}">
                    <input type="hidden" name="remarks" value="Inserted from standby list after direct withdrawal.">
                `;
                document.body.appendChild(f);
                f.submit();
            }
        }
        function closeModals() { document.querySelectorAll('.modal').forEach(m => m.classList.remove('active')); }

        function applyRequestFilters() {
            const selectedType = document.getElementById('requestTypeFilter').value.toLowerCase();
            const q = document.getElementById('requestSearchInput').value.trim().toLowerCase();
            const containers = document.querySelectorAll('.match-group-container');
            let totalShow = 0;

            containers.forEach(container => {
                const type = container.dataset.type || 'regular';
                const name = container.dataset.name || '';
                const location = container.dataset.location || '';
                const rm = container.dataset.rm || '';
                const discipline = container.dataset.discipline || '';

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

                if (typeMatch && textMatch) {
                    container.style.display = 'block';
                    totalShow++;
                } else {
                    container.style.display = 'none';
                }
            });

            const hasFilter = (selectedType !== 'all' || q !== '');
            document.getElementById('requestNoResults').style.display = (hasFilter && totalShow === 0) ? 'block' : 'none';
        }

        function clearRequestFilters() {
            document.getElementById('requestTypeFilter').value = 'all';
            document.getElementById('requestSearchInput').value = '';
            document.getElementById('requestNoResults').style.display = 'none';
            applyRequestFilters();
        }
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>