
<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

requireRole('super_admin');

$db = getDB();
$error = '';
$success = '';

$id = $_GET['id'] ?? 0;
if (!$id) {
    header('Location: users.php');
    exit;
}

// Ambil data user
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: users.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $role = $_POST['role'] ?? '';
    
    if (empty($username)) {
        $error = 'Username harus diisi!';
    } elseif (strlen($username) < 4) {
        $error = 'Username minimal 4 karakter!';
    } elseif (!empty($password) && strlen($password) < 6) {
        $error = 'Password minimal 6 karakter!';
    } elseif (!empty($password) && $password !== $confirm_password) {
        $error = 'Password tidak cocok!';
    } elseif (!in_array($role, ['super_admin', 'admin', 'user'])) {
        $error = 'Role tidak valid!';
    } else {
        try {
            // Cek username sudah ada atau belum (kecuali username sendiri)
            $stmt = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $id]);
            if ($stmt->fetch()) {
                $error = 'Username sudah digunakan!';
            } else {
                if (!empty($password)) {
                    // Update dengan password baru
                    $stmt = $db->prepare("UPDATE users SET username = ?, password = ?, role = ? WHERE id = ?");
                    $stmt->execute([
                        $username,
                        password_hash($password, PASSWORD_DEFAULT),
                        $role,
                        $id
                    ]);
                } else {
                    // Update tanpa password
                    $stmt = $db->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
                    $stmt->execute([
                        $username,
                        $role,
                        $id
                    ]);
                }
                
                $success = 'User berhasil diupdate!';
                
                // Redirect setelah 1 detik
                
            }
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan saat mengupdate data!';
        }
    }
}
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Edit User</h1>
                </div>
            </div>
        </div>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Form Edit User</h3>
                </div>
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="form-group">
                            <label for="username">Username</label>
                            <input type="text" class="form-control" id="username" name="username" 
                                   value="<?php echo htmlspecialchars($user['username']); ?>" required>
                        </div>

                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" class="form-control" id="password" name="password">
                            <small class="form-text text-muted">
                                Kosongkan jika tidak ingin mengubah password. Minimal 6 karakter jika diisi.
                            </small>
                        </div>

                        <div class="form-group">
                            <label for="confirm_password">Konfirmasi Password</label>
                            <input type="password" class="form-control" id="confirm_password" 
                                   name="confirm_password">
                        </div>

                        <div class="form-group">
                            <label for="role">Role</label>
                            <select class="form-control" id="role" name="role" required>
                                <option value="">Pilih Role</option>
                                <option value="user" <?php echo ($user['role'] === 'user') ? 'selected' : ''; ?>>
                                    User
                                </option>
                                <option value="admin" <?php echo ($user['role'] === 'admin') ? 'selected' : ''; ?>>
                                    Admin
                                </option>
                                <option value="super_admin" <?php echo ($user['role'] === 'super_admin') ? 'selected' : ''; ?>>
                                    Super Admin
                                </option>
                            </select>
                        </div>

                        <button type="submit" class="btn btn-primary">Update</button>
                        <a href="users.php" class="btn btn-secondary">Kembali</a>
                    </form>
                </div>
            </div>
        </div>
    </section>
</div>

<?php require_once '../includes/footer.php'; ?>