<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/sidebar.php';

// Cek login & akses admin
cek_login();
if ($_SESSION['role'] != 'admin') {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/users/index.php?error=" . urlencode("ID user tidak valid!"));
    exit();
}
$id = (int)$_GET['id'];

// Ambil data
$query = "SELECT * FROM users WHERE id = $id";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/users/index.php?error=" . urlencode("Data user tidak ditemukan!"));
    exit();
}
$user = mysqli_fetch_assoc($result);

$error = '';
$success = '';

// Proses edit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = sanitize($_POST['username']);
    $nama = sanitize($_POST['nama']);
    $role = sanitize($_POST['role']);
    $change_password = isset($_POST['change_password']) ? true : false;
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($username) || empty($nama) || empty($role)) {
        $error = "Username, nama, dan role harus diisi!";
    } elseif ($change_password && (empty($password) || empty($confirm_password))) {
        $error = "Password baru dan konfirmasinya harus diisi!";
    } elseif ($change_password && $password != $confirm_password) {
        $error = "Password dan konfirmasi password tidak cocok!";
    } elseif ($change_password && strlen($password) < 6) {
        $error = "Password minimal 6 karakter!";
    } else {
        $check_query = "SELECT * FROM users WHERE username = '$username' AND id != $id";
        $check_result = mysqli_query($conn, $check_query);
        
        if (mysqli_num_rows($check_result) > 0) {
            $error = "Username sudah digunakan oleh user lain!";
        } else {
            $update_query = "UPDATE users SET username = '$username', nama = '$nama', role = '$role', updated_at = NOW()";
            if ($change_password) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $update_query = "UPDATE users SET username = '$username', password = '$hashed_password', nama = '$nama', role = '$role', updated_at = NOW()";
            }
            $update_query .= " WHERE id = $id";
            
            if (mysqli_query($conn, $update_query)) {
                $success = "Data user berhasil diperbarui!";
                $result = mysqli_query($conn, $query); // Refresh data
                $user = mysqli_fetch_assoc($result);
            } else {
                $error = "Gagal memperbarui data user: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h2 class="text-3xl font-bold text-white">Edit User</h2>
            <p class="text-slate-400">Perbarui informasi akun pengguna.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/users/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">Kembali</a>
    </div>
    
    <?php if (!empty($error)): ?>
    <div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert"><i class="fas fa-exclamation-circle"></i><span><?php echo htmlspecialchars($error); ?></span></div>
    <?php endif; ?>
    <?php if (!empty($success)): ?>
    <div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert"><i class="fas fa-check-circle"></i><span><?php echo htmlspecialchars($success); ?></span></div>
    <?php endif; ?>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <form method="POST" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Kolom Kiri -->
                <div class="space-y-4">
                    <div>
                        <label for="username" class="block text-slate-400 text-sm font-medium mb-2">Username <span class="text-red-400">*</span></label>
                        <input type="text" name="username" id="username" value="<?php echo htmlspecialchars($user['username']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                    </div>
                    <div>
                        <label for="nama" class="block text-slate-400 text-sm font-medium mb-2">Nama Lengkap <span class="text-red-400">*</span></label>
                        <input type="text" name="nama" id="nama" value="<?php echo htmlspecialchars($user['nama']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                    </div>
                    <div>
                        <label for="role" class="block text-slate-400 text-sm font-medium mb-2">Role <span class="text-red-400">*</span></label>
                        <select name="role" id="role" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                            <option value="admin" <?php echo ($user['role'] == 'admin') ? 'selected' : ''; ?>>Admin</option>
                            <option value="hrd" <?php echo ($user['role'] == 'hrd') ? 'selected' : ''; ?>>HRD</option>
                            <option value="karyawan" <?php echo ($user['role'] == 'karyawan') ? 'selected' : ''; ?> disabled>Karyawan (Dikelola dari modul Karyawan)</option>
                        </select>
                    </div>
                </div>
                
                <!-- Kolom Kanan -->
                <div class="space-y-4">
                    <div class="flex items-center">
                        <input type="checkbox" name="change_password" id="change_password" class="h-4 w-4 rounded border-slate-500 bg-slate-700 text-sky-600 focus:ring-sky-500">
                        <label for="change_password" class="ml-2 block text-sm text-slate-300">Ubah Password</label>
                    </div>
                    <div id="password_fields" class="hidden space-y-4 pt-4 border-t border-slate-700/50">
                        <div>
                            <label for="password" class="block text-slate-400 text-sm font-medium mb-2">Password Baru</label>
                            <input type="password" name="password" id="password" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                            <p class="text-slate-500 text-xs mt-1">Minimal 6 karakter.</p>
                        </div>
                        <div>
                            <label for="confirm_password" class="block text-slate-400 text-sm font-medium mb-2">Konfirmasi Password Baru</label>
                            <input type="password" name="confirm_password" id="confirm_password" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-8 border-t border-slate-700/50 pt-6 flex justify-end">
                <button type="submit" class="bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center gap-2">
                    <i class="fas fa-save"></i> Simpan Perubahan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    document.getElementById('change_password').addEventListener('change', function() {
        const passwordFields = document.getElementById('password_fields');
        if (this.checked) {
            passwordFields.classList.remove('hidden');
        } else {
            passwordFields.classList.add('hidden');
        }
    });
</script>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/footer.php';
?>
