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

$is_admin = isset($_SESSION['admin_id']);
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
$is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
$is_officer_role = $is_ac || $is_aac; // AC and AAC are officers
$is_officer = isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['AC', 'AAC', 'NROI', 'PPSA']);
$is_special = isset($_SESSION['user_role']) && in_array(strtoupper($_SESSION['user_role']), ['PPSA', 'NROI']);

// 1. Initial Access Check - Allow Admin and AC/AAC Officers.
if (!$is_admin && !$is_officer_role) {
    if ($is_officer) {
        header("Location: ../officer/dashboard.php");
    } else {
        header("Location: ../index.php");
    }
    exit;
}

// Define allowed ranks based on current user role for filtering and assignment
$allowedRanks = [];
if ($is_admin) {
    $allowedRanks = ['AC', 'AAC', 'R.O', 'C.R.O', 'NROI', 'PPSA'];
} elseif ($is_ac) {
    $allowedRanks = ['AAC', 'R.O', 'C.R.O'];
} elseif ($is_aac) {
    $allowedRanks = ['R.O', 'C.R.O'];
}

// Fetch Officer Area for filtering if not admin
$officerArea = null;
if ($is_officer_role) {
    $stmt = $pdo->prepare("SELECT area FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $officerArea = $stmt->fetchColumn();
}

// 2. Fetch user info for officer role
$officerName = '';
$officerUserId = null;
$officerRole = '';
if ($is_officer_role) {
    $officerName = capitalizeWords($_SESSION['name'] ?? 'Officer');
    $officerUserId = $_SESSION['user_id'] ?? null;
    $officerRole = $_SESSION['user_role'] ?? '';
}

// Status display labels: Approved=Active, Deactivated/Withdrawn=Inactive, Rejected=Unrecognized, Pending=Pending
function status_display_label($status)
{
    $labels = ['approved' => 'Active', 'deactivated' => 'Inactive', 'withdrawn' => 'Inactive', 'rejected' => 'Unrecognized', 'pending' => 'Pending'];
    return $labels[strtolower(trim((string) $status))] ?? $status;
}

// 3. Fetch filter from URL
$tabFilter = $_GET['tab'] ?? 'all';
// Officers (AC/AAC) should not see the Pending or Archived tabs; force them away from those
// Officers (AC/AAC) should not see the Pending (admin-global) or Archived tabs; force them away from those
if (!$is_admin && in_array($tabFilter, ['pending', 'archived'], true)) {
    $tabFilter = 'all';
}
// Map 'applications' tab to 'pending' status for officers
if ($tabFilter === 'applications' && $is_officer_role) {
    // Treat 'applications' as a valid tab for officers
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Accounts | NROI Portal</title>
    <!-- CSS and 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">
    <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">
</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 ($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 active">
                        <i class="fas fa-user-friends"></i> Accounts
                    </a>
                </li>
                <?php if ($is_admin || $is_officer_role): ?>
                    <li class="sidebar-item" style="display:none;"> <!-- Hidden in sidebar, subtab of Accounts -->
                        <a href="users.php?tab=applications">Applications</a>
                    </li>
                <?php endif; ?>
                <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="../api/matches.php" class="sidebar-link">
                        <i class="fas fa-trophy"></i> Matches
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="request.php" class="sidebar-link">
                        <i class="fas fa-inbox"></i> For Approval
                    </a>
                </li>
                <li class="sidebar-item">
                    <a href="points_card.php" class="sidebar-link">
                        <i class="fas fa-id-card"></i> Points Card
                    </a>
                </li>
                <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 active">
                            <i class="fas fa-user-friends"></i> Accounts
                        </a>
                    </li>
                    <?php if ($is_admin || $is_officer_role): ?>
                        <li class="sidebar-item" style="display:none;"> <!-- Hidden in sidebar, subtab of Accounts -->
                            <a href="users.php?tab=applications">Applications</a>
                        </li>
                    <?php endif; ?>
                    <li class="sidebar-item">
                        <a href="matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="request.php" class="sidebar-link">
                            <i class="fas fa-inbox"></i> For Approval
                        </a>
                    </li>
                <?php endif; ?>
                <li class="sidebar-item">
                    <a href="points_card.php" class="sidebar-link">
                        <i class="fas fa-id-card"></i> Points Card
                    </a>
                </li>
            <?php endif; ?>
        </ul>

        <!-- Sidebar Profile -->
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">
                    <?php
                    if ($is_admin) {
                        echo 'AD';
                    } 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' : htmlspecialchars($officerName); ?>
                    </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
            // 3. Data Fetching
            $search = $_GET['search'] ?? '';
            $sort = $_GET['sort'] ?? 'rank_asc';
            $rankFilter = $_GET['rank_filter'] ?? '';
            $year = 2026;

            $query = "SELECT u.*, 
                 (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = u.id) as manual_total
                 FROM users u WHERE (u.role != 'RM' OR u.role IS NULL)";

            if (!empty($search)) {
                $searchTerms = explode(' ', trim($search));
                foreach ($searchTerms as $term) {
                    if (empty($term))
                        continue;
                    $quotedTerm = $pdo->quote("%$term%");
                    $query .= " AND (u.first_name LIKE $quotedTerm 
                                OR u.middle_name LIKE $quotedTerm 
                                OR u.last_name LIKE $quotedTerm 
                                OR u.email LIKE $quotedTerm 
                                OR u.nroi_id LIKE $quotedTerm)";
                }
            }

            if (!empty($rankFilter)) {
                if ($rankFilter === 'R.O') {
                    $query .= " AND (u.role = 'R.O' OR u.role = 'RO' OR u.role = 'member' OR u.role = '' OR u.role IS NULL)";
                } else if ($rankFilter === 'C.R.O') {
                    $query .= " AND (u.role = 'C.R.O' OR u.role = 'CRO')";
                } else {
                    $query .= " AND u.role = " . $pdo->quote($rankFilter);
                }
            }

            // Filter by officer area and handleable roles if not admin
            if ($officerArea) {
                $query .= " AND area = " . $pdo->quote($officerArea);

                if ($is_ac) {
                    // AC handles AAC, RO, CRO
                    $query .= " AND (role IN ('AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member') OR role IS NULL OR role = '')";
                } elseif ($is_aac) {
                    // AAC handles RO, CRO
                    $query .= " AND (role IN ('R.O', 'C.R.O', 'RO', 'CRO', 'member') OR role IS NULL OR role = '')";
                }
            }
            if ($tabFilter === 'pending')
                $query .= " AND status = 'pending'";
            elseif ($tabFilter === 'rejected')
                $query .= " AND status = 'rejected'";
            elseif ($tabFilter === 'members')
                $query .= " AND role IN ('R.O', 'C.R.O') AND status != 'pending' AND status != 'rejected'";
            elseif ($tabFilter === 'officers')
                $query .= " AND role IN ('AC', 'AAC')";
            elseif ($tabFilter === 'visitors')
                $query .= " AND role IN ('NROI', 'PPSA')";

            // Non-admins (AC/AAC) should never see pending accounts in any list
            if (!$is_admin && $tabFilter !== 'applications') {
                $query .= " AND status != 'pending'";
            }
            if ($tabFilter === 'applications') {
                $query .= " AND status = 'pending'";
            }

            // Exclude archived users from all non-archived tabs
            if ($tabFilter !== 'archived') {
                $query .= " AND u.id NOT IN (SELECT user_id FROM removed_accounts)";
            }

            // Determine Rank Order
            $rankOrder = "'AC', 'AAC', 'R.O', 'RO', 'C.R.O', 'CRO', 'NROI', 'PPSA'";
            if ($sort === 'rank_desc') {
                $rankOrder = "'PPSA', 'NROI', 'C.R.O', 'CRO', 'R.O', 'RO', 'AAC', 'AC'";
            }

            $query .= " ORDER BY last_name ASC"; // Base sort, will re-sort in PHP after points calc
            
            $stmt = $pdo->query($query);
            $users = $stmt->fetchAll();

            // Recalculate totals in PHP to account for missing signature files (Consistent with member summary)
            if (!empty($users)) {
                $uIds = array_column($users, 'id');
                $placeholders = implode(',', array_fill(0, count($uIds), '?'));

                $chkStmt = $pdo->prepare("SELECT user_id, points, rm_signature FROM match_points WHERE user_id IN ($placeholders) AND rm_signature IS NOT NULL AND rm_signature != '' AND rm_signature != 'DEMERIT'");
                $chkStmt->execute($uIds);
                $allMatches = $chkStmt->fetchAll();

                $matchTotals = [];
                foreach ($allMatches as $m) {
                    if (!empty($m['rm_signature']) && file_exists('../' . $m['rm_signature'])) {
                        $matchTotals[$m['user_id']] = ($matchTotals[$m['user_id']] ?? 0) + (float) $m['points'];
                    }
                }

                foreach ($users as &$usr) {
                    $usr['total_points'] = (float) ($usr['manual_total'] ?? 0) + (float) ($matchTotals[$usr['id']] ?? 0);
                }
                unset($usr);

                // Perform final sorting to match intended ordering including calculated points
                usort($users, function ($a, $b) use ($sort, $rankOrder) {
                    // Extract rank priority
                    $pArr = explode(',', str_replace("'", "", $rankOrder));
                    $pArr = array_map('trim', $pArr);
                    $pMap = array_flip($pArr);

                    $getRank = function ($u) {
                        $r = $u['role'] ?? '';
                        if ($r === '' || $r === 'member' || $r === 'RO')
                            return 'R.O';
                        if ($r === 'CRO')
                            return 'C.R.O';
                        return $r;
                    };

                    $rA = $getRank($a);
                    $rB = $getRank($b);
                    $pA = $pMap[$rA] ?? 99;
                    $pB = $pMap[$rB] ?? 99;

                    if ($pA !== $pB)
                        return $pA - $pB;
                    if ($b['total_points'] != $a['total_points'])
                        return $b['total_points'] > $a['total_points'] ? 1 : -1;
                    return strcasecmp($a['last_name'], $b['last_name']);
                });
            }
            ?>

            <div
                style="display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; margin-bottom: 30px; flex-wrap: wrap;">
                <div style="display: flex; flex-direction: column; gap: 20px; flex: 1; min-width: 300px;">
                    <div class="filter-tabs" style="margin-bottom: 0;">
                        <a href="users.php" class="tab-btn <?php echo $tabFilter == 'all' ? 'active' : ''; ?>">All
                            Users</a>
                        <?php if ($is_admin): ?>
                            <a href="users.php?tab=pending"
                                class="tab-btn <?php echo $tabFilter == 'pending' ? 'active' : ''; ?>">Pending </a>
                        <?php elseif ($is_officer_role): ?>
                            <a href="users.php?tab=applications"
                                class="tab-btn <?php echo $tabFilter == 'applications' ? 'active' : ''; ?>">Applications</a>
                        <?php endif; ?>
                        <?php if ($is_admin): ?>
                            <a href="users.php?tab=archived"
                                class="tab-btn <?php echo $tabFilter == 'archived' ? 'active' : ''; ?>">Archived</a>
                        <?php endif; ?>
                    </div>

                    <!-- Improved Search & Filter Bar -->
                    <div class="search-bar-container">
                        <form method="GET" id="searchForm"
                            style="display: flex; gap: 10px; max-width: 900px; flex-wrap: wrap;">
                            <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tabFilter); ?>">
                            <input type="hidden" name="sort" value="<?php echo htmlspecialchars($sort); ?>">

                            <div style="position: relative; flex: 2; 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" name="search" id="accountSearchInput"
                                    placeholder="Search by name, email, or NROI ID..."
                                    value="<?php echo htmlspecialchars($search); ?>"
                                    style="width: 100%; padding: 10px 15px 10px 40px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 0.9rem; outline: none; transition: all 0.2s; background: white;">
                            </div>

                            <div style="min-width: 150px; flex: 1;">
                                <select name="rank_filter" id="rankFilterSelect" onchange="this.form.submit()"
                                    style="width: 100%; padding: 10px 15px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 0.9rem; outline: none; background: white; cursor: pointer;">
                                    <option value="">All Ranks</option>
                                    <?php
                                    foreach ($allowedRanks as $r) {
                                        $selected = ($rankFilter === $r) ? 'selected' : '';
                                        echo "<option value=\"$r\" $selected>$r</option>";
                                    }
                                    ?>
                                </select>
                            </div>

                            <button type="submit" class="btn-primary"
                                style="margin: 0; width: auto; padding: 0 20px; height: 42px; font-size: 0.9rem;">Search</button>
                            <?php if (!empty($search) || !empty($rank_filter)): ?>
                                <a href="users.php?tab=<?php echo htmlspecialchars($tabFilter); ?>&sort=<?php echo htmlspecialchars($sort); ?>"
                                    class="btn-secondary"
                                    style="margin: 0; width: auto; padding: 0 15px; height: 42px; display: flex; align-items: center; text-decoration: none; border: 1px solid #e2e8f0; color: #64748b; background: white; border-radius: 10px;">Clear</a>
                            <?php endif; ?>

                            <?php if ($is_admin): ?>
                                <button type="button" class="btn-primary" onclick="openCreateAccountModal()"
                                    style="margin: 0; width: auto; padding: 0 20px; height: 42px; font-size: 0.9rem; background: #10b981; border-color: #10b981; display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-user-plus"></i> Create Account
                                </button>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>

            </div>

            <?php if ($tabFilter !== 'archived'): ?>
                <div class="content-box" style="padding: 0;">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th class="col-details">User Details</th>
                                <th class="col-role">
                                    <a href="?tab=<?php echo $tabFilter; ?>&sort=<?php echo $sort === 'rank_asc' ? 'rank_desc' : 'rank_asc'; ?>&search=<?php echo urlencode($search); ?>&rank_filter=<?php echo urlencode($rankFilter); ?>"
                                        style="text-decoration:none; color:inherit; display:flex; align-items:center; gap:5px; width: fit-content;">
                                        Rank & Status
                                        <i class="fas fa-sort<?php echo strpos($sort, 'rank') === 0 ? ($sort === 'rank_asc' ? '-up' : '-down') : ''; ?>"
                                            style="font-size:0.75rem; opacity:0.8; color: var(--primary-color);"></i>
                                    </a>
                                </th>
                                <?php if ($is_admin): ?>
                                    <th class="col-area">Area</th>
                                <?php endif; ?>
                                <th class="col-id">NROI ID</th>
                                <th class="col-contact">Contact</th>
                                <th>Points (Total)</th>
                                <th class="col-status">Status</th>
                                <th class="col-actions">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="accountsTableBody">
                            <?php if (empty($users)): ?>
                                <tr class="no-results-row">
                                    <td colspan="<?php echo $is_admin ? '7' : '6'; ?>"
                                        style="text-align:center; padding:100px; color:#64748b;">No accounts found
                                        here.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <!-- Dynamic No Results Row (Hidden by default) -->
                                <tr id="jsNoResultsRow" style="display: none;">
                                    <td colspan="<?php echo $is_admin ? '7' : '6'; ?>"
                                        style="text-align:center; padding:100px; color:#64748b;">No matching accounts found for
                                        your search.</td>
                                </tr>
                                <?php foreach ($users as $user): ?>
                                    <?php $userData = htmlspecialchars(json_encode($user)); ?>
                                    <tr class="<?php echo ($user['status'] == 'deactivated' || $user['status'] == 'rejected') ? 'row-deactivated' : ''; ?>"
                                        onclick="openUserOptionsModal(this)" data-user='<?php echo $userData; ?>'
                                        data-points-link="member_points_summary.php?user_id=<?php echo $user['id']; ?>">
                                        <td class="col-details">
                                            <div class="user-info-cell">
                                                <div class="user-avatar"
                                                    style="width:40px; height:40px; font-size: 0.9rem; background: #eff6ff; color: var(--primary-color); font-weight: 800; overflow: hidden;">
                                                    <?php if (!empty($user['profile_photo']) && is_file(__DIR__ . '/../' . $user['profile_photo'])): ?>
                                                        <img src="../<?php echo htmlspecialchars($user['profile_photo']); ?>" alt=""
                                                            style="width:100%; height:100%; object-fit:cover; display:block;">
                                                    <?php else: ?>
                                                        <?php echo strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)); ?>
                                                    <?php endif; ?>
                                                </div>
                                                <div>
                                                    <div style="font-weight:700; color: #1e293b; font-size: 0.95rem;">
                                                        <?php echo htmlspecialchars(capitalizeWords($user['first_name'] . ' ' . ($user['middle_name'] ? $user['middle_name'] . ' ' : '') . $user['last_name'])); ?>
                                                    </div>
                                                    <div style="font-size:0.75rem; color: #64748b;">
                                                        <?php echo htmlspecialchars($user['email']); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="col-role">
                                            <div style="display: flex; flex-direction: column; gap: 4px;">
                                                <span
                                                    class="role-badge role-<?php echo ($user['role'] && $user['role'] !== 'member') ? $user['role'] : 'R.O'; ?>">
                                                    <?php echo ($user['role'] && $user['role'] !== 'member') ? $user['role'] : 'R.O'; ?>
                                                </span>
                                                <?php
                                                $displayRole = ($user['role'] && $user['role'] !== 'member') ? $user['role'] : 'R.O';
                                                if ($displayRole !== 'AC' && $displayRole !== '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((strtoupper($user['rank']) == 'REGULAR' || strtoupper($user['rank']) == 'OJT' || strtoupper($user['rank']) == 'INTERN') ? $user['rank'] : 'Regular'); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <?php if ($is_admin): ?>
                                            <td class="col-area">
                                                <?php if ($user['area']): ?>
                                                    <span class="area-tag" style="margin:0; font-weight: 600; color: #475569;">
                                                        <i class="fas fa-location-dot"
                                                            style="color:var(--primary-color); font-size: 0.75rem;"></i>
                                                        <?php echo htmlspecialchars($user['area']); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span style="color: #cbd5e1; font-size: 0.8rem;">---</span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endif; ?>
                                        <td class="col-id">
                                            <span class="user-id-small"
                                                style="font-size: 0.9rem; padding: 4px 8px;"><?php echo $user['nroi_id'] ?: '---'; ?></span>
                                        </td>
                                        <td class="col-contact">
                                            <div style="font-weight: 500; font-size: 0.85rem;">
                                                <?php echo htmlspecialchars($user['phone_number']); ?>
                                            </div>
                                        </td>
                                        <td style="font-weight: 700; color: #1e3a8a; font-size: 0.95rem;">
                                            <?php echo number_format($user['total_points'] ?? 0, 2); ?>
                                        </td>
                                        <td class="col-status">
                                            <span
                                                class="status-badge status-<?php echo $user['status']; ?>"><?php echo status_display_label($user['status']); ?></span>
                                        </td>
                                        <td class="col-actions" onclick="event.stopPropagation()">
                                            <div class="action-btns">
                                                <?php if ($user['status'] === 'pending'): ?>
                                                    <?php
                                                    $isPPSANROI = in_array(strtoupper($user['role'] ?? ''), ['PPSA', 'NROI']);
                                                    $isFirstLogin = (int) ($user['is_first_login'] ?? 0) === 1;
                                                    ?>
                                                    <?php if ($isPPSANROI && $isFirstLogin): ?>
                                                        <button class="icon-btn" style="background:#fee2e2; color:#dc2626;"
                                                            title="Remove Account" onclick="deleteUser(<?php echo $user['id']; ?>)">
                                                            <i class="fas fa-user-minus"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <?php if ($is_admin || $is_officer_role): ?>
                                                            <button class="icon-btn btn-approve" title="Approve"
                                                                onclick="openApproveModal(<?php echo $user['id']; ?>, '<?php echo addslashes($user['first_name'] . ' ' . $user['last_name']); ?>', '<?php echo addslashes($user['area'] ?? ''); ?>', '<?php echo addslashes($user['role'] ?? ''); ?>', '<?php echo addslashes($user['rank'] ?? ''); ?>')">
                                                                <i class="fas fa-check"></i>
                                                            </button>
                                                        <?php endif; ?>
                                                        <button class="icon-btn btn-reject" title="Reject"
                                                            onclick="rejectUser(<?php echo $user['id']; ?>)">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php elseif ($user['status'] === 'rejected'): ?>
                                                    <?php if ($is_admin): ?>
                                                        <button class="icon-btn" style="background:#fef2f2; color:#dc2626;"
                                                            title="Permanently Delete" onclick="deleteUser(<?php echo $user['id']; ?>)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <?php
                                                    $isTargetSelf = (int) $user['id'] === (int) ($_SESSION['user_id'] ?? 0);
                                                    $canOfficerEdit = false;
                                                    if (!$isTargetSelf) {
                                                        if ($is_ac) {
                                                            $canOfficerEdit = in_array($user['role'], ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
                                                        } elseif ($is_aac) {
                                                            $canOfficerEdit = in_array($user['role'], ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
                                                        }
                                                    }
                                                    ?>
                                                    <?php if ($is_admin): ?>
                                                        <button class="icon-btn btn-edit" style="background:#f1f5f9; color:#2563eb;"
                                                            title="Edit"
                                                            onclick="openEditModal(<?php echo $user['id']; ?>, '<?php echo ($user['role'] && $user['role'] !== 'member') ? $user['role'] : 'R.O'; ?>', '<?php echo addslashes($user['area']); ?>', '<?php echo addslashes($user['rank'] ?? ''); ?>')">
                                                            <i class="fas fa-pen"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <?php if ($is_aac || $is_ac || $is_admin): ?>
                                                        <button class="icon-btn"
                                                            style="background:<?php echo $user['status'] == 'deactivated' ? '#f0fdf4' : '#fff7ed'; ?>; color:<?php echo $user['status'] == 'deactivated' ? '#16a34a' : '#ea580c'; ?>;"
                                                            title="<?php echo $user['status'] == 'deactivated' ? 'Activate' : 'Deactivate'; ?>"
                                                            onclick="updateStatus(<?php echo $user['id']; ?>, '<?php echo $user['status'] == 'deactivated' ? 'approved' : 'deactivated'; ?>')">
                                                            <i
                                                                class="fas fa-<?php echo $user['status'] == 'deactivated' ? 'check-circle' : 'ban'; ?>"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <?php if ($canOfficerEdit): ?>
                                                        <button class="icon-btn" style="background:#fee2e2; color:#dc2626;"
                                                            title="Remove to Archive"
                                                            onclick="confirmOfficerRemoval(<?php echo $user['id']; ?>, '<?php echo addslashes($user['first_name'] . ' ' . $user['last_name']); ?>')">
                                                            <i class="fas fa-user-minus"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <?php if ($is_admin): ?>
                                                        <button class="icon-btn" style="background:#fef2f2; color:#dc2626;" title="Delete"
                                                            onclick="deleteUser(<?php echo $user['id']; ?>)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <?php if ($tabFilter === 'archived'): ?>
                <div class="content-box" style="margin-top: 25px;">
                    <div class="table-header">
                        <h3>Archived Accounts</h3>
                        <p style="margin:0; font-size:0.85rem; color:#64748b;">Temporary and permanent removals log</p>
                    </div>

                    <div style="overflow-x:auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"><input type="checkbox" id="selectAllArchived"
                                            onclick="toggleAllArchived(this)" style="cursor: pointer;"></th>
                                    <th>Name</th>
                                    <th>NROI ID</th>
                                    <th>Rank</th>
                                    <th>Removed By</th>
                                    <th>Removed At</th>
                                    <th>Signature</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $stmtRemoved = $pdo->query("
                                        SELECT 
                                            ra.id AS archived_record_id,
                                            ra.user_id,
                                            ra.removal_type,
                                            ra.removed_at,
                                            ra.signature,
                                            ra.removed_by_admin_id,
                                            ra.removed_by_user_id,
                                            u.*,
                                            a.username AS admin_username,
                                            ru.first_name AS removed_by_first_name,
                                            ru.last_name AS removed_by_last_name,
                                            ru.role AS removed_by_role,
                                            ((SELECT COALESCE(SUM(mp.points), 0) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = u.id) + 
                                             (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = u.id)) as total_points
                                        FROM removed_accounts ra
                                        LEFT JOIN users u ON ra.user_id = u.id
                                        LEFT JOIN admins a ON ra.removed_by_admin_id = a.id
                                        LEFT JOIN users ru ON ra.removed_by_user_id = ru.id
                                        ORDER BY ra.removed_at DESC
                                        LIMIT 50
                                    ");
                                    $removedRows = $stmtRemoved->fetchAll(PDO::FETCH_ASSOC);
                                } catch (Exception $e) {
                                    $removedRows = [];
                                }
                                ?>
                                <?php if (empty($removedRows)): ?>
                                    <tr>
                                        <td colspan="7" style="text-align:center; padding:40px; color:#94a3b8;">
                                            <i class="fas fa-folder-open"
                                                style="font-size: 2rem; display: block; margin-bottom: 15px; opacity: 0.5;"></i>
                                            No archived account records found.
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($removedRows as $row): ?>
                                        <?php $userData = htmlspecialchars(json_encode($row)); ?>
                                        <tr onclick="openUserOptionsModal(this)" data-user='<?php echo $userData; ?>'
                                            data-points-link="member_points_summary.php?user_id=<?php echo (int) $row['user_id']; ?>"
                                            style="cursor: pointer; transition: background-color 0.2s;">
                                            <td
                                                onclick="event.stopPropagation(); const cb = this.querySelector('input'); if(cb) { cb.checked = !cb.checked; updateArchivedRowStyle(cb); }">
                                                <input type="checkbox" class="archived-checkbox"
                                                    value="<?php echo (int) $row['archived_record_id']; ?>"
                                                    data-userid="<?php echo (int) $row['user_id']; ?>"
                                                    onclick="event.stopPropagation(); updateArchivedRowStyle(this)"
                                                    style="cursor: pointer;">
                                            </td>
                                            <td style="font-weight:600; color:#1e293b;">
                                                <div class="user-main-info">
                                                    <?php echo htmlspecialchars(capitalizeWords(trim(($row['first_name'] ?? '') . ' ' . (!empty($row['middle_name']) ? $row['middle_name'] . ' ' : '') . ($row['last_name'] ?? ''))) ?: '---'); ?>
                                                </div>
                                            </td>
                                            <td><?php echo htmlspecialchars($row['nroi_id'] ?? '---'); ?></td>
                                            <td><?php echo (!empty($row['role']) && $row['role'] !== 'member') ? htmlspecialchars($row['role']) : 'R.O'; ?>
                                            </td>
                                            <td>
                                                <?php
                                                if (!empty($row['admin_username'])) {
                                                    echo htmlspecialchars($row['admin_username'] . ' (Admin)');
                                                } elseif (!empty($row['removed_by_first_name'])) {
                                                    $officerRole = !empty($row['removed_by_role']) ? $row['removed_by_role'] : 'Officer';
                                                    echo htmlspecialchars(capitalizeWords(trim($row['removed_by_first_name'] . ' ' . $row['removed_by_last_name'])) . ' (' . $officerRole . ')');
                                                } else {
                                                    echo '---';
                                                }
                                                ?>
                                            </td>
                                            <td style="font-size:0.85rem; color:#64748b;">
                                                <?php echo isset($row['removed_at']) ? date('M d, Y h:i A', strtotime($row['removed_at'])) : '---'; ?>
                                            </td>
                                            <td>
                                                <?php echo !empty($row['signature']) ? '<a href=\"../' . htmlspecialchars($row['signature']) . '\" target=\"_blank\">View</a>' : '---'; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($is_admin): ?>
                        <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:15px;">
                            <button class="btn-secondary" style="margin:0; width:auto; padding:10px 20px;"
                                onclick="restoreArchivedUser()">
                                Restore
                            </button>
                            <button class="btn-secondary"
                                style="margin:0; width:auto; padding:10px 20px; background:#fee2e2; color:#b91c1c; border-color:#fecaca;"
                                onclick="permanentlyRemoveArchivedUser()">
                                Removed Permanently
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

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

    <!-- Modals (Approval/Edit) -->
    <div id="approveModal" class="modal">
        <div class="modal-content" style="max-width: 420px; text-align: center;">
            <h3 style="margin-top:0; margin-bottom: 12px;">Approve Account</h3>
            <p style="color:#64748b; font-size: 0.95rem; margin-bottom: 8px;">Are you sure you want to approve this
                user?</p>
            <p id="approveUserName" style="font-weight: 700; color: #1e293b; font-size: 1.05rem; margin-bottom: 20px;">
            </p>
            <input type="hidden" id="approveUserId">
            <input type="hidden" id="approveRole">
            <input type="hidden" id="approveRank">
            <input type="hidden" id="approveArea">
            <!-- Officer-side hidden inputs -->
            <input type="hidden" id="approveRoleOfficer">
            <input type="hidden" id="approveRankOfficer">

            <div style="display:flex; justify-content: center; gap:10px; margin-top: 10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">Cancel</button>
                <button class="btn-primary" onclick="submitApproval()"
                    style="width:auto; margin:0; padding:12px 25px;">Approve</button>
            </div>
        </div>
    </div>

    <!-- User Options Modal -->
    <div id="userOptionsModal" class="modal">
        <div class="modal-content" style="max-width: 400px; text-align: center;">
            <h3 style="margin-top:0;">Account Actions</h3>
            <p style="color:#64748b; margin-bottom: 25px;">What would you like to do with this account?</p>

            <div style="display: flex; flex-direction: column; gap: 12px;">
                <button id="btnViewDetails" class="btn-primary" style="width: 100%; justify-content: center;">
                    <i class="fas fa-user-circle" style="margin-right: 8px;"></i> View Full Details
                </button>
                <button id="btnViewPoints" class="btn-secondary"
                    style="width: 100%; justify-content: center; background: #eff6ff; color: #1e40af; border-color: #bfdbfe;">
                    <i class="fas fa-id-card" style="margin-right: 8px;"></i> View Points Card
                </button>
            </div>

            <button onclick="closeModals()"
                style="background: none; border: none; color: #64748b; cursor: pointer; margin-top: 20px; font-size: 0.9rem;">
                Cancel
            </button>
        </div>
    </div>



    <!-- Camera capture modal (Take Photo opens camera, no file upload) -->
    <div id="cameraModal" class="modal" style="z-index: 10002;">
        <div class="modal-content" style="max-width: 520px;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 16px;">
                <h3 style="margin:0"><i class="fas fa-camera"></i> Take Photo</h3>
                <button type="button" onclick="closeCameraModal()"
                    style="background:none; border:none; color:#94a3b8; cursor:pointer; font-size:1.25rem;"><i
                        class="fas fa-times"></i></button>
            </div>
            <div id="cameraError"
                style="display:none; padding:12px; background:#fef2f2; color:#dc2626; border-radius:8px; margin-bottom:12px;">
            </div>
            <video id="cameraVideo" autoplay playsinline
                style="width:100%; max-height: 400px; background:#000; border-radius:8px;"></video>
            <div style="display:flex; gap:10px; justify-content:flex-end; margin-top:16px;">
                <button type="button" onclick="closeCameraModal()"
                    style="background:#e2e8f0; color:#475569; border:none; padding:10px 20px; border-radius:8px; cursor:pointer; font-weight:600;">Cancel</button>
                <button type="button" id="btnCapturePhoto" class="btn-primary" style="margin:0; padding:10px 24px;"><i
                        class="fas fa-circle"></i> Capture</button>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 style="margin-top:0; text-align: center; margin-bottom: 24px;">Update Account</h3>
            <input type="hidden" id="editUserId">

            <label class="form-label" style="text-align: center; display: block;">Rank</label>
            <select id="editRole" class="form-input" style="margin-bottom: 20px;">
                <?php foreach ($allowedRanks as $r): ?>
                    <option value="<?php echo $r; ?>"><?php echo $r; ?></option>
                <?php endforeach; ?>
            </select>

            <div id="editRankContainer">
                <label class="form-label" style="text-align: center; display: block;">Status</label>
                <select id="editRank" class="form-input" style="margin-bottom: 20px;">
                    <option value="Regular">Regular</option>
                    <option value="OJT">OJT</option>
                </select>
            </div>



            <div id="editAreaContainer">
                <label class="form-label" style="text-align: center; display: block;">Area</label>
                <select id="editArea" class="form-input" style="margin-bottom: 30px;">
                    <option value="">Select Area</option>
                    <?php
                    $stmtAreasEdit = $pdo->query("SELECT area_name FROM areas ORDER BY LENGTH(area_name) ASC, area_name ASC");
                    while ($ea = $stmtAreasEdit->fetch()) {
                        echo '<option value="' . htmlspecialchars($ea['area_name']) . '">' . htmlspecialchars($ea['area_name']) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div style="display:flex; justify-content: flex-end; gap:10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">Cancel</button>
                <button class="btn-primary" onclick="submitUpdate()"
                    style="width:auto; margin:0; padding:12px 25px;">Save Changes</button>
            </div>
        </div>
    </div>

    <!-- Details View Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content" style="max-width: 900px;">
            <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 25px; border-bottom: 1px solid #f1f5f9; padding-bottom: 15px;">
                <h3 style="margin:0"><i class="fas fa-user-shield" style="color:var(--primary-color);"></i> User
                    Profile
                    Audit</h3>
                <button onclick="closeModals()" style="background:none; border:none; color:#94a3b8; cursor:pointer;"><i
                        class="fas fa-times"></i></button>
            </div>

            <div id="userDetailsContent">
                <!-- Content injected via JS -->
            </div>

            <div
                style="display:flex; justify-content: flex-end; margin-top: 35px; border-top: 1px solid #f1f5f9; padding-top: 25px;">
                <button class="btn-primary" onclick="closeModals()"
                    style="width:auto; margin:0; padding:12px 35px; background: #f8fafc; color: #1e293b; border: 1px solid #e2e8f0;">Close
                    Overview</button>
            </div>
        </div>
    </div>




    <!-- Delete Confirmation Modal -->
    <div id="deleteConfirmModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 style="margin-top:0;">Delete Account</h3>
            <p style="color:#64748b; font-size:0.9rem; margin-bottom: 20px;">
                How would you like to handle this account?
            </p>

            <div
                style="background:#f9fafb; border-radius:12px; padding:12px 14px; margin-bottom:16px; font-size:0.85rem; color:#6b7280;">
                <strong>Temporary:</strong> Account will be deactivated and moved to <em>Archived</em>.<br>
                <strong>Permanent:</strong> Account will be permanently deleted from the system.
            </div>

            <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">
                    Cancel
                </button>
                <button class="btn-secondary"
                    style="margin:0; width:auto; padding:10px 18px; background:#eff6ff; color:#1d4ed8; border-color:#bfdbfe;"
                    onclick="confirmTemporaryRemoval()">
                    Temporary
                </button>
                <button class="btn-secondary"
                    style="margin:0; width:auto; padding:10px 18px; background:#fee2e2; color:#b91c1c; border-color:#fecaca;"
                    onclick="confirmPermanentRemoval()">
                    Permanent
                </button>
            </div>
        </div>
    </div>

    <!-- Reject Confirmation Modal -->
    <div id="rejectConfirmModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 style="margin-top:0;">Reject Pending Account</h3>
            <p style="color:#64748b; font-size:0.9rem; margin-bottom: 20px;">
                Are you sure you want to reject this pending account? It will be moved out of the pending list and
                marked as rejected.
            </p>

            <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">
                    Cancel
                </button>
                <button class="btn-secondary"
                    style="margin:0; width:auto; padding:10px 18px; background:#fee2e2; color:#b91c1c; border-color:#fecaca;"
                    onclick="confirmRejectUser()">
                    Reject
                </button>
            </div>
        </div>
    </div>

    <!-- Archived Actions Confirmation Modal -->
    <div id="archivedConfirmModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 id="archivedModalTitle" style="margin-top:0;">Confirm Action</h3>
            <p id="archivedModalText" style="color:#64748b; font-size:0.9rem; margin-bottom: 20px;">
                Are you sure you want to proceed with this action on the archived account?
            </p>

            <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">
                    Cancel
                </button>
                <button id="archivedPrimaryBtn" class="btn-secondary"
                    style="margin:0; width:auto; padding:10px 18px; background:#eff6ff; color:#1d4ed8; border-color:#bfdbfe;"
                    data-action="restore" onclick="confirmArchivedAction()">
                    Confirm
                </button>
            </div>
        </div>
    </div>

    <!-- Update Status Confirm Modal -->
    <div id="updateStatusModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 style="margin-top:0;">Confirm Status Change</h3>
            <p style="color:#64748b; font-size:0.9rem; margin-bottom: 24px;">Are you sure you want to change this
                account's status?</p>
            <div style="display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" onclick="closeModals()"
                    style="background: none; border: none; color: #64748b; cursor: pointer; font-weight: 600;">Cancel</button>
                <button type="button" id="updateStatusConfirmBtn" class="btn-primary"
                    style="margin: 0; padding: 10px 18px;">Confirm</button>
            </div>
        </div>
    </div>

    <!-- Archive Account Confirm Modal (General for Officers) -->
    <div id="archiveAccountModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 id="archiveModalTitle" style="margin-top:0;">Remove Account</h3>
            <p id="archiveModalText" style="color:#64748b; font-size:0.9rem; margin-bottom: 24px;">
                Are you sure you want to remove <strong id="archiveUserName">this user</strong>?
            </p>
            <div style="display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" onclick="closeModals()"
                    style="background: none; border: none; color: #64748b; cursor: pointer; font-weight: 600;">Cancel</button>
                <button type="button" id="archiveConfirmBtn" class="btn-secondary"
                    style="margin: 0; padding: 10px 18px; background: #fee2e2; color: #b91c1c; border-color: #fecaca;">Remove</button>
            </div>
        </div>
    </div>

    <!-- Message Modal (replaces alert) -->
    <div id="messageModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <p id="messageModalText" style="margin: 0 0 20px 0; color: #334155;"></p>
            <div style="display: flex; justify-content: flex-end;">
                <button type="button" onclick="closeModals()" class="btn-primary" style="margin: 0;">OK</button>
            </div>
        </div>
    </div>

    <!-- Create Account Confirmation Modal -->
    <div id="createConfirmModal" class="modal">
        <div class="modal-content" style="max-width: 420px;">
            <h3 style="margin-top:0;">Create New Account</h3>
            <p style="color:#64748b; font-size:0.9rem; margin-bottom: 20px;">
                Are you sure all entered details are correct and you want to create this user account?
            </p>

            <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:10px;">
                <button onclick="closeModals()"
                    style="background:none; border:none; color:#64748b; cursor:pointer; font-weight:600;">
                    Cancel
                </button>
                <button class="btn-secondary"
                    style="margin:0; width:auto; padding:10px 18px; background:#eff6ff; color:#1d4ed8; border-color:#bfdbfe;"
                    onclick="confirmCreateAccount()">
                    Create Account
                </button>
            </div>
        </div>
    </div>

    <script src="../assets/js/loader.js"></script>

    <script>
        function capitalizeWords(str) {
            if (!str) return '';
            return str.trim().toLowerCase().split(' ').map(word => {
                if (word.length === 0) return word;
                return word.charAt(0).toUpperCase() + word.slice(1);
            }).join(' ');
        }
        let selectedRowForOptions = null;

        function openUserOptionsModal(row) {
            selectedRowForOptions = row;
            // If user clicked row, open modal first
            document.getElementById('userOptionsModal').classList.add('active');

            // Set up click handlers
            const pointsLink = row.getAttribute('data-points-link');

            document.getElementById('btnViewDetails').onclick = function () {
                closeModals();
                viewUserDetails(selectedRowForOptions);
            };

            document.getElementById('btnViewPoints').onclick = function () {
                window.location.href = pointsLink;
            };
        }
        // Status display: approved=Active, deactivated/withdrawn=Inactive, rejected=Unrecognized, pending=Pending
        function statusDisplayLabel(status) {
            const s = (status || '').toString().toLowerCase().trim();
            const labels = { approved: 'Active', deactivated: 'Inactive', withdrawn: 'Inactive', rejected: 'Unrecognized', pending: 'Pending' };
            return labels[s] || status;
        }

        // Profile Dropdown
        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'));

        const isAdmin = <?php echo json_encode($is_admin); ?>;
        const officerArea = <?php echo json_encode($officerArea ?? ''); ?>;

        function openApproveModal(id, name, userArea, userRole, userRank) {
            document.getElementById('approveUserId').value = id;
            document.getElementById('approveUserName').textContent = name;

            // Store registration values in hidden inputs — no dropdowns shown
            const resolvedRole = (userRole && userRole !== 'member') ? userRole : 'R.O';
            const resolvedRank = userRank || 'Regular';
            const resolvedArea = userArea || '';

            if (isAdmin) {
                document.getElementById('approveRole').value = resolvedRole;
                document.getElementById('approveRank').value = resolvedRank;
                document.getElementById('approveArea').value = resolvedArea;
            } else {
                // Officer: only R.O/C.R.O allowed, area is fixed to officer's area
                const officerRole = (resolvedRole === 'R.O' || resolvedRole === 'C.R.O') ? resolvedRole : 'R.O';
                document.getElementById('approveRoleOfficer').value = officerRole;
                document.getElementById('approveRankOfficer').value = resolvedRank;
            }

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

        function openEditModal(id, role, area, rank) {
            document.getElementById('editUserId').value = id;
            document.getElementById('editRole').value = role || 'R.O';
            document.getElementById('editArea').value = area || '';
            document.getElementById('editRank').value = rank || 'Regular';

            handleRankVisibility('editRole', 'editRankContainer', 'editRank', 'editAreaContainer');
            document.getElementById('editModal').classList.add('active');
        }

        function handleRankVisibility(roleId, containerId, rankSelectId, areaContainerId = null) {
            const roleEl = typeof roleId === 'string' ? document.getElementById(roleId) : roleId;
            const container = document.getElementById(containerId);
            const rankSelect = document.getElementById(rankSelectId);
            const areaContainer = areaContainerId ? document.getElementById(areaContainerId) : null;
            if (!roleEl || !container || !rankSelect) return;

            const role = roleEl.value;
            if (role === 'AC' || role === 'AAC' || role === 'RM') {
                container.style.display = 'none';
                rankSelect.value = 'Regular';
            } else {
                container.style.display = 'block';
            }

            if (areaContainer) {
                if (role === 'RM') {
                    areaContainer.style.display = 'none';
                    const areaSelect = areaContainer.querySelector('select');
                    if (areaSelect) areaSelect.value = '';
                } else {
                    areaContainer.style.display = 'block';
                }
            }
        }

        // Add Listeners
        document.getElementById('editRole')?.addEventListener('change', () => handleRankVisibility('editRole', 'editRankContainer', 'editRank', 'editAreaContainer'));
        document.querySelector('select[name="role"]')?.addEventListener('change', function () {
            // For Create Modal: role select usually has name="role". Let's check.
            // In createModal it's <select name="role" class="form-input" required>
            // We need a way to find its status and area containers.
            // The createModal status select is <select name="rank" ...>
            // I'll add an ID to make it easier.
            handleRankVisibility(this, 'createRankContainer', 'createRankSelect', 'createAreaContainer');
        });

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

        function viewUserDetails(row) {
            const user = JSON.parse(row.getAttribute('data-user'));
            const content = document.getElementById('userDetailsContent');

            content.innerHTML = `
                <!-- Personal Information -->
                <div class="profile-section-title"><i class="fas fa-user-circle"></i> Personal Information</div>
                <div class="profile-grid">
                    <div class="detail-item" style="grid-column: span 2; border-right: 1px solid #eef2f6;">
                        <span class="detail-label">Full Name</span>
                        <div class="detail-value" style="font-size: 1.4rem; color: var(--primary-color);">${capitalizeWords((user.first_name || '') + ' ' + (user.middle_name ? user.middle_name + ' ' : '') + (user.last_name || ''))}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Birth Date / Age</span>
                        <div class="detail-value">${user.dob} <span style="color:#d1d5db; font-size:0.8rem; font-weight:400;">(${user.age} yrs)</span></div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Gender</span>
                        <div class="detail-value">${user.gender}</div>
                    </div>
                </div>

                <!-- Membership Details -->
                <div class="profile-section-title"><i class="fas fa-id-card"></i> Membership Details</div>
                <div class="profile-grid">
                    <div class="detail-item">
                        <span class="detail-label">NROI ID</span>
                        <div class="detail-value" style="background:#eff6ff; padding:8px 15px; border-radius:8px; display:inline-block; font-weight:700; color:#2563eb;">${user.nroi_id || '---'}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">PPSA ID</span>
                        <div class="detail-value" style="background:#f8fafc; padding:8px 15px; border-radius:8px; display:inline-block; font-weight:700;">${user.ppsa_id || '---'}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Rank</span>
                        <div class="detail-value">
                            <span class="role-badge role-${(user.role && user.role !== 'member') ? user.role : 'R.O'}" style="padding:8px 16px;">${((user.role && user.role !== 'member') ? user.role : 'R.O').toUpperCase()}</span>
                        </div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Account Status</span>
                        <div class="detail-value">
                            <span class="status-badge status-${user.status || 'pending'}" style="padding:8px 12px; border-radius:8px; font-weight:700;">
                                ${statusDisplayLabel(user.status)}
                            </span>
                        </div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Status (Rank)</span>
                        <div class="detail-value">
                            <span style="padding:8px 12px; background:#f1f5f9; color:#475569; border-radius:8px; font-weight:700;">
                                ${user.rank || 'Regular'}
                            </span>
                        </div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Match Assignment</span>
                        <div class="detail-value" style="font-weight: 600; color: #1e293b;">${user.match_assignment || 'None'}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Match Role</span>
                        <div class="detail-value" style="font-weight: 600; color: #1e293b;">${user.match_role || 'None'}</div>
                    </div>
                    <div class="detail-item" style="grid-column: span 2;">
                        <span class="detail-label">Total Points (2026)</span>
                        <div class="detail-value" style="font-weight: 700; color: #1e3a8a; font-size: 1.2rem;">${parseFloat(user.total_points_2026 || 0).toFixed(2)}</div>
                    </div>
                </div>

                <!-- Address Information -->
                <div class="profile-section-title"><i class="fas fa-map-location-dot"></i> Address Information</div>
                <div class="profile-grid full">
                    <div class="detail-item">
                        <span class="detail-label">Complete Registered Address</span>
                        <div class="detail-value" style="font-size: 1rem; line-height: 1.8; color: #475569; background: #fff; padding: 15px; border: 1px solid #f1f5f9; border-radius: 12px;">
                            <i class="fas fa-house-user" style="color:#cbd5e1; margin-right:10px;"></i>
                            ${user.street ? capitalizeWords(user.street) + ', ' : ''}${capitalizeWords(user.barangay)}, 
                            ${capitalizeWords(user.city_municipality)}, ${capitalizeWords(user.province)}, 
                            ${capitalizeWords(user.region)} ${user.zipcode}
                        </div>
                    </div>
                </div>

                <!-- Social media and Contacts -->
                <div class="profile-section-title"><i class="fas fa-share-nodes"></i> Social media and Contacts</div>
                <div class="profile-grid">
                    <div class="detail-item">
                        <span class="detail-label">Email Address</span>
                        <div class="detail-value" style="word-break: break-all; font-size: 0.95rem; color: #475569;">${user.email}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Mobile Number</span>
                        <div class="detail-value" style="letter-spacing:0.5px;">${user.phone_number}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Facebook Profile Link</span>
                        <div class="detail-value" style="word-break: break-all; font-size: 0.85rem; color: #3b82f6;">${capitalizeWords(user.facebook_link || '---')}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Viber / Telegram</span>
                        <div class="detail-value">${user.viber_number || user.telegram_number || '---'}</div>
                    </div>
                </div>

                <!-- Emergency Contact -->
                <div class="profile-section-title"><i class="fas fa-life-ring"></i> Emergency Contact</div>
                <div class="profile-grid">
                    <div class="detail-item" style="grid-column: span 2;">
                        <span class="detail-label">Primary Emergency Contact</span>
                        <div class="detail-value" style="color: #dc2626; font-weight:700;">${capitalizeWords(user.emergency_contact_name || '---')}</div>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">Emergency Phone</span>
                        <div class="detail-value" style="background:#fff1f2; color:#be123c; padding:8px 15px; border-radius:8px; display:inline-block;">${user.emergency_contact_number || '---'}</div>
                    </div>
                </div>
            `;

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

        function submitApproval() {
            const id = document.getElementById('approveUserId').value;
            let role, area, rank;

            if (isAdmin) {
                role = document.getElementById('approveRole').value || 'R.O';
                area = document.getElementById('approveArea').value;
                rank = document.getElementById('approveRank').value || 'Regular';
            } else {
                role = document.getElementById('approveRoleOfficer').value || 'R.O';
                rank = document.getElementById('approveRankOfficer').value || 'Regular';
                area = officerArea;
            }

            sendAction('approve', { id, role, area, rank });
        }

        function submitUpdate() {
            const action = isAdmin ? 'update_profile' : 'officer_update_member';
            sendAction(action, {
                id: document.getElementById('editUserId').value,
                role: document.getElementById('editRole').value,
                area: document.getElementById('editArea').value,
                rank: document.getElementById('editRank').value
            });
        }

        let pendingUpdateStatus = { id: null, status: null };
        function updateStatus(id, status) {
            pendingUpdateStatus = { id: id, status: status };
            document.getElementById('updateStatusModal').classList.add('active');
        }
        document.getElementById('updateStatusConfirmBtn').addEventListener('click', function () {
            if (pendingUpdateStatus.id !== null) {
                sendAction('update_status', { id: pendingUpdateStatus.id, status: pendingUpdateStatus.status });
                pendingUpdateStatus = { id: null, status: null };
                closeModals();
            }
        });

        // Reject pending account via modal
        let pendingRejectId = null;
        function rejectUser(id) {
            pendingRejectId = id;
            const modal = document.getElementById('rejectConfirmModal');
            if (modal) modal.classList.add('active');
        }
        function confirmRejectUser() {
            if (!pendingRejectId) return;
            sendAction('reject', { id: pendingRejectId });
            pendingRejectId = null;
            closeModals();
        }

        // Delete confirmation via modal (no more browser "localhost says" prompts)
        let pendingDeleteId = null;

        function deleteUser(id) {
            pendingDeleteId = id;
            const modal = document.getElementById('deleteConfirmModal');
            if (modal) modal.classList.add('active');
        }

        function confirmTemporaryRemoval() {
            if (!pendingDeleteId) return;
            sendAction('remove_temp', { id: pendingDeleteId });
            pendingDeleteId = null;
            closeModals();
        }

        function confirmPermanentRemoval() {
            if (!pendingDeleteId) return;
            sendAction('delete', { id: pendingDeleteId });
            pendingDeleteId = null;
            closeModals();
        }

        let pendingArchiveId = null;
        function confirmOfficerRemoval(id, name) {
            pendingArchiveId = id;
            const modal = document.getElementById('archiveAccountModal');
            if (modal) {
                document.getElementById('archiveUserName').textContent = name || 'this account';
                modal.classList.add('active');
            }
        }

        const archiveConfirmBtn = document.getElementById('archiveConfirmBtn');
        if (archiveConfirmBtn) {
            archiveConfirmBtn.addEventListener('click', function () {
                if (pendingArchiveId !== null) {
                    sendAction('remove_temp', { id: pendingArchiveId });
                    pendingArchiveId = null;
                    closeModals();
                }
            });
        }

        // Archived selection helpers
        function getSelectedArchived() {
            const checked = document.querySelectorAll('.archived-checkbox:checked');
            let removedIds = [];
            let userIds = [];
            checked.forEach(cb => {
                removedIds.push(cb.value);
                userIds.push(cb.getAttribute('data-userid'));
            });
            return { removedIds, userIds };
        }

        function toggleAllArchived(source) {
            const checkboxes = document.querySelectorAll('.archived-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = source.checked;
                updateArchivedRowStyle(cb);
            });
        }

        function toggleArchivedCheckbox(row) {
            const checkbox = row.querySelector('.archived-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateArchivedRowStyle(checkbox);
            }
        }

        function updateArchivedRowStyle(checkbox) {
            const row = checkbox.closest('tr');
            if (row) {
                row.style.backgroundColor = checkbox.checked ? '#eff6ff' : '';
            }
        }

        function showMessageModal(msg) {
            document.getElementById('messageModalText').textContent = msg;
            document.getElementById('messageModal').classList.add('active');
        }
        function restoreArchivedUser() {
            const selected = getSelectedArchived();
            if (selected.removedIds.length === 0) {
                showMessageModal('Please select at least one archived record to restore.');
                return;
            }
            const modal = document.getElementById('archivedConfirmModal');
            if (!modal) return;
            document.getElementById('archivedModalTitle').textContent = 'Restore Archived Account(s)';
            document.getElementById('archivedModalText').textContent =
                `This will restore the ${selected.removedIds.length} selected archived account(s) back to active status.`;
            document.getElementById('archivedPrimaryBtn').textContent = 'Restore';
            document.getElementById('archivedPrimaryBtn').setAttribute('data-action', 'restore');
            modal.classList.add('active');
        }

        function permanentlyRemoveArchivedUser() {
            const selected = getSelectedArchived();
            if (selected.removedIds.length === 0) {
                showMessageModal('Please select at least one archived record to remove.');
                return;
            }
            const modal = document.getElementById('archivedConfirmModal');
            if (!modal) return;
            document.getElementById('archivedModalTitle').textContent = 'Remove Archived Account(s) Permanently';
            document.getElementById('archivedModalText').textContent =
                `This will permanently remove the ${selected.removedIds.length} selected archived account(s). This action cannot be undone.`;
            document.getElementById('archivedPrimaryBtn').textContent = 'Removed Permanently';
            document.getElementById('archivedPrimaryBtn').setAttribute('data-action', 'permanent');
            modal.classList.add('active');
        }

        function confirmArchivedAction() {
            const selected = getSelectedArchived();
            if (selected.removedIds.length === 0) return;

            const btn = document.getElementById('archivedPrimaryBtn');
            if (!btn) return;
            const action = btn.getAttribute('data-action');

            if (action === 'restore') {
                sendAction('archive_restore', { removed_id: selected.removedIds.join(','), user_id: selected.userIds.join(',') });
            } else if (action === 'permanent') {
                sendAction('archive_permanent', { removed_id: selected.removedIds.join(','), user_id: selected.userIds.join(',') });
            }

            closeModals();
        }



        function sendAction(action, data) {
            const fd = new FormData();
            fd.append('action', action);
            for (let k in data) fd.append(k, data[k]);
            fetch('admin_user_actions.php', { method: 'POST', body: fd })
                .then(r => r.json()).then(res => res.success ? location.reload() : showMessageModal(res.message))
                .catch(() => showMessageModal('Action failed.'));
        }
        // Real-time Search as you type
        const accountSearchInput = document.getElementById('accountSearchInput');
        const accountsTableBody = document.getElementById('accountsTableBody');
        if (accountSearchInput && accountsTableBody) {
            const initialQuery = accountSearchInput.value.trim();
            function performLocalSearch(isAutoReset = false) {
                const query = accountSearchInput.value.toLowerCase().trim();
                const terms = query.split(/\s+/).filter(t => t.length > 0);
                const rows = accountsTableBody.getElementsByTagName('tr');
                const noResultsPlaceholder = document.getElementById('jsNoResultsRow');

                // Auto-reset: If user clears a submitted search, go back to full list
                if (query === '' && initialQuery !== '' && isAutoReset !== true) {
                    window.location.href = window.location.pathname + '?tab=<?php echo $tabFilter; ?>&sort=<?php echo $sort; ?>&rank_filter=<?php echo urlencode($rankFilter); ?>';
                    return;
                }

                let visibleCount = 0;
                for (let i = 0; i < rows.length; i++) {
                    const row = rows[i];
                    if (!row || row.classList.contains('empty-row') || row.classList.contains('no-results-row') || row.id === 'jsNoResultsRow') continue;

                    const content = row.textContent.toLowerCase();
                    const matches = terms.length === 0 || terms.every(t => content.includes(t));
                    row.style.display = matches ? '' : 'none';
                    if (matches) visibleCount++;
                }

                if (noResultsPlaceholder) {
                    noResultsPlaceholder.style.display = (visibleCount === 0 && terms.length > 0) ? '' : 'none';
                }
            }

            // Bind to all relevant events
            ['input', 'keyup', 'change', 'paste', 'search'].forEach(evt => {
                accountSearchInput.addEventListener(evt, () => performLocalSearch(false));
            });

            // Initial run on load
            setTimeout(() => performLocalSearch(true), 100);
        }
    </script>

    <!-- Create Account Modal -->
    <div id="createAccountModal" class="modal">
        <div class="modal-content" style="max-width: 480px;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 24px;">
                <h3 style="margin:0;"><i class="fas fa-user-plus" style="margin-right: 10px; color: #10b981;"></i>Create
                    Account</h3>
                <button type="button" onclick="closeModals()"
                    style="background:none; border:none; color:#94a3b8; cursor:pointer; font-size:1.25rem;"><i
                        class="fas fa-times"></i></button>
            </div>

            <form id="createAccountForm">
                <div class="form-group" style="margin-bottom: 15px;">
                    <label class="form-label">Rank</label>
                    <select name="rank" class="form-input" required>
                        <option value="PPSA">PPSA</option>
                        <option value="NROI">NROI</option>
                    </select>
                </div>

                <div class="form-group" style="margin-bottom: 25px;">
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email" class="form-input" placeholder="Enter user's email" required>
                    <p style="font-size: 0.75rem; color: #64748b; margin-top: 8px;">
                        <i class="fas fa-info-circle"></i> A unique username and temporary password will be
                        automatically generated and sent to the user.
                    </p>
                </div>

                <div style="display: flex; justify-content: flex-end; gap: 12px;">
                    <button type="button" onclick="closeModals()" class="btn-secondary"
                        style="margin:0; width:auto; padding: 10px 20px;">Cancel</button>
                    <button type="submit" class="btn-primary"
                        style="margin:0; width:auto; padding: 10px 25px; background: #10b981; border-color: #10b981;">Create
                        Account</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Account Success Modal -->
    <div id="accountSuccessModal" class="modal">
        <div class="modal-content"
            style="max-width: 450px; background: #1a1a1a; color: #ffffff; border-radius: 15px; border: 1px solid rgba(255,255,255,0.1); box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); padding: 30px;">
            <div style="margin-bottom: 25px;">
                <h3 style="margin: 0; color: #ffffff; font-size: 1.25rem; font-weight: 600;">Account created
                    successfully!</h3>
            </div>

            <div
                style="background: rgba(255,255,255,0.05); border-radius: 12px; padding: 20px; margin-bottom: 20px; border: 1px solid rgba(255,255,255,0.05);">
                <div style="display: flex; margin-bottom: 12px; gap: 10px;">
                    <span style="color: #94a3b8; font-size: 0.95rem; width: 100px;">Username:</span>
                    <span id="successUsername"
                        style="color: #ffffff; font-weight: 600; font-family: 'Inter', sans-serif; font-size: 0.95rem;"></span>
                </div>
                <div style="display: flex; gap: 10px;">
                    <span style="color: #94a3b8; font-size: 0.95rem; width: 100px;">Password:</span>
                    <span id="successPassword"
                        style="color: #ffffff; font-weight: 600; font-family: 'Inter', sans-serif; font-size: 0.95rem;"></span>
                </div>
            </div>

            <p id="successEmailInfo" style="color: #ffffff; font-size: 0.95rem; margin-bottom: 30px; line-height: 1.5;">
            </p>

            <div style="display: flex; justify-content: flex-end;">
                <button onclick="location.reload()"
                    style="padding: 12px 35px; background: #ffbead; color: #000; border: none; border-radius: 50px; font-weight: 700; cursor: pointer; transition: all 0.2s ease; font-size: 0.9rem;">
                    OK
                </button>
            </div>
        </div>
    </div>

    <script>
        // Create Account Functions
        function openCreateAccountModal() {
            document.getElementById('createAccountModal').classList.add('active');
        }

        // Form Submission for Create Account
        document.getElementById('createAccountForm')?.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn = this.querySelector('button[type="submit"]');
            const originalText = btn.textContent;
            btn.textContent = 'Creating...';
            btn.disabled = true;

            const formData = new FormData(this);
            fetch('create_account_admin.php', {
                method: 'POST',
                body: formData
            })
                .then(r => r.json())
                .then(data => {
                    btn.textContent = originalText;
                    btn.disabled = false;

                    if (data.success) {
                        // Show success modal instead of alert
                        document.getElementById('successUsername').textContent = data.username;
                        document.getElementById('successPassword').textContent = data.password;
                        document.getElementById('successEmailInfo').textContent = `An activation link has been sent to ${formData.get('email')}`;
                        document.getElementById('accountSuccessModal').classList.add('active');
                        // No reload here, user clicks OK
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .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>