<?php
$pageTitle = 'Admin Users';
require_once dirname(__DIR__) . '/includes/header.php';

// Only superadmin can manage users
if ($admin['role'] !== 'superadmin') {
    flash('Access denied. Superadmin only.','error');
    redirect(ADMIN_URL.'/index.php');
}

// Delete
if (isset($_GET['delete'])) {
    $did = (int)$_GET['delete'];
    if ($did === (int)$admin['id']) { flash('Cannot delete your own account.','error'); redirect(ADMIN_URL.'/pages/admin-users.php'); }
    db()->query("DELETE FROM admin_users WHERE id=$did");
    flash('User deleted.','success');
    redirect(ADMIN_URL.'/pages/admin-users.php');
}

$error = '';
// Add user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_add'])) {
    $uname = trim($_POST['username'] ?? '');
    $fname = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $pass  = $_POST['password'] ?? '';
    $role  = $_POST['role'] ?? 'editor';
    if (!$uname || !$pass) { $error = 'Username and password are required.'; }
    else {
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        $st = db()->prepare("INSERT INTO admin_users (username,password,full_name,email,role) VALUES (?,?,?,?,?)");
        $st->bind_param('sssss', $uname,$hash,$fname,$email,$role);
        if ($st->execute()) { flash('Admin user added!','success'); redirect(ADMIN_URL.'/pages/admin-users.php'); }
        else { $error = 'Username already exists.'; }
    }
}
// Change password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_chpass'])) {
    $uid  = (int)$_POST['user_id'];
    $pass = $_POST['new_password'] ?? '';
    if (strlen($pass) < 6) { $error = 'Password must be at least 6 characters.'; }
    else {
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        $st = db()->prepare("UPDATE admin_users SET password=? WHERE id=?");
        $st->bind_param('si', $hash, $uid);
        $st->execute();
        flash('Password updated!','success');
        redirect(ADMIN_URL.'/pages/admin-users.php');
    }
}

$users = db()->query("SELECT id,username,full_name,email,role,last_login,created_at FROM admin_users ORDER BY id")->fetch_all(MYSQLI_ASSOC);
$editPass = isset($_GET['chpass']) ? (int)$_GET['chpass'] : 0;
?>
<div class="page-header">
    <h1>Admin Users</h1>
    <div class="page-header-actions">
        <button onclick="document.getElementById('addModal').classList.add('open')" class="btn btn-primary"><i class="fas fa-user-plus"></i> Add User</button>
    </div>
</div>

<?php if ($error): ?><div class="flash flash-error"><i class="fas fa-exclamation-circle"></i><?=e($error)?></div><?php endif; ?>

<?php if ($editPass): ?>
<div class="card" style="margin-bottom:20px;border:2px solid var(--warn)">
    <div class="card-header"><i class="fas fa-key" style="color:var(--warn)"></i><h2>Change Password</h2></div>
    <div class="card-body">
        <form method="POST" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
            <input type="hidden" name="user_id" value="<?=$editPass?>">
            <div class="form-group" style="margin:0;flex:1;min-width:200px">
                <label class="form-label">New Password</label>
                <input type="password" name="new_password" class="form-control" placeholder="Min 6 characters" required>
            </div>
            <button type="submit" name="action_chpass" class="btn btn-primary"><i class="fas fa-save"></i> Update</button>
            <a href="admin-users.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><i class="fas fa-users-cog" style="color:var(--brand)"></i><h2>All Admin Users</h2>
        <span style="color:var(--muted);font-size:13px;margin-left:auto"><?=count($users)?> users</span>
    </div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Name</th><th>Username</th><th>Email</th><th>Role</th><th>Last Login</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($users as $u): ?>
            <tr <?=$u['id']==$admin['id']?'style="background:#f0fdf4"':''?>>
                <td style="font-weight:600">
                    <div style="display:flex;align-items:center;gap:10px">
                        <div style="width:34px;height:34px;background:var(--brand);border-radius:50%;display:grid;place-items:center;color:#fff;font-weight:700;font-size:13px;flex-shrink:0"><?=strtoupper(substr($u['full_name']??$u['username'],0,1))?></div>
                        <?=e($u['full_name']??$u['username'])?>
                        <?php if($u['id']==$admin['id']): ?><span class="badge badge-green" style="font-size:10px">You</span><?php endif; ?>
                    </div>
                </td>
                <td style="color:var(--muted)">@<?=e($u['username'])?></td>
                <td style="font-size:13px"><?=e($u['email'])?></td>
                <td><span class="badge <?=$u['role']==='superadmin'?'badge-blue':'badge-yellow' ?>"><?=ucfirst($u['role'])?></span></td>
                <td style="font-size:12px;color:var(--muted)"><?=$u['last_login']?date('M j, Y g:i A',strtotime($u['last_login'])):'Never'?></td>
                <td>
                    <div style="display:flex;gap:6px">
                        <a href="admin-users.php?chpass=<?=$u['id']?>" class="btn btn-secondary btn-sm btn-icon" title="Change Password"><i class="fas fa-key"></i></a>
                        <?php if($u['id']!=$admin['id']): ?>
                        <button onclick="confirmDelete('admin-users.php?delete=<?=$u['id']?>','user <?=e(addslashes($u['username']))?>')" class="btn btn-danger btn-sm btn-icon" title="Delete"><i class="fas fa-trash"></i></button>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add User Modal -->
<div class="modal-overlay" id="addModal" onclick="if(event.target===this)this.classList.remove('open')">
    <div class="modal-box">
        <div class="modal-title"><i class="fas fa-user-plus" style="color:var(--brand)"></i> Add Admin User</div>
        <form method="POST">
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" class="form-control" placeholder="username" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Password *</label>
                    <input type="password" name="password" class="form-control" placeholder="Min 6 chars" required>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">Full Name</label>
                <input type="text" name="full_name" class="form-control" placeholder="Display name">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" placeholder="admin@email.com">
                </div>
                <div class="form-group">
                    <label class="form-label">Role</label>
                    <select name="role" class="form-select">
                        <option value="editor">Editor</option>
                        <option value="superadmin">Superadmin</option>
                    </select>
                </div>
            </div>
            <div class="modal-btns">
                <button type="button" onclick="document.getElementById('addModal').classList.remove('open')" class="btn btn-secondary">Cancel</button>
                <button type="submit" name="action_add" class="btn btn-primary"><i class="fas fa-save"></i> Add User</button>
            </div>
        </form>
    </div>
</div>
<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
