<?php
/**
 * Super Administrator Central Dashboard
 * Location: public_html/admin/dashboard_admin.php
 * Displays: #users, #partners, #projects, #artifacts, #artifact templates, plus user & admin password manager
 */

require_once __DIR__ . '/../connections/connect.php';
if (file_exists(__DIR__ . '/../includes/functions.php')) {
    require_once __DIR__ . '/../includes/functions.php';
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Defensive helper fallback (ensures no fatal error if functions.php was not updated on disk)
if (!function_exists('is_admin_logged_in')) {
    function is_admin_logged_in() {
        return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true && !empty($_SESSION['admin_user_id']);
    }
}
if (!function_exists('require_admin_login')) {
    function require_admin_login() {
        if (!is_admin_logged_in()) {
            header("Location: login_admin.php?error=" . urlencode("Super Administrator authentication required."));
            exit;
        }
    }
}
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        return htmlspecialchars(trim((string)$data), ENT_QUOTES, 'UTF-8');
    }
}

// Enforce Super Admin authentication
require_admin_login();

$msg = '';
$error = '';

$admin_id = $_SESSION['admin_user_id'];
$admin_username = $_SESSION['admin_username'];

// Handle POST actions (Admin Profile Update, User Password Reset / Credentials Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // 1. UPDATE ADMIN'S OWN PROFILE & PASSWORD
    if ($action === 'update_admin_self') {
        $new_username = trim($_POST['username'] ?? '');
        $new_email = trim($_POST['email'] ?? '');
        $new_fullname = trim($_POST['full_name'] ?? '');
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if (empty($new_username) || empty($new_email)) {
            $error = "Admin username and email cannot be empty.";
        } elseif (!empty($new_password) && $new_password !== $confirm_password) {
            $error = "New password and confirmation do not match.";
        } else {
            try {
                if (!empty($new_password)) {
                    $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE admin_users SET username = :username, email = :email, full_name = :full_name, password_hash = :hash WHERE id = :id");
                    $stmt->execute([
                        'username' => $new_username,
                        'email' => $new_email,
                        'full_name' => $new_fullname,
                        'hash' => $new_hash,
                        'id' => $admin_id
                    ]);
                } else {
                    $stmt = $pdo->prepare("UPDATE admin_users SET username = :username, email = :email, full_name = :full_name WHERE id = :id");
                    $stmt->execute([
                        'username' => $new_username,
                        'email' => $new_email,
                        'full_name' => $new_fullname,
                        'id' => $admin_id
                    ]);
                }

                $_SESSION['admin_username'] = $new_username;
                $_SESSION['admin_email'] = $new_email;
                $_SESSION['admin_full_name'] = $new_fullname;
                $msg = "Your Super Administrator profile and credentials have been updated successfully.";
            } catch (PDOException $e) {
                $error = "Failed to update admin profile: " . $e->getMessage();
            }
        }
    }

    // 2. UPDATE USER CREDENTIALS & PASSWORD RESET
    if ($action === 'update_user_credentials') {
        $target_user_id = trim($_POST['target_user_id'] ?? '');
        $user_first_name = trim($_POST['first_name'] ?? '');
        $user_last_name = trim($_POST['last_name'] ?? '');
        $user_email = trim($_POST['email'] ?? '');
        $user_role = trim($_POST['role'] ?? 'TEAM_MEMBER');
        $user_status = trim($_POST['status'] ?? 'ACTIVE');
        $user_new_password = $_POST['user_new_password'] ?? '';

        if (empty($target_user_id) || empty($user_email)) {
            $error = "User ID and Email are required.";
        } else {
            try {
                if (!empty($user_new_password)) {
                    $user_hash = password_hash($user_new_password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE users SET first_name = :fn, last_name = :ln, email = :email, role = :role, status = :status, password_hash = :hash WHERE id = :id");
                    $stmt->execute([
                        'fn' => $user_first_name,
                        'ln' => $user_last_name,
                        'email' => $user_email,
                        'role' => $user_role,
                        'status' => $user_status,
                        'hash' => $user_hash,
                        'id' => $target_user_id
                    ]);
                } else {
                    $stmt = $pdo->prepare("UPDATE users SET first_name = :fn, last_name = :ln, email = :email, role = :role, status = :status WHERE id = :id");
                    $stmt->execute([
                        'fn' => $user_first_name,
                        'ln' => $user_last_name,
                        'email' => $user_email,
                        'role' => $user_role,
                        'status' => $user_status,
                        'id' => $target_user_id
                    ]);
                }

                $msg = "User credentials for " . htmlspecialchars($user_email) . " updated successfully.";
            } catch (PDOException $e) {
                $error = "Failed to update user: " . $e->getMessage();
            }
        }
    }
}

