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

// Saat tombol simpan ditekan
if(isset($_POST['simpan'])) {
    $username = $_POST['username'];
    $role = $_POST['role'];
    $id_guru = $_POST['id_guru'];

    // Ambil nama dari master_guru berdasarkan id_guru yang dipilih
    $q_nama = mysqli_query($koneksi, "SELECT nama FROM master_guru WHERE id_guru = '$id_guru'");
    $d_nama = mysqli_fetch_array($q_nama);
    $nama_lengkap = $d_nama['nama']; // Nama didapat otomatis

    // Simpan ke database
    $query = "INSERT INTO users (username, role, id_guru, nama_lengkap) 
              VALUES ('$username', '$role', '$id_guru', '$nama_lengkap')";
    mysqli_query($koneksi, $query);
}


include 'layout_header.php';
?>

<div class="container-fluid p-4">
    <h3>Tambah 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" required>
        </div>
        <div class="mb-3">
            <label>Password</label>
            <input type="password" name="password" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Role</label>
            <select name="role" class="form-select" id="roleSelect" onchange="toggleGuru(this.value)">
                <option value="admin">Admin</option>
                <option value="guru">Guru</option>
            </select>
        </div>
        <div class="mb-3" id="guruField" style="display: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)) {
                    echo "<option value='{$g['id_guru']}'>{$g['nama']}</option>";
                }
                ?>
            </select>
        </div>
        <button type="submit" name="simpan" class="btn btn-primary">Simpan</button>
    </form>
</div>

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