<?php
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
//cekAdmin();

$id = $_GET['id']; // Mengambil ID dari URL

// Proses update data
if (isset($_POST['update'])) {
    $username = $_POST['username'];
    $role = $_POST['role'];
    $id_guru = ($_POST['role'] == 'guru') ? $_POST['id_guru'] : "NULL";
    
    // Jika password diisi, maka update password
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $sql = "UPDATE users SET username='$username', password='$password', role='$role', id_guru=$id_guru WHERE id_user='$id'";
    } else {
        $sql = "UPDATE users SET username='$username', role='$role', id_guru=$id_guru WHERE id_user='$id'";
    }

    if (mysqli_query($koneksi, $sql)) {
        echo "<script>alert('Data berhasil diupdate!'); window.location='user_management.php';</script>";
    } else {
        echo "Error: " . mysqli_error($koneksi);
    }
}

// Ambil data lama untuk ditampilkan di form
$data = mysqli_fetch_array(mysqli_query($koneksi, "SELECT * FROM users WHERE id_user='$id'"));
include 'layout_header.php';
?>

<div class="container-fluid p-4">
    <h3>Edit User</h3>
    <form method="POST" class="card p-4 col-md-6">
        <div class="mb-3">
            <label>Username</label>
            <input type="text" name="username" class="form-control" value="<?= $data['username'] ?>" required>
        </div>
        <div class="mb-3">
            <label>Password Baru (Kosongkan jika tidak ingin diganti)</label>
            <input type="password" name="password" class="form-control">
        </div>
        <div class="mb-3">
            <label>Role</label>
            <select name="role" class="form-select" id="roleSelect" onchange="toggleGuru(this.value)">
                <option value="admin" <?= ($data['role'] == 'admin') ? 'selected' : '' ?>>Admin</option>
                <option value="guru" <?= ($data['role'] == 'guru') ? 'selected' : '' ?>>Guru</option>
            </select>
        </div>
        <div class="mb-3" id="guruField" style="display:<?= ($data['role'] == 'guru') ? 'block' : 'none' ?>;">
            <label>Pilih Data Guru</label>
            <select name="id_guru" class="form-select">
                <?php
                $q = mysqli_query($koneksi, "SELECT * FROM master_guru");
                while($g = mysqli_fetch_array($q)) {
                    $selected = ($g['id_guru'] == $data['id_guru']) ? 'selected' : '';
                    echo "<option value='{$g['id_guru']}' $selected>{$g['nama']}</option>";
                }
                ?>
            </select>
        </div>
        <button type="submit" name="update" class="btn btn-success">Update User</button>
        <a href="user_management.php" class="btn btn-secondary">Kembali</a>
    </form>
</div>

<script>
function toggleGuru(val) {
    document.getElementById('guruField').style.display = (val == 'guru') ? 'block' : 'none';
}
</script>