// -------------------------------------------------------------
// FETCH HIGH LEVEL APPLICATION DATA / METRICS
// -------------------------------------------------------------
try {
    // 1. # Users
    $count_users = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $count_active_users = $pdo->query("SELECT COUNT(*) FROM users WHERE status = 'ACTIVE'")->fetchColumn();

    // 2. # Partners (Subcontractors)
    $count_partners = $pdo->query("SELECT COUNT(*) FROM external_partners")->fetchColumn();

    // 3. # Projects
    $count_projects = $pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn();
    $count_active_projects = $pdo->query("SELECT COUNT(*) FROM projects WHERE status = 'ACTIVE'")->fetchColumn();

    // 4. # Artifacts Created
    $count_artifacts = $pdo->query("SELECT COUNT(*) FROM project_artifacts")->fetchColumn();
    $count_completed_artifacts = $pdo->query("SELECT COUNT(*) FROM project_artifacts WHERE status = 'COMPLETED'")->fetchColumn();

    // 5. # Artifact Templates (Standard Global vs Custom Tenant)
    $count_standard_templates = $pdo->query("SELECT COUNT(*) FROM artifact_templates WHERE is_standard_template = 1 OR account_id IS NULL")->fetchColumn();
    $count_custom_templates = $pdo->query("SELECT COUNT(*) FROM artifact_templates WHERE is_standard_template = 0 AND account_id IS NOT NULL")->fetchColumn();
    $count_total_templates = $count_standard_templates + $count_custom_templates;

    // 6. # Accounts / Companies
    $count_accounts = $pdo->query("SELECT COUNT(*) FROM accounts")->fetchColumn();

    // Fetch Current Admin Record
    $adminStmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = :id");
    $adminStmt->execute(['id' => $admin_id]);
    $current_admin = $adminStmt->fetch() ?: [
        'username' => 'admin',
        'email' => 'admin@mibuildqc.local',
        'full_name' => 'System Super Administrator'
    ];

    // Fetch All Users across all accounts with company names
    $usersStmt = $pdo->query("
        SELECT u.*, a.company_name 
        FROM users u 
        LEFT JOIN accounts a ON u.account_id = a.id 
        ORDER BY u.created_at DESC
    ");
    $all_users = $usersStmt->fetchAll();

    // Fetch Standard Templates
    $stdTemplatesStmt = $pdo->query("
        SELECT * FROM artifact_templates 
        WHERE is_standard_template = 1 OR account_id IS NULL 
        ORDER BY created_at DESC
    ");
    $standard_templates = $stdTemplatesStmt->fetchAll();

    // Fetch Recent System Audit Logs
    $auditLogsStmt = $pdo->query("
        SELECT * FROM audit_logs 
        ORDER BY created_at DESC 
        LIMIT 15
    ");
    $audit_logs = $auditLogsStmt->fetchAll();

} catch (PDOException $e) {
    $error = "Error fetching dashboard data: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Super Admin Dashboard - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>body { font-family: 'Plus Jakarta Sans', sans-serif; }</style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen">

    <!-- Top Navigation -->
    <header class="bg-slate-950 border-b border-slate-800 sticky top-0 z-30">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3.5 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-xl bg-indigo-600 flex items-center justify-center text-white font-black shadow-md">
                    QC
                </div>
                <div>
                    <div class="text-sm font-extrabold text-white flex items-center gap-2">
                        <span>MiBuildqc Control Panel</span>
                        <span class="text-[10px] px-2 py-0.5 rounded-full bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">SUPER ADMIN</span>
                    </div>
                </div>
            </div>

            <div class="flex items-center gap-3">
                <a href="create_artifact.php" class="px-3.5 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold shadow-md transition-all flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    <span> Build Standard Template</span>
                </a>

                <a href="../team/dashboard.php" class="px-3 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-semibold border border-slate-700 transition-colors">
                    Tenant View
                </a>

                <a href="logout_admin.php" class="p-2 rounded-xl bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/30 text-xs font-bold transition-colors" title="Log Out">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                    </svg>
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">

        <?php if (!empty($msg)): ?>
            <div class="p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs flex items-center justify-between">
                <span><?php echo htmlspecialchars($msg); ?></span>
                <button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white">✕</button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="p-4 rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs flex items-center justify-between">
                <span><?php echo htmlspecialchars($error); ?></span>
                <button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white">✕</button>
            </div>
        <?php endif; ?>

        <!-- High-Level Application Data Metrics Cards -->
        <div class="space-y-3">
            <h2 class="text-xs font-bold uppercase tracking-wider text-slate-400">High-Level Application Data</h2>
            
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
                
                <!-- 1. # Users -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Total Users</span>
                        <span class="text-indigo-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_users; ?></div>
                    <div class="text-[10px] text-emerald-400 font-medium">● <?php echo (int)$count_active_users; ?> Active</div>
                </div>

                <!-- 2. # Partners -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Partners</span>
                        <span class="text-amber-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_partners; ?></div>
                    <div class="text-[10px] text-slate-400">Subcontractors</div>
                </div>

                <!-- 3. # Projects -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Projects</span>
                        <span class="text-cyan-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_projects; ?></div>
                    <div class="text-[10px] text-cyan-300 font-medium"><?php echo (int)$count_active_projects; ?> Active Sites</div>
                </div>

                <!-- 4. # Artifacts Created -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Artifacts</span>
                        <span class="text-emerald-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_artifacts; ?></div>
                    <div class="text-[10px] text-emerald-400 font-medium"><?php echo (int)$count_completed_artifacts; ?> Completed</div>
                </div>

                <!-- 5. # Artifact Templates -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Templates</span>
                        <span class="text-purple-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_total_templates; ?></div>
                    <div class="text-[10px] text-purple-300 font-medium"><?php echo (int)$count_standard_templates; ?> Standard Global</div>
                </div>

                <!-- 6. # Accounts / Companies -->
                <div class="bg-slate-800/90 border border-slate-700/80 rounded-2xl p-4 space-y-1 shadow-lg">
                    <div class="text-xs text-slate-400 flex items-center justify-between">
                        <span>Companies</span>
                        <span class="text-orange-400 font-bold">#</span>
                    </div>
                    <div class="text-2xl font-black text-white"><?php echo (int)$count_accounts; ?></div>
                    <div class="text-[10px] text-orange-300 font-medium">Tenant Accounts</div>
                </div>

            </div>
        </div>

        <!-- Standard QC Templates Builder Banner -->
        <div class="bg-gradient-to-r from-indigo-900/60 to-purple-900/60 border border-indigo-500/30 rounded-3xl p-6 sm:p-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
            <div class="space-y-2">
                <div class="flex items-center gap-2">
                    <span class="text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-indigo-500/30 text-indigo-200 border border-indigo-400/30">
                        GLOBAL CHECKLIST BUILDER
                    </span>
                </div>
                <h3 class="text-xl font-bold text-white">Standard QC Templates for All Users</h3>
                <p class="text-xs text-slate-300 max-w-xl">
                    Create master standardized quality control templates (e.g. Concrete Pre-Pour, Waterproofing, Framing) that every company and user across the application can immediately access and execute.
                </p>
            </div>
            <a href="create_artifact.php" class="px-5 py-3 rounded-2xl bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs shadow-xl shadow-indigo-600/30 flex items-center gap-2 shrink-0 transition-all">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                <span>Launch create_artifact.php</span>
            </a>
        </div>

        <!-- Two Columns: Admin Self-Credentials Update & Global User Management -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Left Col (1): Super Admin Profile & Password Update -->
            <div class="bg-slate-800/90 border border-slate-700/80 rounded-3xl p-6 space-y-5 shadow-xl">
                <div class="border-b border-slate-700/80 pb-3">
                    <h3 class="text-base font-bold text-white flex items-center gap-2">
                        <svg class="w-4 h-4 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                        </svg>
                        <span>My Admin Credentials</span>
                    </h3>
                    <p class="text-xs text-slate-400 mt-0.5">Change Super Admin username & password.</p>
                </div>

                <form action="dashboard_admin.php" method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="update_admin_self">

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Super Admin Username *</label>
                        <input type="text" name="username" required value="<?php echo htmlspecialchars($current_admin['username']); ?>" class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white focus:border-indigo-500 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Admin Email Address *</label>
                        <input type="email" name="email" required value="<?php echo htmlspecialchars($current_admin['email']); ?>" class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white focus:border-indigo-500 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Full Name</label>
                        <input type="text" name="full_name" value="<?php echo htmlspecialchars($current_admin['full_name']); ?>" class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white focus:border-indigo-500 outline-none">
                    </div>

                    <div class="pt-2 border-t border-slate-700/80 space-y-3">
                        <div class="text-xs font-bold text-indigo-300">Update Admin Password</div>

                        <div>
                            <label class="block text-xs text-slate-400 mb-1">New Password</label>
                            <input type="password" name="new_password" placeholder="Leave blank to keep unchanged" class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white focus:border-indigo-500 outline-none">
                        </div>

                        <div>
                            <label class="block text-xs text-slate-400 mb-1">Confirm New Password</label>
                            <input type="password" name="confirm_password" placeholder="Confirm new password" class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white focus:border-indigo-500 outline-none">
                        </div>
                    </div>

                    <button type="submit" class="w-full py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs rounded-xl transition-all shadow-md">
                        Save Admin Credentials
                    </button>
                </form>
            </div>

            <!-- Right Col (2 & 3): Global User Account & Password Manager -->
            <div class="lg:col-span-2 bg-slate-800/90 border border-slate-700/80 rounded-3xl p-6 space-y-5 shadow-xl">
                <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-b border-slate-700/80 pb-3">
                    <div>
                        <h3 class="text-base font-bold text-white flex items-center gap-2">
                            <svg class="w-4 h-4 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path>
                            </svg>
                            <span>Global User Management & Password Reset</span>
                        </h3>
                        <p class="text-xs text-slate-400 mt-0.5">Manage usernames, roles, and reset passwords for any registered user.</p>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs text-slate-300">
                        <thead class="bg-slate-900/80 text-slate-400 font-bold uppercase tracking-wider text-[10px]">
                            <tr>
                                <th class="py-3 px-3">User</th>
                                <th class="py-3 px-3">Company</th>
                                <th class="py-3 px-3">Role</th>
                                <th class="py-3 px-3">Status</th>
                                <th class="py-3 px-3 text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700/60">
                            <?php if (empty($all_users)): ?>
                                <tr>
                                    <td colspan="5" class="py-6 text-center text-slate-500">No users found in database.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($all_users as $user): ?>
                                    <tr class="hover:bg-slate-700/30 transition-colors">
                                        <td class="py-3 px-3">
                                            <div class="font-bold text-white"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></div>
                                            <div class="text-[11px] text-slate-400 font-mono"><?php echo htmlspecialchars($user['email']); ?></div>
                                        </td>
                                        <td class="py-3 px-3 text-slate-300 font-medium">
                                            <?php echo htmlspecialchars($user['company_name'] ?? 'Unassigned'); ?>
                                        </td>
                                        <td class="py-3 px-3">
                                            <span class="px-2 py-0.5 rounded text-[10px] font-bold <?php echo $user['role'] === 'PRIMARY_ADMIN' ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30' : 'bg-slate-700 text-slate-300'; ?>">
                                                <?php echo htmlspecialchars($user['role']); ?>
                                            </span>
                                        </td>
                                        <td class="py-3 px-3">
                                            <span class="text-[10px] font-bold <?php echo $user['status'] === 'ACTIVE' ? 'text-emerald-400' : 'text-amber-400'; ?>">
                                                ● <?php echo htmlspecialchars($user['status']); ?>
                                            </span>
                                        </td>
                                        <td class="py-3 px-3 text-right">
                                            <button onclick="openUserModal(<?php echo htmlspecialchars(json_encode($user)); ?>)" class="px-2.5 py-1.5 bg-slate-700 hover:bg-indigo-600 hover:text-white rounded-lg text-[11px] font-bold text-slate-200 transition-colors">
                                                Edit / Reset Pass
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

            </div>

        </div>

    </main>

    <!-- Modal for User Edit & Password Reset -->
    <div id="userModal" class="fixed inset-0 bg-black/70 backdrop-blur-xs hidden z-50 flex items-center justify-center p-4">
        <div class="bg-slate-900 border border-slate-800 rounded-3xl max-w-md w-full p-6 space-y-4 shadow-2xl">
            <div class="flex items-center justify-between border-b border-slate-800 pb-3">
                <h4 class="text-sm font-bold text-white">Edit User & Reset Password</h4>
                <button onclick="closeUserModal()" class="text-slate-400 hover:text-white font-bold">✕</button>
            </div>

            <form action="dashboard_admin.php" method="POST" class="space-y-3.5 text-xs">
                <input type="hidden" name="action" value="update_user_credentials">
                <input type="hidden" name="target_user_id" id="modal_user_id">

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1">First Name</label>
                        <input type="text" name="first_name" id="modal_first_name" required class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-white outline-none focus:border-indigo-500">
                    </div>
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1">Last Name</label>
                        <input type="text" name="last_name" id="modal_last_name" required class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-white outline-none focus:border-indigo-500">
                    </div>
                </div>

                <div>
                    <label class="block text-slate-300 font-semibold mb-1">Email Address</label>
                    <input type="email" name="email" id="modal_email" required class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-white outline-none focus:border-indigo-500">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1">Role</label>
                        <select name="role" id="modal_role" class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-white outline-none">
                            <option value="PRIMARY_ADMIN">PRIMARY_ADMIN</option>
                            <option value="TEAM_MEMBER">TEAM_MEMBER</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1">Status</label>
                        <select name="status" id="modal_status" class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-white outline-none">
                            <option value="ACTIVE">ACTIVE</option>
                            <option value="PENDING_VERIFICATION">PENDING_VERIFICATION</option>
                            <option value="INACTIVE">INACTIVE</option>
                        </select>
                    </div>
                </div>

                <div class="p-3.5 bg-slate-800/80 rounded-2xl border border-slate-700/80 space-y-2">
                    <label class="block font-bold text-indigo-300">Set New Password</label>
                    <input type="text" name="user_new_password" placeholder="Enter new password (or leave empty)" class="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl font-mono text-white outline-none focus:border-indigo-500">
                    <p class="text-[10px] text-slate-400">Leave blank to keep user's current password unchanged.</p>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="closeUserModal()" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 rounded-xl text-slate-300 font-semibold">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2 bg-indigo-600 hover:bg-indigo-500 rounded-xl text-white font-bold shadow-md">
                        Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openUserModal(user) {
            document.getElementById('modal_user_id').value = user.id;
            document.getElementById('modal_first_name').value = user.first_name || '';
            document.getElementById('modal_last_name').value = user.last_name || '';
            document.getElementById('modal_email').value = user.email || '';
            document.getElementById('modal_role').value = user.role || 'TEAM_MEMBER';
            document.getElementById('modal_status').value = user.status || 'ACTIVE';
            document.getElementById('userModal').classList.remove('hidden');
        }

        function closeUserModal() {
            document.getElementById('userModal').classList.add('hidden');
        }
    </script>

</body>
</html>