<?php
require_once '../config/koneksi.php';
require_once '../helpers/functions.php';

if (!isLogin() || !isAdmin()) {
    redirect('../auth/login.php');
}

$id = (int) ($_GET['id'] ?? 0);
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id=$id"));

if (!$user) {
    setFlash('danger', 'User tidak ditemukan.');
    redirect('users.php');
}

if (isset($_POST['update'])) {
    $nama = trim($_POST['nama']);
    $username = trim($_POST['username']);
    $role = $_POST['role'];
    $passwordBaru = trim($_POST['password_baru']);

    if (empty($nama) || empty($username) || empty($role)) {
        setFlash('danger', 'Field wajib diisi.');
        redirect("user_edit.php?id=$id");
    }

    $cek = mysqli_prepare($conn, "SELECT id FROM users WHERE username=? AND id != ?");
    mysqli_stmt_bind_param($cek, "si", $username, $id);
    mysqli_stmt_execute($cek);
    $result = mysqli_stmt_get_result($cek);

    if (mysqli_num_rows($result) > 0) {
        setFlash('danger', 'Username sudah digunakan user lain.');
        redirect("user_edit.php?id=$id");
    }

    if (!empty($passwordBaru)) {
        $passwordHash = password_hash($passwordBaru, PASSWORD_DEFAULT);
        $stmt = mysqli_prepare($conn, "UPDATE users SET nama=?, username=?, role=?, password=? WHERE id=?");
        mysqli_stmt_bind_param($stmt, "ssssi", $nama, $username, $role, $passwordHash, $id);
    } else {
        $stmt = mysqli_prepare($conn, "UPDATE users SET nama=?, username=?, role=? WHERE id=?");
        mysqli_stmt_bind_param($stmt, "sssi", $nama, $username, $role, $id);
    }

    mysqli_stmt_execute($stmt);

    setFlash('success', 'User berhasil diperbarui.');
    redirect('users.php');
}

$title = "Edit User";
include '../layouts/header.php';
?>

<div class="container-fluid">
    <div id="overlay" class="overlay"></div>

    <div class="row">
        <div class="col-lg-2 p-0">
            <?php include '../layouts/sidebar.php'; ?>
        </div>

        <div class="col-lg-10 p-0">
            <?php include '../layouts/navbar.php'; ?>

            <div class="content-wrap">
                <?php showFlash(); ?>

                <div class="card p-4">
                    <div class="mb-4">
                        <h4 class="section-title mb-1">Edit User</h4>
                        <p class="text-muted mb-0">Perbarui data akun pengguna.</p>
                    </div>

                    <form method="POST" class="row g-3">
                        <div class="col-md-6">
                            <label>Nama Lengkap</label>
                            <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($user['nama']); ?>" required>
                        </div>

                        <div class="col-md-6">
                            <label>Username</label>
                            <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($user['username']); ?>" required>
                        </div>

                        <div class="col-md-6">
                            <label>Password Baru <small class="text-muted">(opsional)</small></label>
                            <input type="password" name="password_baru" class="form-control" placeholder="Kosongkan jika tidak diubah">
                        </div>

                        <div class="col-md-6">
                            <label>Role</label>
                            <select name="role" class="form-select" required>
                                <option value="admin" <?= $user['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                <option value="client" <?= $user['role'] == 'client' ? 'selected' : ''; ?>>Client</option>
                            </select>
                        </div>

                        <div class="col-12 d-flex gap-2 mt-3">
                            <button type="submit" name="update" class="btn btn-warning">Update</button>
                            <a href="users.php" class="btn btn-outline-secondary">Kembali</a>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>
</div>

<?php include '../layouts/footer.php'; ?>