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

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

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

// Fetch User Details from Database
$stmt = $pdo->prepare("SELECT area, profile_photo, is_first_login, email, phone_number, first_name, last_name, middle_name, extension, position, username FROM users WHERE id = ?");
$stmt->execute([$userId]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

$area = $userData['area'] ?? '';
$profilePhoto = $userData['profile_photo'] ?? '';
$isFirstLogin = $userData['is_first_login'] ?? 0;
$userEmail = $userData['email'] ?? '';
$userPhone = $userData['phone_number'] ?? '';
$userFirstName = $userData['first_name'] ?? '';
$userLastName = $userData['last_name'] ?? '';
$userMiddleName = $userData['middle_name'] ?? '';
$userExtension = $userData['extension'] ?? '';
$userPosition = $userData['position'] ?? '';
$userUsername = $userData['username'] ?? '';

// Handle Signification Actions (Approve, Standby, Reject)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['signification_action'])) {
    try {
        $significationId = $_POST['signification_id'];
        $action = $_POST['signification_action'];
        $remarks = $_POST['remarks'] ?? '';

        $status = '';
        if ($action === 'approve') {
            $status = 'approved';
        } elseif ($action === 'reject') {
            $status = 'declined';
        } elseif ($action === 'standby') {
            $status = 'standby';
        } elseif ($action === 'withdraw') {
            $status = 'withdrawn';
            if (empty($remarks))
                $remarks = 'Directly withdrawn by officer';
        }

        // Fetch match_id before updating for redirect context
        $stmtContext = $pdo->prepare("
            SELECT ms.match_id, u.email, u.first_name, u.last_name, 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 = ?
        ");
        $stmtContext->execute([$significationId]);
        $sigInfo = $stmtContext->fetch(PDO::FETCH_ASSOC);
        $matchId = $sigInfo['match_id'] ?? null;

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

        // Send Email Notification
        if ($sigInfo && !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);

            $formattedStatus = ucfirst($status);
            // For withdrawals and rejections, include the reason and reviewer role in the email
            $emailReason = in_array($action, ['withdraw', 'reject']) ? $remarks : '';
            sendMatchNotification($sigInfo['email'], $fullName, $formattedStatus, $sigInfo['match_name'], $schedule, $sigInfo['location'], $emailReason, $role);
        }

        if ($action === 'withdraw') {
            header("Location: ../api/request.php?tab=signified&success=withdrawn&match_id=" . $matchId);
            exit;
        }

        $_SESSION['success_msg'] = "Signification " . ucfirst($status) . " successfully!";
        header("Location: dashboard.php");
        exit;
    } catch (PDOException $e) {
        $_SESSION['error_msg'] = "Action failed: " . $e->getMessage();
        header("Location: dashboard.php");
        exit;
    }
}

// Status display: approved=Active, withdrawn=Inactive, declined=Unrecognized, etc.
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);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo $role; ?> Dashboard | NROI Portal
    </title>
    <!-- Google Fonts -->
    <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">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom 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">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
