<?php
// user-management.php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

require_once '../config/config.php';
session_start();

// === AUTH & ROLE CHECK ===
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id        = (int)$_SESSION['user_id'];
$user_role      = $_SESSION['role'];
$user_company_id = $_SESSION['company_id'] ?? null;

// === BUILD WHERE CLAUSE ===
$where  = $user_role === 'admin' ? "" : "WHERE u.company_id = ?";
$params = $user_role === 'admin' ? [] : [$user_company_id];
$types  = $user_role === 'admin' ? '' : 'i';

// === FETCH USERS ===
$sql = "SELECT u.id, u.email, u.role, u.company_id, c.company_name, u.name 
        FROM users u 
        LEFT JOIN companies c ON u.company_id = c.id 
        $where 
        ORDER BY c.company_name, u.email";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$users = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// === FETCH COMPANIES FOR DROPDOWN ===
if ($user_role === 'admin') {
    $stmt = $conn->prepare("SELECT id, company_name FROM companies ORDER BY company_name");
    $stmt->execute();
    $res = $stmt->get_result();
    $companies = $res->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $stmt = $conn->prepare("SELECT id, company_name FROM companies WHERE id = ?");
    $stmt->bind_param('i', $user_company_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $companies = $res->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// === GROUP USERS BY COMPANY ===
$users_by_company = [];
foreach ($users as $user) {
    $company_name = $user['company_name'] ?: 'No Company';
    $users_by_company[$company_name][] = $user;
}

// === HANDLE SAVE USER ===
$error = $success = '';
if (isset($_POST['save_user'])) {
    $edit_id     = (int)($_POST['user_id'] ?? 0);
    $name        = trim($_POST['name'] ?? '');
    $email       = trim($_POST['email'] ?? '');
    $password    = $_POST['password'] ?? '';
    $role        = $_POST['role'] ?? 'user';
    $company_id  = $user_role === 'admin' ? (!empty($_POST['company_id']) ? (int)$_POST['company_id'] : null) : $user_company_id;

    // === VALIDATION ===
    if (empty($name)) {
        $error = "Name is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif ($password && strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } elseif ($edit_id == 0 && empty($password)) {
        $error = "Password is required for new users.";
    } elseif ($user_role !== 'admin' && $role === 'admin') {
        $error = "You cannot create admin users.";
    } else {
        // Check email uniqueness
        $check = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $check->bind_param('si', $email, $edit_id);
        $check->execute();
        $check_res = $check->get_result();
        if ($check_res->num_rows > 0) {
            $error = "Email already exists.";
        }
        $check->close();
    }

    if (!$error) {
        $hash = !empty($password) ? password_hash($password, PASSWORD_DEFAULT) : null;

        if ($edit_id) {
            // === UPDATE USER ===
            if ($hash) {
                $sql = "UPDATE users SET name = ?, email = ?, password = ?, role = ?, company_id = ? WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('ssssii', $name, $email, $hash, $role, $company_id, $edit_id);
            } else {
                $sql = "UPDATE users SET name = ?, email = ?, role = ?, company_id = ? WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('sssii', $name, $email, $role, $company_id, $edit_id);
            }
        } else {
            // === INSERT USER ===
            $sql = "INSERT INTO users (name, email, password, role, company_id) VALUES (?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssssi', $name, $email, $hash, $role, $company_id);
        }

        if ($stmt->execute()) {
            $success = "User saved successfully!";
            $stmt->close();
            header("Location: admin-user-management.php?success=1");
            exit;
        } else {
            $error = "Database error. Please try again.";
        }
    }
}

// === HANDLE DELETE ===
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    if ($del_id !== $user_id) {
        $check = $user_role === 'admin'
            ? $conn->prepare("SELECT id FROM users WHERE id = ?")
            : $conn->prepare("SELECT id FROM users WHERE id = ? AND company_id = ?");

        if ($user_role === 'admin') {
            $check->bind_param('i', $del_id);
        } else {
            $check->bind_param('ii', $del_id, $user_company_id);
        }
        $check->execute();
        $res = $check->get_result();
        if ($res->num_rows > 0) {
            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param('i', $del_id);
            $stmt->execute();
            $stmt->close();
            $success = "User deleted successfully!";
        } else {
            $error = "User not found or access denied.";
        }
        $check->close();
    } else {
        $error = "You cannot delete your own account.";
    }
    header("Location: user-management.php" . ($error ? "?error=" . urlencode($error) : ""));
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    :root {
        --primary: #7c3aed;
        --primary-light: #8b5cf6;
        --secondary: #06b6d4;
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --dark: #0f172a;
        --darker: #020617;
        --card-bg: rgba(255, 255, 255, .08);
        --border: rgba(255, 255, 255, .1);
        --text: #f1f5f9;
        --text-light: #cbd5e1;
        --radius: 1rem;
        --radius-sm: .75rem;
        --transition: all .3s cubic-bezier(.4, 0, .2, 1)
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box
    }

    body {
        font-family: 'Inter', sans-serif;
        background: linear-gradient(135deg, var(--darker), var(--dark));
        color: var(--text);
        min-height: 100vh
    }

    .background {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        overflow: hidden
    }

    .gradient-orb {
        position: absolute;
        border-radius: 50%;
        filter: blur(80px);
        opacity: .3;
        animation: float 25s ease-in-out infinite
    }

    .orb-1 {
        width: 400px;
        height: 400px;
        background: linear-gradient(45deg, var(--primary), var(--secondary));
        top: -100px;
        left: -100px
    }

    .orb-2 {
        width: 300px;
        height: 300px;
        background: linear-gradient(45deg, var(--secondary), var(--success));
        bottom: -50px;
        right: -50px;
        animation-delay: -8s
    }

    @keyframes float {

        0%,
        100% {
            transform: translate(0, 0) scale(1)
        }

        25% {
            transform: translate(100px, 100px) scale(1.1)
        }

        50% {
            transform: translate(0, 200px) scale(.9)
        }

        75% {
            transform: translate(-100px, 100px) scale(1.05)
        }
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 2rem
    }

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 3rem;
        flex-wrap: wrap;
        gap: 1.5rem
    }

    .header-content h1 {
        font-size: 2.5rem;
        font-weight: 700;
        background: linear-gradient(135deg, var(--text), var(--primary-light));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: .5rem
    }

    .header-content p {
        color: var(--text-light);
        font-size: 1.1rem
    }

    .btn {
        display: inline-flex;
        align-items: center;
        gap: .5rem;
        padding: .875rem 1.5rem;
        border: none;
        border-radius: var(--radius-sm);
        font-weight: 600;
        font-size: .95rem;
        text-decoration: none;
        cursor: pointer;
        transition: var(--transition);
        position: relative;
        overflow: hidden
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: #fff
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(124, 58, 237, .4)
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 3rem
    }

    .stat-card {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 1.5rem;
        text-align: center;
        transition: var(--transition)
    }

    .stat-card:hover {
        transform: translateY(-5px);
        border-color: var(--primary-light);
        box-shadow: 0 20px 40px rgba(0, 0, 0, .3)
    }

    .stat-number {
        font-size: 2rem;
        font-weight: 700;
        background: linear-gradient(135deg, var(--text), var(--primary-light));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent
    }

    .stat-label {
        color: var(--text-light);
        font-size: .9rem;
        margin-top: .5rem
    }

    .company-section {
        margin-bottom: 3rem
    }

    .company-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid var(--border)
    }

    .company-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: var(--text);
        display: flex;
        align-items: center;
        gap: .75rem
    }

    .company-user-count {
        background: var(--primary);
        color: #fff;
        padding: .25rem .75rem;
        border-radius: 1rem;
        font-size: .8rem;
        font-weight: 600
    }

    .table-container {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        overflow: hidden;
        box-shadow: 0 20px 40px rgba(0, 0, 0, .3);
        margin-bottom: 2rem
    }

    .table {
        width: 100%;
        border-collapse: collapse
    }

    .table-header {
        background: linear-gradient(135deg, var(--primary), var(--primary-light))
    }

    .table th {
        padding: 1.25rem 1rem;
        text-align: left;
        font-weight: 600;
        color: #fff;
        font-size: .9rem;
        text-transform: uppercase;
        letter-spacing: .5px
    }

    .table td {
        padding: 1.25rem 1rem;
        border-bottom: 1px solid var(--border);
        color: var(--text)
    }

    .table tbody tr {
        transition: var(--transition)
    }

    .table tbody tr:hover {
        background: rgba(255, 255, 255, .05);
        transform: translateX(5px)
    }

    .role-badge {
        display: inline-flex;
        align-items: center;
        gap: .5rem;
        padding: .5rem 1rem;
        border-radius: 2rem;
        font-size: .8rem;
        font-weight: 600;
        text-transform: uppercase
    }

    .role-admin {
        background: rgba(239, 68, 68, .2);
        color: var(--danger)
    }

    .role-sub_admin {
        background: rgba(245, 158, 11, .2);
        color: var(--warning)
    }

    .role-user {
        background: rgba(16, 185, 129, .2);
        color: var(--success)
    }

    .action-buttons {
        display: flex;
        gap: .5rem;
        flex-wrap: wrap
    }

    .btn-action {
        padding: .5rem .75rem;
        border: none;
        border-radius: var(--radius-sm);
        font-size: .8rem;
        font-weight: 500;
        text-decoration: none;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: .25rem
    }

    .btn-edit {
        background: rgba(245, 158, 11, .2);
        color: var(--warning)
    }

    .btn-delete {
        background: rgba(239, 68, 68, .2);
        color: var(--danger)
    }

    .btn-action:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, .2)
    }

    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: var(--text-light)
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 1rem;
        opacity: .5
    }

    .empty-state h3 {
        font-size: 1.5rem;
        margin-bottom: .5rem;
        color: var(--text)
    }

    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, .8);
        backdrop-filter: blur(10px);
        justify-content: center;
        align-items: center;
        z-index: 1000;
        padding: 1rem
    }

    .modal.active {
        display: flex;
        animation: fadeIn .3s ease
    }

    .modal-content {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        padding: 2.5rem;
        border-radius: var(--radius);
        width: 100%;
        max-width: 500px;
        box-shadow: 0 25px 50px rgba(0, 0, 0, .4);
        position: relative
    }

    .modal-header {
        /* margin-bottom: 2rem; */
        text-align: center
    }

    .modal-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: var(--text);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: .5rem
    }

    .close-btn {
        position: absolute;
        top: 1.5rem;
        right: 1.5rem;
        background: none;
        border: none;
        color: var(--text-light);
        font-size: 1.5rem;
        cursor: pointer;
        transition: var(--transition)
    }

    .close-btn:hover {
        color: var(--danger);
        transform: rotate(90deg)
    }

    .form-group {
        margin-bottom: 1.5rem
    }

    .form-label {
        font-weight: 600;
        margin-bottom: .5rem;
        display: block;
        color: var(--text);
        font-size: .95rem
    }

    .form-input,
    .form-select {
        width: 100%;
        padding: .875rem 1rem;
        background: rgba(255, 255, 255, .07);
        border: 1.5px solid var(--border);
        border-radius: var(--radius-sm);
        color: var(--text);
        font-size: .95rem;
        transition: var(--transition)
    }

    .form-input:focus,
    .form-select:focus {
        outline: none;
        border-color: var(--primary-light);
        background: rgba(124, 58, 237, .1);
        box-shadow: 0 0 0 3px rgba(124, 58, 237, .2)
    }

    .form-helper {
        font-size: .8rem;
        color: var(--text-light);
        margin-top: .25rem
    }

    .modal-actions {
        display: flex;
        gap: 1rem;
        margin-top: 2rem
    }

    .btn-secondary {
        background: rgba(255, 255, 255, .1);
        color: var(--text);
        border: 1px solid var(--border)
    }

    .btn-secondary:hover {
        background: rgba(255, 255, 255, .15)
    }

    .alert-success {
        background: rgba(16, 185, 129, .2);
        border: 1px solid rgba(16, 185, 129, .3);
        color: var(--success);
        padding: 1rem 1.5rem;
        border-radius: var(--radius-sm);
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        gap: .5rem
    }

    .alert-error {
        background: rgba(239, 68, 68, .2);
        border: 1px solid rgba(239, 68, 68, .3);
        color: var(--danger);
        padding: 1rem 1.5rem;
        border-radius: var(--radius-sm);
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        gap: .5rem
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: scale(.9)
        }

        to {
            opacity: 1;
            transform: scale(1)
        }
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px)
        }

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

    .fade-in-up {
        animation: fadeInUp .6s ease-out
    }

    @media(max-width:1024px) {
        .container {
            padding: 1.5rem
        }

        .header {
            flex-direction: column;
            align-items: stretch
        }
    }

    @media(max-width:768px) {
        .table-container {
            overflow-x: auto
        }

        .table {
            min-width: 700px
        }

        .stats-grid {
            grid-template-columns: repeat(2, 1fr)
        }

        .header-content h1 {
            font-size: 2rem
        }

        .action-buttons {
            flex-direction: column
        }

        .modal-content {
            padding: 2rem 1.5rem
        }

        .company-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem
        }
    }

    @media(max-width:480px) {
        .container {
            padding: 1rem
        }

        .stats-grid {
            grid-template-columns: 1fr
        }

        .modal-actions {
            flex-direction: column
        }
    }
    option{
        color: black;
    }
    </style>
