<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

$error = '';
$success = '';

// 1. BALANCE ADJUSTMENT ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['adjust_balance'])) {
    $userId = intval($_POST['user_id']);
    $adjustType = $_POST['adjust_type']; // credit or debit
    $amount = floatval($_POST['adjust_amount']);
    $description = trim($_POST['adjust_description'] ?? '');
    $notify = isset($_POST['notify_user']);
    
    if ($amount <= 0) {
        $error = 'Please enter a valid amount.';
    } else {
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $targetUser = $stmt->get_result()->fetch_assoc();
        
        if ($targetUser) {
            $newBalance = $adjustType === 'credit' 
                ? $targetUser['available_balance'] + $amount 
                : $targetUser['available_balance'] - $amount;
            
            // Syncing both available and total account balance
            $stmt = $db->prepare("UPDATE users SET available_balance = ?, account_balance = ? WHERE id = ?");
            $stmt->bind_param('ddi', $newBalance, $newBalance, $userId);
            $stmt->execute();
            
            // Create corresponding platform transaction record
            $ref = generateReference();
            $txType = $adjustType === 'credit' ? 'credit' : 'debit';
            $txData = [
                'user_id' => $userId,
                'transaction_type' => $txType,
                'amount' => $amount,
                'currency' => $targetUser['currency'] ?? 'USD',
                'description' => $description ?: 'Admin balance adjustment',
                'reference_number' => $ref,
                'beneficiary_name' => null,
                'beneficiary_account' => null,
                'beneficiary_bank' => null,
                'beneficiary_bank_code' => null,
                'beneficiary_swift' => null,
                'beneficiary_iban' => null,
                'beneficiary_routing' => null,
                'beneficiary_country' => null,
                'transfer_type' => 'local',
                'transfer_mode' => 'wire',
                'require_imf' => 0,
                'require_cot' => 0,
                'require_otp' => 0,
                'ip_address' => $_SERVER['REMOTE_ADDR'],
            ];
            createTransaction($txData);
            
            createNotification($userId, 'Balance ' . ucfirst($adjustType), 
                'Your account has been ' . $adjustType . 'ed with ' . formatCurrency($amount) . '. ' . ($description ?: ''),
                'success'
            );
            
            if ($notify) {
                $subject = 'Account Balance Update';
                $body = "<h2>Balance Update</h2><p>Your account has been {$adjustType}ed with " . formatCurrency($amount) . "</p><p>Description: " . e($description) . "</p>";
                @sendMail($targetUser['email'], $subject, $body);
            }
            
            $success = 'Balance adjusted successfully!';
        }
    }
}

// 2. // 2. UPDATE SECURITY GATES ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_gates'])) {
    $userId = intval($_POST['user_id']);
    
    $enableIMF = isset($_POST['enable_imf']) ? 1 : 0;
    $imfCode = trim($_POST['imf_code'] ?? '');
    $enableCOT = isset($_POST['enable_cot']) ? 1 : 0;
    $cotCode = trim($_POST['cot_code'] ?? '');
    $enableATC = isset($_POST['enable_atc']) ? 1 : 0;
    $atcCode = trim($_POST['atc_code'] ?? '');
    $enableTXC = isset($_POST['enable_txc']) ? 1 : 0;
    $txcCode = trim($_POST['txc_code'] ?? '');
    $enableOTP = isset($_POST['enable_otp']) ? 1 : 0;
    $enableOTPlogin = isset($_POST['enable_otp_login']) ? 1 : 0;
    $enablePopup = isset($_POST['enable_popup']) ? 1 : 0;
    $popupMessage = trim($_POST['popup_message'] ?? '');
    $enable2FA = isset($_POST['enable_2fa']) ? 1 : 0;
    
    // Matched strictly with columns in your users table definition
    $stmt = $db->prepare("UPDATE users SET 
        enable_imf = ?, imf_code = ?, enable_cot = ?, cot_code = ?,
        enable_anti_terrorist = ?, anti_terrorist_code = ?,
        enable_tax_clearance = ?, tax_clearance_code = ?,
        enable_otp = ?, enable_otp_login = ?,
        show_popup = ?, popup_message = ?,
        enable_2fa = ?
        WHERE id = ?");
        
    // FIXED: Changed from 'isisissississii' (15) to 'isisississisii' (14) to match the 14 variables perfectly
    $stmt->bind_param('isisississisii', 
        $enableIMF, $imfCode, $enableCOT, $cotCode,
        $enableATC, $atcCode, $enableTXC, $txcCode,
        $enableOTP, $enableOTPlogin, $enablePopup, $popupMessage,
        $enable2FA, $userId
    );
    
    if ($stmt->execute()) {
        $success = 'Security gates updated successfully!';
    } else {
        $error = 'Failed to update security gates.';
    }
}