</head>

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



    <!-- Sidebar Navigation -->
    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($role === 'AC') {
                    echo 'A.C';
                } elseif ($role === 'AAC') {
                    echo 'A.A.C';
                } else {
                    echo htmlspecialchars($role ?? 'OFFICER');
                }
                ?>
            </div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link active">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <?php if (!$isSpecialRole): ?>
                <li class="sidebar-item">
                    <a href="notifications.php" class="sidebar-link">
                        <i class="fas fa-bell"></i> Notifications
                    </a>
                </li>
                <?php if ($role === 'AC' || $role === 'AAC'): ?>
                    <li class="sidebar-item">
                        <a href="../api/users.php" class="sidebar-link">
                            <i class="fas fa-user-friends"></i> Accounts
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="../api/matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="../api/request.php" class="sidebar-link">
                            <i class="fas fa-inbox"></i> For Approval
                        </a>
                    </li>
                <?php else: ?>
                    <li class="sidebar-item">
                        <a href="../api/matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                <?php endif; ?>
            <?php endif; ?>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
        </ul>

        <!-- Sidebar Profile -->
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar"
                    style="width: 35px; height: 35px; min-width: 35px; overflow: hidden; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #e2e8f0;">
                    <?php if (!empty($profilePhoto)): ?>
                        <img src="../<?php echo htmlspecialchars($profilePhoto); ?>" alt=""
                            style="width: 100%; height: 100%; object-fit: cover;">
                    <?php else: ?>
                        <span
                            style="font-weight: 700; color: #64748b; font-size: 0.8rem;"><?php echo strtoupper(substr($role ?? 'OF', 0, 2)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name"><?php echo htmlspecialchars(capitalizeWords($firstName)); ?></div>
                    <div class="sidebar-user-role"><?php echo htmlspecialchars($role ?? '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="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 Content Area -->
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>DASHBOARD</p>
                    </div>
                </div>
            </header>

            <?php if (isset($_SESSION['success_msg'])): ?>
                <div class="alert alert-success"
                    style="padding: 15px; background: #dcfce7; color: #16a34a; border-radius: 12px; margin-bottom: 24px; 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-bottom: 24px; 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 ($role === 'AC' || $role === 'AAC' || $isSpecialRole): ?>
                <!-- Area Indicator for Officers -->
                <?php if (!$isSpecialRole): ?>
                    <div style="display: flex; justify-content: flex-end; margin-bottom: 24px;">
                        <div
                            style="display: flex; align-items: center; gap: 12px; background: transparent; padding: 8px 16px; border-radius: 14px; border: 1px solid #e2e8f0; box-shadow: none;">
                            <div
                                style="width: 40px; height: 40px; background: #eff6ff; color: #2563eb; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem;">
                                <i class="fas fa-location-dot"></i>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <span
                                    style="font-size: 0.75rem; color: #64748b; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em;">Assigned
                                    Area:</span>
                                <span
                                    style="font-size: 1rem; font-weight: 800; color: #1e3a8a;"><?php echo htmlspecialchars(capitalizeWords($area ?: 'Not Set')); ?></span>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php
                // Pre-calculate counts
                if ($isSpecialRole) {
                    $stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE status != 'pending' AND (role NOT IN ('RM', 'PPSA', 'NROI') OR role IS NULL)");
                } else {
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE area = ? AND status != 'pending'");
                    $stmt->execute([$area]);
                }
                $totalUsers = $stmt->fetchColumn();
                ?>

                <!-- Stats Grid -->
                <div class="metrics-grid">
                    <?php if (!$isSpecialRole): ?>
                        <div class="metric-card-fancy">
                            <div class="metric-content">
                                <div class="metric-info">
                                    <h4>Total Users</h4>
                                    <span class="value"><?php echo $totalUsers; ?></span>
                                </div>
                                <div class="metric-icon-circle icon-blue">
                                    <i class="fas fa-users"></i>
                                </div>
                            </div>
                        </div>

                        <a href="../api/users.php?tab=applications" class="metric-card-fancy"
                            style="text-decoration: none; color: inherit; display: block;">
                            <div class="metric-content">
                                <div class="metric-info">
                                    <h4>Pending</h4>
                                    <?php
                                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE area = ? AND status = 'pending'");
                                    $stmt->execute([$area]);
                                    $pendingCount = $stmt->fetchColumn();
                                    ?>
                                    <span class="value"><?php echo $pendingCount; ?></span>
                                </div>
                                <div class="metric-icon-circle icon-orange">
                                    <i class="fas fa-clock"></i>
                                </div>
                            </div>
                        </a>
                    <?php endif; ?>
                </div>

                <?php if ($isSpecialRole): ?>
                    <?php
                    $stmtAreaData = $pdo->query("
                        SELECT area, COUNT(*) as member_count
                        FROM users
                        WHERE status = 'approved'
                          AND area IS NOT NULL AND area != ''
                          AND (role NOT IN ('RM','PPSA','NROI') OR role IS NULL)
                        GROUP BY area
                        ORDER BY CAST(area AS UNSIGNED) ASC
                    ");
                    $areaChartData = $stmtAreaData->fetchAll(PDO::FETCH_ASSOC);
                    $chartLabels = json_encode(array_map(fn($r) => 'Area ' . $r['area'], $areaChartData));
                    $chartValues = json_encode(array_column($areaChartData, 'member_count'));
                    ?>
                    <div
                        style="background:#fff; border-radius:18px; box-shadow:0 4px 24px rgba(30,58,138,0.08); padding:28px 32px; margin-bottom:24px;">
                        <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:20px;">
                            <div>
                                <h3 style="margin:0 0 4px; font-size:1.1rem; font-weight:800; color:#1e293b;">National Member
                                    Distribution</h3>
                                <p style="margin:0; font-size:0.82rem; color:#94a3b8; font-weight:500;">Approved members per
                                    area nationwide</p>
                            </div>
                            <div
                                style="background:#eff6ff; color:#2563eb; font-size:0.75rem; font-weight:800; padding:6px 14px; border-radius:20px; text-transform:uppercase; letter-spacing:0.05em;">
                                <i class="fas fa-chart-line" style="margin-right:5px;"></i> Area Overview
                            </div>
                        </div>
                        <div style="position:relative; height:280px;">
                            <!-- Total Members Indicator Overlay (Floating) -->
                            <div
                                style="position:absolute; top:-10px; left:50%; transform:translateX(-50%); text-align:center; z-index:10; pointer-events:none;">
                                <div
                                    style="font-size:0.66rem; font-weight:800; color:#94a3b8; text-transform:uppercase; letter-spacing:0.1em; margin-bottom:2px;">
                                    National Members</div>
                                <div style="font-size:2.5rem; font-weight:900; color:#1e3a8a; line-height:1; opacity: 0.9;">
                                    <?php echo $totalUsers; ?></div>
                            </div>
                            <canvas id="areaDistributionChart"></canvas>
                        </div>
                    </div>
                    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
                    <script>
                        (function () {
                            const labels = <?php echo $chartLabels; ?>;
                            const values = <?php echo $chartValues; ?>;
                            const ctx = document.getElementById('areaDistributionChart').getContext('2d');
                            const gradient = ctx.createLinearGradient(0, 0, 0, 280);
                            gradient.addColorStop(0, 'rgba(37,99,235,0.25)');
                            gradient.addColorStop(1, 'rgba(37,99,235,0.0)');
                            new Chart(ctx, {
                                type: 'line',
                                data: {
                                    labels: labels,
                                    datasets: [{
                                        label: 'Members',
                                        data: values,
                                        fill: true,
                                        backgroundColor: gradient,
                                        borderColor: '#2563eb',
                                        borderWidth: 3,
                                        pointBackgroundColor: '#fff',
                                        pointBorderColor: '#2563eb',
                                        pointBorderWidth: 3,
                                        pointRadius: 6,
                                        pointHoverRadius: 9,
                                        pointHoverBackgroundColor: '#2563eb',
                                        tension: 0.4
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    interaction: { mode: 'index', intersect: false },
                                    plugins: {
                                        legend: { display: false },
                                        tooltip: {
                                            backgroundColor: '#1e293b',
                                            titleColor: '#94a3b8',
                                            bodyColor: '#fff',
                                            bodyFont: { weight: 700, size: 14 },
                                            padding: 12,
                                            cornerRadius: 10,
                                            callbacks: {
                                                label: ctx => ' ' + ctx.parsed.y + ' member' + (ctx.parsed.y !== 1 ? 's' : '')
                                            }
                                        }
                                    },
                                    scales: {
                                        x: {
                                            grid: { display: false },
                                            ticks: { color: '#64748b', font: { weight: 600, size: 12 } },
                                            border: { display: false }
                                        },
                                        y: {
                                            beginAtZero: true,
                                            ticks: { color: '#94a3b8', font: { weight: 600 }, stepSize: 1, precision: 0 },
                                            grid: { color: 'rgba(0,0,0,0.05)' },
                                            border: { display: false }
                                        }
                                    }
                                }
                            });
                        })();
                    </script>
                <?php endif; ?>

                <?php
                // Score overview for ALL roles: global for special, area-scoped for AC/AAC
                $isAcAac = ($role === 'AC' || $role === 'AAC');
                if ($isSpecialRole) {
                    $stmtScores2 = $pdo->query("
                        SELECT u.first_name, u.last_name,
                            COALESCE((SELECT SUM(mp.points) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id=u.id),0) +
                            COALESCE((SELECT SUM(mm.points) FROM manual_match_points mm WHERE mm.user_id=u.id),0) AS total_points
                        FROM users u
                        WHERE u.status='approved' AND (u.role NOT IN ('RM','PPSA','NROI') OR u.role IS NULL)
                        ORDER BY total_points DESC LIMIT 10
                    ");
                    $stmtPerf2 = $pdo->query("
                        SELECT
                            COUNT(*) as total_members,
                            COALESCE(SUM(scores.user_total), 0) as grand_total,
                            COALESCE(MAX(scores.user_total), 0) as top_score
                        FROM (
                            SELECT u.id,
                                COALESCE((SELECT SUM(mp.points) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = u.id), 0) +
                                COALESCE((SELECT SUM(mm.points) FROM manual_match_points mm WHERE mm.user_id = u.id), 0)
                                AS user_total
                            FROM users u
                            WHERE u.status = 'approved' AND (u.role NOT IN ('RM','PPSA','NROI') OR u.role IS NULL)
                        ) AS scores
                    ");
                } else {
                    $stmtScores2 = $pdo->prepare("
                        SELECT u.first_name, u.last_name,
                            COALESCE((SELECT SUM(mp.points) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id=u.id),0) +
                            COALESCE((SELECT SUM(mm.points) FROM manual_match_points mm WHERE mm.user_id=u.id),0) AS total_points
                        FROM users u
                        WHERE u.status='approved' AND u.area=? AND (u.role NOT IN ('RM','PPSA','NROI') OR u.role IS NULL)
                        ORDER BY total_points DESC LIMIT 10
                    ");
                    $stmtScores2->execute([$area]);
                    $stmtPerf2 = $pdo->prepare("
                        SELECT
                            COUNT(*) as total_members,
                            COALESCE(SUM(scores.user_total), 0) as grand_total,
                            COALESCE(MAX(scores.user_total), 0) as top_score
                        FROM (
                            SELECT u.id,
                                COALESCE((SELECT SUM(mp.points) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = u.id), 0) +
                                COALESCE((SELECT SUM(mm.points) FROM manual_match_points mm WHERE mm.user_id = u.id), 0)
                                AS user_total
                            FROM users u
                            WHERE u.status = 'approved' AND u.area = ? AND (u.role NOT IN ('RM','PPSA','NROI') OR u.role IS NULL)
                        ) AS scores
                    ");
                    $stmtPerf2->execute([$area]);
                }
                $scoreRows2 = $stmtScores2->fetchAll(PDO::FETCH_ASSOC);
                $scoreLabels2 = json_encode(array_map(fn($r) => capitalizeWords($r['last_name'] . ', ' . $r['first_name']), $scoreRows2));
                $scoreValues2 = json_encode(array_column($scoreRows2, 'total_points'));
                $perf2 = $stmtPerf2->fetch(PDO::FETCH_ASSOC);
                $avgScore2 = ($perf2['total_members'] > 0) ? round($perf2['grand_total'] / $perf2['total_members'], 2) : 0;
                ?>

                <!-- Score Overview Chart -->
                <div
                    style="background:#fff; border-radius:18px; box-shadow:0 4px 24px rgba(30,58,138,0.08); padding:24px 28px; margin-bottom:20px;">
                    <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:18px;">
                        <div>
                            <h3 style="margin:0 0 4px; font-size:1rem; font-weight:800; color:#1e293b;">Total Score Overview
                            </h3>
                            <p style="margin:0; font-size:0.78rem; color:#94a3b8; font-weight:500;">
                                Top 10 members by accumulated points
                                <?php echo $isSpecialRole ? '(National)' : '(Your Area)'; ?>
                            </p>
                        </div>
                        <div
                            style="background:#f0fdf4; color:#059669; font-size:0.7rem; font-weight:800; padding:5px 12px; border-radius:20px; text-transform:uppercase;">
                            <i class="fas fa-trophy" style="margin-right:4px;"></i> Scores
                        </div>
                    </div>
                    <div style="position:relative; height:240px;">
                        <canvas id="officerScoreChart"></canvas>
                    </div>
                </div>

                <!-- Performance Summary Banner -->
                <div
                    style="background:linear-gradient(135deg,#1e3a8a 0%,#2563eb 100%); border-radius:16px; padding:22px 28px; margin-bottom:24px; display:flex; align-items:center; gap:32px; flex-wrap:wrap; box-shadow:0 8px 24px rgba(37,99,235,0.25);">
                    <div style="flex:1; min-width:140px; text-align:center;">
                        <div
                            style="font-size:0.68rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                            Members</div>
                        <div style="font-size:1.9rem; font-weight:900; color:#fff;">
                            <?php echo number_format($perf2['total_members']); ?>
                        </div>
                    </div>
                    <div style="width:1px; height:44px; background:rgba(255,255,255,0.15); flex-shrink:0;"></div>
                    <div style="flex:1; min-width:140px; text-align:center;">
                        <div
                            style="font-size:0.68rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                            Avg. Score</div>
                        <div style="font-size:1.9rem; font-weight:900; color:#fff;">
                            <?php echo number_format($avgScore2, 2); ?>
                        </div>
                    </div>
                    <div style="width:1px; height:44px; background:rgba(255,255,255,0.15); flex-shrink:0;"></div>
                    <div style="flex:1; min-width:140px; text-align:center;">
                        <div
                            style="font-size:0.68rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px;">
                            Highest Score</div>
                        <div style="font-size:1.9rem; font-weight:900; color:#fff;">
                            <?php echo number_format($perf2['top_score'], 2); ?>
                        </div>
                    </div>
                    <div style="flex:3; min-width:200px; padding-left:16px; border-left:1px solid rgba(255,255,255,0.15);">
                        <div
                            style="font-size:0.68rem; font-weight:800; color:rgba(255,255,255,0.6); text-transform:uppercase; letter-spacing:0.08em; margin-bottom:6px;">
                            <i class="fas fa-chart-bar" style="margin-right:5px;"></i> Performance Summary
                        </div>
                        <p style="margin:0; font-size:0.87rem; color:rgba(255,255,255,0.88); line-height:1.65;">
                            <?php
                            $scope = $isSpecialRole ? 'nationally' : 'in your area';
                            if ($perf2['total_members'] == 0) {
                                echo 'No member data available yet.';
                            } elseif ($avgScore2 >= 20) {
                                echo "Excellent performance $scope. Members are consistently accumulating high match points.";
                            } elseif ($avgScore2 >= 10) {
                                echo "Good overall performance $scope. Most members are actively participating in matches.";
                            } elseif ($avgScore2 >= 5) {
                                echo "Moderate performance $scope. Some members are active — encourage more participation.";
                            } else {
                                echo "Performance is still building up $scope. Encourage more match participation to improve scores.";
                            }
                            ?>
                        </p>
                    </div>
                </div>

                <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
                <script>
                    (function () {
                        const sCtx = document.getElementById('officerScoreChart').getContext('2d');
                        const sGrad = sCtx.createLinearGradient(0, 0, 0, 240);
                        sGrad.addColorStop(0, 'rgba(5,150,105,0.88)');
                        sGrad.addColorStop(1, 'rgba(5,150,105,0.28)');
                        new Chart(sCtx, {
                            type: 'bar',
                            data: {
                                labels: <?php echo $scoreLabels2; ?>,
                                datasets: [{ label: 'Points', data: <?php echo $scoreValues2; ?>, backgroundColor: sGrad, borderColor: '#059669', borderWidth: 0, borderRadius: 9, borderSkipped: false }]
                            },
                            options: {
                                responsive: true, maintainAspectRatio: false,
                                interaction: { mode: 'index', intersect: false },
                                plugins: { legend: { display: false }, tooltip: { backgroundColor: '#1e293b', titleColor: '#94a3b8', bodyColor: '#fff', bodyFont: { weight: 700, size: 13 }, padding: 10, cornerRadius: 10, callbacks: { label: c => ' ' + c.parsed.y.toFixed(2) + ' pts' } } },
                                scales: {
                                    x: { grid: { display: false }, ticks: { color: '#64748b', font: { weight: 600, size: 10 }, maxRotation: 35, minRotation: 20 }, border: { display: false } },
                                    y: { beginAtZero: true, ticks: { color: '#94a3b8', font: { weight: 600 } }, grid: { color: 'rgba(0,0,0,0.04)' }, border: { display: false } }
                                }
                            }
                        });
                    })();
                </script>

                <?php if (!$isSpecialRole): ?>
                    <!-- Active Call-up: matches up to the last day before match start (start_date > today) -->
                    <?php
                    $today = date('Y-m-d');

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

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

                    try {
                        $stmtActive = $pdo->prepare("
                    SELECT DISTINCT m.id, m.match_name, m.location, m.range_master, m.match_level, m.start_date, m.end_date, $rmSelect, $roSelect,
                    (SELECT COUNT(*) FROM match_significations WHERE match_id = m.id AND status = 'approved') as approved_count
                    FROM match_schedules m
                    JOIN match_significations ms ON ms.match_id = m.id
                    JOIN users u ON ms.user_id = u.id
                    WHERE u.area = ? AND m.end_date >= ?
                    AND (m.is_local = 1 OR m.is_retroactive = 1)
                    ORDER BY m.start_date ASC
                ");
                        $stmtActive->execute([$area, $today]);
                        $activeMatches = $stmtActive->fetchAll(PDO::FETCH_ASSOC);
                        $stmtSigs = $pdo->prepare("
                    SELECT ms.*, u.nroi_id, u.first_name, u.last_name,
                           (SELECT al.performed_by_role FROM activity_logs al
                            WHERE al.reference_type = 'match_signification' AND al.reference_id = ms.id
                              AND al.performed_by_role IN ('AC','AAC','ADMIN','RM')
                            ORDER BY al.created_at DESC LIMIT 1) as reviewer_role,
                           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
                    LEFT JOIN match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
                    WHERE ms.match_id = ? AND u.area = ?
                    ORDER BY 
                      CASE ms.status 
                        WHEN 'pending' THEN 1 
                        WHEN 'approved' THEN 2 
                        WHEN 'standby' THEN 3 
                        WHEN 'withdrawal_requested' THEN 4
                        WHEN 'withdrawn' THEN 7
                        WHEN 'deactivated' THEN 7
                        WHEN 'rejected' THEN 7
                        WHEN 'declined' THEN 7
                        ELSE 6 
                      END ASC, 
                      ms.created_at DESC
                ");
                    } catch (Exception $e) {
                        $activeMatches = [];
                    }
                    ?>
                    <div class="table-header" style="gap: 12px; flex-wrap: wrap;">
                        <h3 style="margin:0; width: 100%;">Active Call-up</h3>
                        <p style="margin: 0; font-size: 0.85rem; color: #64748b; width: 100%;">Call-ups for matches up to
                            the last day before match start.</p>
                    </div>

                    <?php if (empty($activeMatches)): ?>
                        <div style="text-align: center; color: #64748b; padding: 60px 20px;">
                            <i class="fas fa-folder-open"
                                style="font-size: 2rem; display: block; margin-bottom: 15px; opacity: 0.5;"></i>
                            No active call-up matches found yet.
                        </div>
                    <?php else: ?>
                        <?php foreach ($activeMatches as $match): ?>
                            <?php
                            $stmtSigs->execute([$match['id'], $area]);
                            $sigs = $stmtSigs->fetchAll(PDO::FETCH_ASSOC);

                            // Verify signatures exist on disk
                            foreach ($sigs as &$s) {
                                if ($s['match_completion_status'] === 'served' && !empty($s['rm_signature'])) {
                                    $sigPath = '../' . $s['rm_signature'];
                                    if (!file_exists($sigPath)) {
                                        $s['match_completion_status'] = 'incomplete';
                                    }
                                }
                            }
                            unset($s);
                            ?>
                            <div class="content-box"
                                style="margin-bottom: 20px; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px;">
                                <div style="display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 15px; margin-bottom: 15px; cursor: pointer;"
                                    onclick="toggleMatchTable(<?php echo $match['id']; ?>)">
                                    <div style="flex: 1; min-width: 200px;">
                                        <h4
                                            style="margin: 0 0 10px 0; color: #1e3a8a; font-size: 1.1rem; display: flex; align-items: center; gap: 8px;">
                                            <i class="fas fa-chevron-right toggle-icon-<?php echo $match['id']; ?>"
                                                style="font-size: 0.9rem; transition: transform 0.2s; color: #64748b;"></i>
                                            <?php echo htmlspecialchars($match['match_name']); ?>
                                        </h4>
                                        <div style="display: flex; flex-wrap: wrap; gap: 15px; font-size: 0.9rem; color: #475569;">
                                            <span>
                                                <i class="far fa-calendar-alt" style="color: #64748b; width: 14px;"></i>
                                                <strong>Schedule:</strong>
                                                <?php
                                                $sDate = strtotime($match['start_date']);
                                                $eDate = strtotime($match['end_date']);
                                                if (date('Y-m-d', $sDate) === date('Y-m-d', $eDate)) {
                                                    echo date('M d, Y', $sDate);
                                                } else {
                                                    echo date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);
                                                }
                                                ?>
                                            </span>
                                            <span><i class="fas fa-map-marker-alt" style="color: #64748b; width: 14px;"></i>
                                                <strong>Match Location:</strong>
                                                <?php echo htmlspecialchars($match['location']); ?></span>
                                            <span><i class="fas fa-user-tie" style="color: #64748b; width: 14px;"></i> <strong>Range
                                                    Master (RM):</strong>
                                                <?php echo !empty($match['rm_name']) ? htmlspecialchars(capitalizeWords($match['rm_name'])) : '---'; ?></span>
                                        </div>
                                    </div>
                                    <div style="text-align: right;">
                                        <?php
                                        $approved = $match['approved_count'];
                                        $limit = $match['ro_limit'];
                                        $isFull = ($limit > 0 && $approved >= $limit);
                                        ?>
                                        <span
                                            style="font-weight: 700; font-size: 0.85rem; color: <?php echo $isFull ? '#ef4444' : '#10b981'; ?>; background: <?php echo $isFull ? '#fef2f2' : '#f0fdf4'; ?>; padding: 4px 12px; border-radius: 20px; border: 1px solid <?php echo $isFull ? '#fecaca' : '#bbf7d0'; ?>;">
                                            <?php echo $approved; ?> / <?php echo $limit > 0 ? $limit : '∞'; ?> Slots
                                        </span>
                                        <?php if ($isFull): ?>
                                            <div
                                                style="font-size: 0.65rem; color: #ef4444; margin-top: 4px; font-weight: 700; text-transform: uppercase;">
                                                Match Full</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div id="match-table-<?php echo $match['id']; ?>"
                                    style="overflow-x:auto; display: none; margin-top: 15px; border-top: 1px solid #e2e8f0; padding-top: 15px;">
                                    <table class="modern-table">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>NROI ID</th>
                                                <th>Status</th>
                                                <th>Reason / Remarks</th>
                                                <th>Signified at</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($sigs)): ?>
                                                <tr>
                                                    <td colspan="6" style="text-align: center; color: #64748b;">No significations in
                                                        your area for this match.</td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($sigs as $s): ?>
                                                    <tr>
                                                        <td style="font-weight:700; color:#1e293b;">
                                                            <?php echo htmlspecialchars(capitalizeWords(($s['last_name'] ?? '') . ', ' . ($s['first_name'] ?? ''))); ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($s['nroi_id'] ?? '---'); ?></td>
                                                        <td>
                                                            <span
                                                                class="status-badge status-<?php echo htmlspecialchars($s['status']); ?>"><?php echo status_display_label($s['status']); ?></span>
                                                        </td>
                                                        <td>
                                                            <?php
                                                            $uReason = trim($s['withdrawal_reason'] ?? '');
                                                            $oNote = trim($s['officer_remarks'] ?? '');
                                                            if ($uReason !== '' || $oNote !== ''):
                                                                ?>
                                                                    <div style="font-size:0.78rem; color:#1e293b; line-height:1.4;">
                                                                        <?php if ($uReason !== ''): ?>
                                                                                <div style="margin-bottom:3px;">
                                                                                    <span style="font-weight:600; color:#92400e;">Your Reason (Request to Withdraw):</span><br>
                                                                                    <?php echo htmlspecialchars($uReason); ?>
                                                                                </div>
                                                                        <?php endif; ?>
                                                                        <?php if ($oNote !== ''): ?>
                                                                                <?php
                                                                                $rRole = strtoupper(trim($s['reviewer_role'] ?? ''));
                                                                                $baseLabel = match ($rRole) {
                                                                                    'AC' => 'AC note',
                                                                                    'AAC' => 'AAC note',
                                                                                    'ADMIN' => 'Admin note',
                                                                                    'RM' => 'RM note',
                                                                                    default => 'Officer note',
                                                                                };
                                                                                if ($s['status'] === 'standby') {
                                                                                    $roleLabel = $baseLabel . ' (Standby Note):';
                                                                                } elseif ($s['status'] === 'approved' && $uReason !== '') {
                                                                                    $roleLabel = $baseLabel . ' (Rejected to Withdraw Note):';
                                                                                } elseif (in_array($s['status'], ['declined', 'rejected'])) {
                                                                                    $roleLabel = $baseLabel . ' (Rejection/Decline Note):';
                                                                                } elseif ($s['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($oNote); ?>
                                                                                </div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                            <?php else: ?>
                                                                    <span style="color: #94a3b8; font-size: 0.75rem;">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td style="font-size:0.85rem; color:#64748b;">
                                                            <?php echo isset($s['created_at']) ? date('M d, Y h:i A', strtotime($s['created_at'])) : 'N/A'; ?>
                                                        </td>
                                                        <td>
                                                            <div class="action-btns" style="display: flex; gap: 5px; justify-content: center;">
                                                                <?php if ($s['match_completion_status'] === 'served'): ?>
                                                                    <span
                                                                        style="font-size: 0.7rem; color: #059669; font-weight: 700; background: #ecfdf5; padding: 4px 10px; border-radius: 6px; border: 1px solid #a7f3d0; letter-spacing: 0.5px;">SERVED</span>
                                                                <?php elseif ($s['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 ? "alert('This match is already full. You cannot approve more members.')" : "handleSignificationAction(" . $s['id'] . ", 'approve')"; ?>"
                                                                        <?php echo $isFull ? 'disabled' : ''; ?> title="Approve"><i
                                                                            class="fas fa-check"></i> Approve</button>
                                                                    <button class="icon-btn"
                                                                        style="background: #f59e0b; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                        onclick="handleSignificationAction(<?php echo $s['id']; ?>, 'standby')"
                                                                        title="Standby"><i class="fas fa-pause"></i> Standby</button>
                                                                    <button class="icon-btn btn-reject"
                                                                        style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                        onclick="openRejectModal(<?php echo $s['id']; ?>, '<?php echo htmlspecialchars(addslashes(($s['last_name'] ?? '') . ', ' . ($s['first_name'] ?? ''))); ?>')"
                                                                        title="Reject"><i class="fas fa-times"></i> Reject</button>
                                                                <?php elseif ($s['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 ? "alert('This match is already full. You cannot approve more members.')" : "handleSignificationAction(" . $s['id'] . ", 'approve')"; ?>"
                                                                        <?php echo $isFull ? 'disabled' : ''; ?> title="Approve"><i
                                                                            class="fas fa-check"></i> Approve</button>
                                                                    <button class="icon-btn btn-reject"
                                                                        style="width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                        onclick="openRejectModal(<?php echo $s['id']; ?>, '<?php echo htmlspecialchars(addslashes(($s['last_name'] ?? '') . ', ' . ($s['first_name'] ?? ''))); ?>')"
                                                                        title="Reject"><i class="fas fa-times"></i> Reject</button>
                                                                <?php elseif ($s['status'] === 'withdrawal_requested'): ?>
                                                                    <a href="../api/request.php" class="icon-btn"
                                                                        style="background:#fef2f2; color:#dc2626; text-decoration: none; display: inline-flex; align-items: center; justify-content: center;"
                                                                        title="Review Withdrawal"><i class="fas fa-exclamation-triangle"></i></a>
                                                                <?php elseif ($s['status'] === 'approved'): ?>
                                                                    <button class="icon-btn"
                                                                        style="background: #ef4444; color: white; width: auto; padding: 5px 12px; font-size: 0.75rem;"
                                                                        onclick="handleDirectWithdraw(<?php echo $s['id']; ?>)"
                                                                        title="Direct Withdraw">Withdraw</button>
                                                                <?php else: ?>
                                                                    <span style="font-size: 0.8rem; color: #64748b;">—</span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

            </div>
        <?php endif; // End Active Call-up content ?>
        </div>
    <?php endif; // End AC/AAC/SpecialRole block ?>
    </main>
    </div> <!-- End Main Layout -->

    <!-- Profile Completion Modal (First Login Only) -->
    <div id="profileCompletionModal" class="modal <?php echo $isFirstLogin ? 'active' : ''; ?>"
        style="z-index: 9999; background: rgba(0,0,0,0.8);">
        <div class="modal-content" style="max-width: 550px; border-radius: 20px;">
            <div style="text-align: center; margin-bottom: 25px;">
                <div
                    style="width: 80px; height: 80px; background: #f0fdf4; color: #10b981; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; font-size: 2rem;">
                    <i class="fas fa-user-check"></i>
                </div>
                <h2 style="margin: 0; color: #1e293b;">Complete Your Profile</h2>
                <p style="color: #64748b; margin-top: 8px;">Welcome! Please provide your official details to proceed.
                </p>
            </div>

            <form id="profileCompletionForm">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <div class="form-group">
                        <label class="form-label"
                            style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">First
                            Name</label>
                        <input type="text" name="first_name" class="form-input"
                            value="<?php echo htmlspecialchars($userFirstName); ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label"
                            style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Middle
                            Name</label>
                        <input type="text" name="middle_name" class="form-input"
                            value="<?php echo htmlspecialchars($userMiddleName); ?>">
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <div class="form-group">
                        <label class="form-label"
                            style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Last
                            Name</label>
                        <input type="text" name="last_name" class="form-input"
                            value="<?php echo htmlspecialchars($userLastName); ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label"
                            style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Extension</label>
                        <input type="text" name="extension" class="form-input" placeholder="Jr, Sr, etc."
                            value="<?php echo htmlspecialchars($userExtension); ?>">
                    </div>
                </div>

                <div class="form-group" style="margin-bottom: 15px;">
                    <label class="form-label"
                        style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Email
                        Address</label>
                    <input type="email" name="email" class="form-input"
                        value="<?php echo htmlspecialchars($userEmail); ?>" required>
                </div>

                <div class="form-group" style="margin-bottom: 15px;">
                    <label class="form-label"
                        style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Mobile/Telephone
                        Number</label>
                    <input type="text" name="phone_number" class="form-input"
                        value="<?php echo htmlspecialchars($userPhone); ?>" required>
                </div>

                <div class="form-group" style="margin-bottom: 25px;">
                    <label class="form-label"
                        style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Position</label>
                    <input type="text" name="position" class="form-input" placeholder="e.g. Secretary, Director, etc."
                        value="<?php echo htmlspecialchars($userPosition); ?>" required>
                </div>

                <div
                    style="background: #f8fafc; padding: 20px; border-radius: 12px; border: 1px solid #e2e8f0; margin-bottom: 25px;">
                    <h4
                        style="margin: 0 0 15px 0; color: #1e293b; font-size: 0.95rem; display: flex; align-items: center; gap: 8px;">
                        <i class="fas fa-lock" style="color: #64748b;"></i> Account Credentials
                    </h4>

                    <div class="form-group" style="margin-bottom: 15px;">
                        <label class="form-label"
                            style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Preferred
                            Username</label>
                        <input type="text" name="new_username" class="form-input"
                            value="<?php echo htmlspecialchars($userUsername); ?>" required>
                        <p style="font-size: 0.75rem; color: #64748b; margin-top: 5px;">You will use this to log in from
                            now on.</p>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label class="form-label"
                                style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">New
                                Password</label>
                            <input type="password" name="new_password" class="form-input"
                                placeholder="Min. 8 characters" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label"
                                style="font-weight: 700; color: #1e293b; margin-bottom: 8px; display: block;">Confirm
                                Password</label>
                            <input type="password" name="confirm_password" class="form-input"
                                placeholder="Repeat password" required>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn-primary"
                    style="width: 100%; height: 50px; font-size: 1rem; background: #10b981; border-color: #10b981; border-radius: 12px; font-weight: 700; margin: 0; transition: all 0.3s ease;">Save
                    & Continue</button>
            </form>
        </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="signification_action" id="modal_signification_action" value="reject">
                <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; transition: all 0.2s;">
                        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; transition: all 0.2s;">
                        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>
            <form method="POST">
                <input type="hidden" name="signification_action" value="withdraw">
                <input type="hidden" name="signification_id" id="direct_withdraw_id">
                <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" 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="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; cursor: pointer; font-weight: 700; padding: 8px 16px; border-radius: 6px; font-size: 0.85rem; transition: all 0.2s;">
                        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; transition: all 0.2s;">
                        Withdraw
                    </button>
                </div>
            </form>
        </div>
    </div>



    <script src="../assets/js/loader.js"></script>
    <script>
        // Profile Dropdown Toggle
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');

        if (profileToggle && profileDropdown) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });

            // Close dropdown when clicking outside
            document.addEventListener('click', (e) => {
                if (!profileToggle.contains(e.target) && !profileDropdown.contains(e.target)) {
                    profileDropdown.classList.remove('active');
                }
            });
        }

        // Handle Signification Actions
        function handleSignificationAction(significationId, action) {
            if (action === 'approve') {
                if (confirm('Are you sure you want to approve this signification?')) {
                    submitSignificationAction(significationId, 'approve', '');
                }
            } else if (action === 'standby') {
                openRemarksModal(significationId, 'standby');
            }
        }

        function handleDirectWithdraw(significationId) {
            document.getElementById('direct_withdraw_id').value = significationId;
            document.getElementById('directWithdrawModal').classList.add('active');
        }



        function submitSignificationAction(significationId, action, remarks) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="signification_action" value="${action}">
                <input type="hidden" name="signification_id" value="${significationId}">
                <input type="hidden" name="remarks" value="${remarks}">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        function openRemarksModal(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_signification_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') {
                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') {
                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 openRejectModal(significationId, memberName) {
            openRemarksModal(significationId, 'reject');
        }

        function closeModals() {
            document.querySelectorAll('.modal').forEach(m => m.classList.remove('active'));
        }

        function toggleMatchTable(matchId) {
            const table = document.getElementById('match-table-' + matchId);
            const icon = document.querySelector('.toggle-icon-' + matchId);
            if (table.style.display === 'none' || table.style.display === '') {
                table.style.display = 'block';
                if (icon) icon.style.transform = 'rotate(90deg)';
            } else {
                table.style.display = 'none';
                if (icon) icon.style.transform = 'rotate(0deg)';
            }
        }

        // --- Profile Completion Logic for First Login ---
        <?php if ($isFirstLogin): ?>
            window.addEventListener('DOMContentLoaded', () => {
                document.getElementById('profileCompletionModal').classList.add('active');
            });
        <?php endif; ?>

        document.getElementById('profileCompletionForm')?.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn = this.querySelector('button[type="submit"]');
            const originalText = btn.textContent;

            // Password match validation
            const pass = this.querySelector('input[name="new_password"]').value;
            const conf = this.querySelector('input[name="confirm_password"]').value;

            if (pass !== conf) {
                alert('Passwords do not match!');
                return;
            }

            if (pass.length < 8) {
                alert('Password must be at least 8 characters long!');
                return;
            }

            // Email validation
            const email = this.querySelector('input[name="email"]').value;
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert('Please enter a valid email address!');
                return;
            }

            // PH Phone validation (11 digits, starts with 09)
            const phone = this.querySelector('input[name="phone_number"]').value;
            const phoneRegex = /^09\d{9}$/;
            if (!phoneRegex.test(phone)) {
                alert('Please enter a valid 11-digit Philippine mobile number starting with 09! (e.g., 09123456789)');
                return;
            }

            // Username validation (alphanumeric, no spaces)
            const username = this.querySelector('input[name="new_username"]').value;
            if (!/^[a-zA-Z0-9_.-]+$/.test(username)) {
                alert('Username can only contain letters, numbers, underscores, dots, and hyphens.');
                return;
            }

            btn.textContent = 'Saving Profile...';
            btn.disabled = true;

            const formData = new FormData(this);
            fetch('../api/complete_profile.php', {
                method: 'POST',
                body: formData
            })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                        btn.textContent = originalText;
                        btn.disabled = false;
                    }
                })
                .catch(err => {
                    console.error(err);
                    btn.textContent = originalText;
                    btn.disabled = false;
                    alert('An error occurred. Please try again.');
                });
        });
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>