</head>

<body>
    <div class="background">
        <div class="gradient-orb orb-1"></div>
        <div class="gradient-orb orb-2"></div>
    </div>

    <div class="container">
        <div class="header fade-in-up">
            <div class="header-content">
                <h1>User Management</h1>
                <p>Manage users company-wise with proper access control</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()">Add New User</button>
            <a href="./admin-dashboard.php"><button class="btn btn-primary">Dashboard</button></a>
        </div>

        <?php if (isset($_GET['success']) || $success): ?>
        <div class="alert-success fade-in-up">
            User saved successfully!
        </div>
        <?php endif; ?>

        <?php if ($error || isset($_GET['error'])): ?>
        <div class="alert-error fade-in-up">
            <?= htmlspecialchars($error ?: $_GET['error']) ?>
        </div>
        <?php endif; ?>

        <div class="stats-grid fade-in-up" style="animation-delay:0.1s">
            <div class="stat-card"><span class="stat-number"><?= count($users) ?></span><span class="stat-label">Total
                    Users</span></div>
            <div class="stat-card"><span class="stat-number"><?= count($companies) ?></span><span
                    class="stat-label">Companies</span></div>
            <div class="stat-card"><span
                    class="stat-number"><?= count(array_filter($users, fn($u) => $u['role'] === 'admin')) ?></span><span
                    class="stat-label">Admins</span></div>
            <div class="stat-card"><span
                    class="stat-number"><?= count(array_filter($users, fn($u) => $u['role'] === 'user')) ?></span><span
                    class="stat-label">Regular Users</span></div>
        </div>

        <?php if (empty($users_by_company)): ?>
        <div class="empty-state fade-in-up">
            <h3>No Users Found</h3>
            <p>Get started by adding your first user</p>
            <button class="btn btn-primary" onclick="openAddModal()" style="margin-top:1rem;">Add First User</button>
        </div>
        <?php else: ?>
        <?php foreach ($users_by_company as $company_name => $company_users): ?>
        <div class="company-section fade-in-up">
            <div class="company-header">
                <h2 class="company-title">
                    <?= htmlspecialchars($company_name) ?>
                    <span class="company-user-count"><?= count($company_users) ?> users</span>
                </h2>
            </div>
            <div class="table-container">
                <table class="table">
                    <thead class="table-header">
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Role</th>
                            <th>Company</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($company_users as $u): ?>
                        <tr>
                            <td>
                                <div style="font-weight:600;"><?= htmlspecialchars($u['name'] ?? '—') ?></div>
                            </td>
                            <td>
                                <div style="font-weight:600;"><?= htmlspecialchars($u['email']) ?></div>
                                <div style="font-size:0.8rem;color:var(--text-light);">ID: <?= $u['id'] ?></div>
                            </td>
                            <td>
                                <span class="role-badge role-<?= str_replace('_', '-', $u['role']) ?>">
                                    <?= ucfirst(str_replace('_', ' ', $u['role'])) ?>
                                </span>
                            </td>
                            <td><span
                                    style="color:var(--text-light);"><?= htmlspecialchars($u['company_name'] ?: 'No Company') ?></span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-action btn-edit"
                                        onclick='openEditModal(<?= json_encode($u, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'
                                        title="Edit">Edit</button>
                                    <?php if ($u['id'] != $user_id): ?>
                                    <a href="?delete=<?= $u['id'] ?>" class="btn-action btn-delete" title="Delete"
                                        onclick="return confirm('Delete <?= addslashes(htmlspecialchars($u['email'])) ?>? This cannot be undone.')">Delete</a>
                                    <?php else: ?>
                                    <span class="btn-action" style="opacity:0.5;cursor:not-allowed;"
                                        title="Cannot delete own account">Delete</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- MODAL -->
    <div class="modal" id="userModal">
        <div class="modal-content">
            <button class="close-btn" onclick="closeModal()">X</button>
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">Add User</h2>
            </div>
            <form method="post" id="userForm">
                <input type="hidden" name="user_id" id="user_id">
                <div class="form-group">
                    <label class="form-label">Name</label>
                    <input type="text" name="name" id="name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email" id="email" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" id="password" class="form-input">
                    <div class="form-helper" id="passHelper">Enter a password (min. 6 characters)</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Role</label>
                    <select name="role" id="role" class="form-select" required>
                        <option value="user">User</option>
                        <option value="sub_admin">Sub-Admin</option>
                        <?php if ($user_role === 'admin'): ?>
                        <option value="admin">Admin</option>
                        <option value="purchase">Purchase</option>
                        <?php endif; ?>
                    </select>
                </div>
                <?php if ($user_role === 'admin'): ?>
                <div class="form-group">
                    <label class="form-label">Company</label>
                    <select name="company_id" id="company_id" class="form-select">
                        <option value="">No Company (Admin)</option>
                        <?php foreach ($companies as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['company_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php else: ?>
                <input type="hidden" name="company_id" value="<?= $user_company_id ?>">
                <div class="form-group">
                    <label class="form-label">Company</label>
                    <div
                        style="padding:.875rem 1rem;background:rgba(255,255,255,.05);border-radius:var(--radius-sm);color:var(--text-light);">
                        <?= htmlspecialchars($companies[0]['company_name'] ?? 'Your Company') ?>
                    </div>
                </div>
                <?php endif; ?>
                <div class="modal-actions">
                    <button type="submit" name="save_user" class="btn btn-primary">Save User</button>
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    function openAddModal() {
        document.getElementById('modalTitle').textContent = 'Add User';
        document.getElementById('passHelper').textContent = 'Enter a password (min. 6 characters)';
        document.getElementById('userForm').reset();
        document.getElementById('user_id').value = '';
        document.getElementById('password').required = true;
        document.getElementById('userModal').classList.add('active');
        setTimeout(() => document.getElementById('name').focus(), 300);
    }

    function openEditModal(user) {
        document.getElementById('modalTitle').textContent = 'Edit User';
        document.getElementById('passHelper').textContent = 'Leave blank to keep current password';
        document.getElementById('user_id').value = user.id;
        document.getElementById('name').value = user.name || '';
        document.getElementById('email').value = user.email;
        document.getElementById('role').value = user.role;
        <?php if ($user_role === 'admin'): ?>
        document.getElementById('company_id').value = user.company_id || '';
        <?php endif; ?>
        document.getElementById('password').required = false;
        document.getElementById('userModal').classList.add('active');
        setTimeout(() => document.getElementById('name').focus(), 300);
    }

    function closeModal() {
        document.getElementById('userModal').classList.remove('active');
    }

    document.addEventListener('keydown', e => e.key === 'Escape' && closeModal());
    document.getElementById('userModal').addEventListener('click', e => e.target === this && closeModal());

    // Auto-hide alerts
    setTimeout(() => {
        document.querySelectorAll('.alert-success, .alert-error').forEach(a => {
            a.style.transition = 'opacity 0.5s';
            a.style.opacity = '0';
            setTimeout(() => a.remove(), 500);
        });
    }, 5000);
    </script>
</body>

</html>