// 3. SEND EMAIL ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $userId = intval($_POST['user_id']);
    $subject = trim($_POST['email_subject'] ?? '');
    $body = trim($_POST['email_body'] ?? '');
    
    $stmt = $db->prepare("SELECT email, first_name FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $targetUser = $stmt->get_result()->fetch_assoc();
    
    if ($targetUser && sendMail($targetUser['email'], $subject, $body)) {
        $success = 'Email sent successfully to ' . e($targetUser['email']);
    } else {
        $error = 'Failed to send email.';
    }
}

// 4. UPDATE STATUS AND KYC ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $userId = intval($_POST['user_id']);
    $newStatus = $_POST['account_status'];
    $kycStatus = $_POST['kyc_status'];
    $accType = $_POST['account_type'];
    
    $stmt = $db->prepare("UPDATE users SET account_status = ?, kyc_status = ?, account_type = ? WHERE id = ?");
    $stmt->bind_param('sssi', $newStatus, $kycStatus, $accType, $userId);
    if ($stmt->execute()) {
        $success = 'Account status configurations updated successfully!';
    } else {
        $error = 'Failed to update account status properties.';
    }
}

// Pagination parameters
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 15;
$offset = ($page - 1) * $limit;

// Filter/Search engine
$search = trim($_GET['search'] ?? '');
$where = '';
$params = [];
$types = '';

if ($search) {
    $where = "WHERE (first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR account_number LIKE ?)";
    $searchParam = "%$search%";
    $params = [$searchParam, $searchParam, $searchParam, $searchParam];
    $types = 'ssss';
}

// Pull active set
$query = "SELECT * FROM users $where ORDER BY created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types .= 'ii';

$stmt = $db->prepare($query);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$usersList = [];
while ($row = $result->fetch_assoc()) {
    $usersList[] = $row;
}

// Pagination counts
$countQuery = "SELECT COUNT(*) as total FROM users $where";
if ($search) {
    $countStmt = $db->prepare($countQuery);
    $sp = "%$search%";
    $countStmt->bind_param('ssss', $sp, $sp, $sp, $sp);
    $countStmt->execute();
    $totalRecords = $countStmt->get_result()->fetch_assoc()['total'];
} else {
    $totalRecords = 0;
    $countRes = $db->query("SELECT COUNT(*) as total FROM users");
    if ($countRes) {
         $totalRecords = $countRes->fetch_assoc()['total'];
    }
}
$totalPages = ceil($totalRecords / $limit);

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - <?php echo defined('SITE_NAME') ? SITE_NAME : 'Admin Platform'; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        /* Standalone Explicit Structural Overrides for Custom Modals */
        .custom-modal-overlay {
            display: none !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
            background: rgba(0, 0, 0, 0.6) !important;
            z-index: 99999 !important;
            align-items: center !important;
            justify-content: center !important;
        }
        .custom-modal-overlay.active {
            display: flex !important;
        }
        .custom-modal-box {
            background: #ffffff !important;
            padding: 24px !important;
            border-radius: 8px !important;
            max-width: 550px !important;
            width: 90% !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
            animation: modalFadeIn 0.25s ease;
            color: #333333 !important;
        }
        .custom-modal-box.modal-lg {
            max-width: 750px !important;
        }
        .custom-form-group {
            margin-bottom: 14px !important;
            text-align: left !important;
        }
        .custom-form-group label {
            display: block !important;
            font-size: 13px !important;
            font-weight: 600 !important;
            color: #4e73df !important;
            margin-bottom: 4px !important;
        }
        .custom-form-control {
            width: 100% !important;
            padding: 9px !important;
            border: 1px solid #d1d3e2 !important;
            border-radius: 4px !important;
            font-size: 13px !important;
            box-sizing: border-box !important;
            background: #ffffff !important;
            color: #333333 !important;
        }
        @keyframes modalFadeIn {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger fade-in"><span>⚠</span> <?php echo e($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success fade-in"><span>✓</span> <?php echo e($success); ?></div>
            <?php endif; ?>
            
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-body">
                    <form method="GET" action="" style="display: flex; gap: 12px;">
                        <div class="search-box" style="flex: 1;">
                            <input type="text" name="search" class="form-control" placeholder="Search by name, email, or account number..." value="<?php echo e($search); ?>">
                        </div>
                        <button type="submit" class="btn btn-primary">Search</button>
                        <?php if ($search): ?>
                            <a href="users.php" class="btn btn-secondary">Clear</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
            
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Account</th>
                                    <th>Type</th>
                                    <th>Balance</th>
                                    <th>KYC</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($usersList) > 0): ?>
                                    <?php foreach ($usersList as $u): ?>
                                        <tr>
                                            <td>
                                                <div style="display: flex; align-items: center; gap: 10px;">
                                                    <div style="width: 36px; height: 36px; border-radius: 50%; background: #4e73df; color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px;">
                                                        <?php echo strtoupper(substr($u['first_name'] ?? 'U', 0, 1) . substr($u['last_name'] ?? 'N', 0, 1)); ?>
                                                    </div>
                                                    <div>
                                                        <div style="font-weight: 600;"><?php echo e(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')); ?></div>
                                                        <div style="font-size: 12px; color: #858796;"><?php echo e($u['email'] ?? ''); ?></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td><code style="font-size: 11px;"><?php echo e($u['account_number'] ?? 'N/A'); ?></code></td>
                                            <td><span style="text-transform: capitalize;"><?php echo e($u['account_type'] ?? 'savings'); ?></span></td>
                                            <td style="font-weight: 700;"><?php echo function_exists('formatCurrency') ? formatCurrency($u['available_balance']) : ($u['currency'] ?? '$') . number_format($u['available_balance'], 2); ?></td>
                                            <td><span class="kyc-status <?php echo e($u['kyc_status'] ?? 'pending'); ?>" style="padding: 3px 8px; font-size:11px; border-radius:3px; font-weight:600;"><?php echo ucfirst(e($u['kyc_status'] ?? 'pending')); ?></span></td>
                                            <td>
                                                <span class="status-badge <?php echo ($u['account_status'] ?? 'active') === 'active' ? 'success' : (($u['account_status'] ?? '') === 'suspended' ? 'danger' : 'warning'); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($u['account_status'] ?? 'active')); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div style="display: flex; gap: 4px;">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openModal('modal-balance-<?php echo $u['id']; ?>')">Balance</button>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openModal('modal-gates-<?php echo $u['id']; ?>')">Gates</button>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openModal('modal-status-<?php echo $u['id']; ?>')">Status</button>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openModal('modal-email-<?php echo $u['id']; ?>')">Email</button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="text-center" style="padding: 40px; color: #858796;">No accounts or users match criteria</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if ($totalPages > 1): ?>
                    <div style="padding: 16px 24px;">
                        <div class="pagination">
                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <?php if ($i === $page): ?>
                                    <span class="active-page" style="padding: 5px 10px; font-weight:bold; background:#e3e6f0; border-radius:3px; margin: 0 2px;"><?php echo $i; ?></span>
                                <?php else: ?>
                                    <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" style="padding: 5px 10px; margin: 0 2px; text-decoration:none; color:#4e73df;"><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php foreach ($usersList as $u): ?>
    
    <div class="custom-modal-overlay" id="modal-balance-<?php echo $u['id']; ?>">
        <div class="custom-modal-box">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e3e6f0; padding-bottom:12px; margin-bottom:16px;">
                <span style="font-weight:700; font-size:16px;">Adjust Funds - <?php echo e(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')); ?></span>
                <button type="button" style="background:none; border:none; font-size:18px; cursor:pointer;" onclick="closeModal('modal-balance-<?php echo $u['id']; ?>')">✕</button>
            </div>
            <div>
                <div style="background: #f8f9fc; border-radius: 4px; padding: 12px; margin-bottom: 16px;">
                    <div style="display: flex; justify-content: space-between; font-size: 14px;">
                        <span style="color: #858796;">Available Balance:</span>
                        <span style="font-weight: 700; color:#1cc88a;"><?php echo function_exists('formatCurrency') ? formatCurrency($u['available_balance']) : ($u['currency'] ?? '$') . number_format($u['available_balance'], 2); ?></span>
                    </div>
                </div>
                <form method="POST" action="">
                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                    <input type="hidden" name="adjust_balance" value="1">
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 14px;">
                        <div class="custom-form-group">
                            <label>Type *</label>
                            <select name="adjust_type" class="custom-form-control" required>
                                <option value="credit">Credit (Deposit Funds)</option>
                                <option value="debit">Debit (Deduct Funds)</option>
                            </select>
                        </div>
                        <div class="custom-form-group">
                            <label>Amount *</label>
                            <input type="number" name="adjust_amount" class="custom-form-control" step="0.01" min="0.01" required>
                        </div>
                    </div>
                    <div class="custom-form-group">
                        <label>Transaction Narration / Description</label>
                        <textarea name="adjust_description" class="custom-form-control" rows="2" placeholder="e.g. Wire Transfer Deposit Credit"></textarea>
                    </div>
                    <label style="display: flex; align-items: center; gap: 8px; font-size: 12px; cursor: pointer; color: #333;">
                        <input type="checkbox" name="notify_user" checked style="accent-color: #4e73df;"> Trigger Automated Email Alert Notification
                    </label>
                    
                    <div style="padding-top:16px; margin-top:16px; border-top:1px solid #e3e6f0; text-align:right;">
                        <button type="button" class="btn btn-secondary" style="padding:8px 16px; margin-right:5px;" onclick="closeModal('modal-balance-<?php echo $u['id']; ?>')">Cancel</button>
                        <button type="submit" class="btn btn-primary" style="padding:8px 16px;">Update Ledger</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="custom-modal-overlay" id="modal-gates-<?php echo $u['id']; ?>">
        <div class="custom-modal-box modal-lg" style="max-height:85vh; overflow-y:auto;">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e3e6f0; padding-bottom:12px; margin-bottom:16px;">
                <span style="font-weight:700; font-size:16px;">Security Gates Override - <?php echo e(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')); ?></span>
                <button type="button" style="background:none; border:none; font-size:18px; cursor:pointer;" onclick="closeModal('modal-gates-<?php echo $u['id']; ?>')">✕</button>
            </div>
            <div>
                <form method="POST" action="">
                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                    <input type="hidden" name="update_gates" value="1">
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div style="border: 1px solid #e3e6f0; padding:12px; border-radius:6px;">
                            <h4 style="margin:0 0 8px 0; color:#efb810; font-size:13px;">🌍 IMF Code Restrictions</h4>
                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px; font-size:12px; cursor: pointer; color:#333;">
                                <input type="checkbox" name="enable_imf" <?php echo ($u['enable_imf'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Lock Transfer behind IMF Code
                            </label>
                            <div class="custom-form-group">
                                <input type="text" name="imf_code" class="custom-form-control" style="padding:6px;" value="<?php echo e($u['imf_code'] ?? ''); ?>" placeholder="Set IMF validation code">
                            </div>
                        </div>
                        
                        <div style="border: 1px solid #e3e6f0; padding:12px; border-radius:6px;">
                            <h4 style="margin:0 0 8px 0; color:#36b9cc; font-size:13px;">💱 COT Code Restrictions</h4>
                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px; font-size:12px; cursor: pointer; color:#333;">
                                <input type="checkbox" name="enable_cot" <?php echo ($u['enable_cot'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Lock Transfer behind COT Code
                            </label>
                            <div class="custom-form-group">
                                <input type="text" name="cot_code" class="custom-form-control" style="padding:6px;" value="<?php echo e($u['cot_code'] ?? ''); ?>" placeholder="Set COT validation code">
                            </div>
                        </div>
                        
                        <div style="border: 1px solid #e3e6f0; padding:12px; border-radius:6px;">
                            <h4 style="margin:0 0 8px 0; color:#e74a3b; font-size:13px;">🛡️ Anti-Terrorist Clearance Code</h4>
                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px; font-size:12px; cursor: pointer; color:#333;">
                                <input type="checkbox" name="enable_atc" <?php echo ($u['enable_anti_terrorist'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Require Anti-Terrorist Pass
                            </label>
                            <div class="custom-form-group">
                                <input type="text" name="atc_code" class="custom-form-control" style="padding:6px;" value="<?php echo e($u['anti_terrorist_code'] ?? ''); ?>" placeholder="Set ATC validation code">
                            </div>
                        </div>
                        
                        <div style="border: 1px solid #e3e6f0; padding:12px; border-radius:6px;">
                            <h4 style="margin:0 0 8px 0; color:#1cc88a; font-size:13px;">📋 Tax Clearance Code</h4>
                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px; font-size:12px; cursor: pointer; color:#333;">
                                <input type="checkbox" name="enable_txc" <?php echo ($u['enable_tax_clearance'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Require Tax Pin Authorization
                            </label>
                            <div class="custom-form-group">
                                <input type="text" name="txc_code" class="custom-form-control" style="padding:6px;" value="<?php echo e($u['tax_clearance_code'] ?? ''); ?>" placeholder="Set Tax validation code">
                            </div>
                        </div>
                    </div>
                    
                    <div style="border-top: 1px solid #e3e6f0; margin-top: 16px; padding-top: 16px;">
                        <h4 style="margin:0 0 12px 0; font-size:14px; color:#4e73df;">Additional Security Vectors</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size:12px; color:#333;">
                            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                                <input type="checkbox" name="enable_otp" <?php echo ($u['enable_otp'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Transaction OTP Requirement
                            </label>
                            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                                <input type="checkbox" name="enable_otp_login" <?php echo ($u['enable_otp_login'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Login Access 2FA OTP Prompt
                            </label>
                            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                                <input type="checkbox" name="enable_2fa" <?php echo ($u['enable_2fa'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Core Authenticator 2FA 
                            </label>
                            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                                <input type="checkbox" name="enable_popup" <?php echo ($u['show_popup'] ?? 0) ? 'checked' : ''; ?> style="accent-color: #4e73df;"> Active Admin Login Popup Message
                            </label>
                        </div>
                        <div class="custom-form-group" style="margin-top: 12px;">
                            <label style="font-size:11px; font-weight:600; color:#858796;">Target User Dashboard Intercept Interstitial Popup Text Message Notice</label>
                            <textarea name="popup_message" class="custom-form-control" rows="2" placeholder="Force alert window messaging on login context..."><?php echo e($u['popup_message'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    
                    <div style="padding-top:16px; margin-top:16px; border-top:1px solid #e3e6f0; text-align:right;">
                        <button type="button" class="btn btn-secondary" style="padding:8px 16px; margin-right:5px;" onclick="closeModal('modal-gates-<?php echo $u['id']; ?>')">Cancel</button>
                        <button type="submit" class="btn btn-primary" style="padding:8px 16px;">Commit Rule Profiles</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="custom-modal-overlay" id="modal-status-<?php echo $u['id']; ?>">
        <div class="custom-modal-box">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e3e6f0; padding-bottom:12px; margin-bottom:16px;">
                <span style="font-weight:700; font-size:16px;">Configure Status Parameters</span>
                <button type="button" style="background:none; border:none; font-size:18px; cursor:pointer;" onclick="closeModal('modal-status-<?php echo $u['id']; ?>')">✕</button>
            </div>
            <div>
                <form method="POST" action="">
                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                    <input type="hidden" name="update_status" value="1">
                    
                    <div class="custom-form-group">
                        <label>Account Operation Status</label>
                        <select name="account_status" class="custom-form-control">
                            <option value="active" <?php echo ($u['account_status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active / Operational</option>
                            <option value="suspended" <?php echo ($u['account_status'] ?? '') === 'suspended' ? 'selected' : ''; ?>>Suspended / Hold</option>
                            <option value="dormant" <?php echo ($u['account_status'] ?? '') === 'dormant' ? 'selected' : ''; ?>>Dormant / Restricted</option>
                        </select>
                    </div>
                    
                    <div class="custom-form-group">
                        <label>KYC Compliance Certification</label>
                        <select name="kyc_status" class="custom-form-control">
                            <option value="approved" <?php echo ($u['kyc_status'] ?? '') === 'approved' ? 'selected' : ''; ?>>Approved / Passed Verification</option>
                            <option value="pending" <?php echo ($u['kyc_status'] ?? '') === 'pending' ? 'selected' : ''; ?>>Pending Manual Verification Document Audit</option>
                            <option value="rejected" <?php echo ($u['kyc_status'] ?? '') === 'rejected' ? 'selected' : ''; ?>>Rejected Compliance Profile</option>
                        </select>
                    </div>

                    <div class="custom-form-group">
                        <label>Product Tier Account Type Selection</label>
                        <select name="account_type" class="custom-form-control">
                            <option value="savings" <?php echo ($u['account_type'] ?? '') === 'savings' ? 'selected' : ''; ?>>Savings Tier Account Ledger</option>
                            <option value="current" <?php echo ($u['account_type'] ?? '') === 'current' ? 'selected' : ''; ?>>Checking / Current Tier Ledger</option>
                            <option value="checking" <?php echo ($u['account_type'] ?? '') === 'checking' ? 'selected' : ''; ?>>Standard Checking Product Group</option>
                        </select>
                    </div>
                    
                    <div style="padding-top:16px; border-top:1px solid #e3e6f0; text-align:right;">
                        <button type="button" class="btn btn-secondary" style="padding:8px 16px; margin-right:5px;" onclick="closeModal('modal-status-<?php echo $u['id']; ?>')">Cancel</button>
                        <button type="submit" class="btn btn-primary" style="padding:8px 16px; background:#1cc88a !important; border-color:#1cc88a !important;">Update Status Parameters</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="custom-modal-overlay" id="modal-email-<?php echo $u['id']; ?>">
        <div class="custom-modal-box">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e3e6f0; padding-bottom:12px; margin-bottom:16px;">
                <span style="font-weight:700; font-size:16px;">Direct Electronic Mail Dispatch - <?php echo e($u['first_name'] ?? ''); ?></span>
                <button type="button" style="background:none; border:none; font-size:18px; cursor:pointer;" onclick="closeModal('modal-email-<?php echo $u['id']; ?>')">✕</button>
            </div>
            <div>
                <form method="POST" action="">
                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                    <input type="hidden" name="send_email" value="1">
                    
                    <div class="custom-form-group">
                        <label>Mail Header Subject Line *</label>
                        <input type="text" name="email_subject" class="custom-form-control" required placeholder="e.g. Identity Authentication Verification Complete Notice">
                    </div>
                    <div class="custom-form-group">
                        <label>Message Body Document Context (HTML Standard Layouts Allowed) *</label>
                        <textarea name="email_body" class="custom-form-control" rows="6" required placeholder="Write custom mail information body context here..."></textarea>
                    </div>
                    
                    <div style="padding-top:16px; border-top:1px solid #e3e6f0; text-align:right;">
                        <button type="button" class="btn btn-secondary" style="padding:8px 16px; margin-right:5px;" onclick="closeModal('modal-email-<?php echo $u['id']; ?>')">Cancel</button>
                        <button type="submit" class="btn btn-primary" style="padding:8px 16px;">Dispatch System Message Email</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    
    <script>
    function openModal(modalId) {
        var modal = document.getElementById(modalId);
        if(modal) {
            modal.classList.add('active');
        }
    }
    function closeModal(modalId) {
        var modal = document.getElementById(modalId);
        if(modal) {
            modal.classList.remove('active');
        }
    }
    </script>
    <script src="../assets/js/main.js"></script>
</body>
</html>
