<?php
// admin/pengguna.php
include_once 'init.php';

$page_title = 'Manajemen Pengguna';
$page_icon = 'bi-people-fill';

// 1. PROSES TAMBAH / UPDATE
if (isset($_POST['simpan_user'])) {
    $nama = $_POST['nama_lengkap'];
    $user = $_POST['username'];
    $pass = $_POST['password']; 
    $id = $_POST['id'] ?? '';

    try {
        if (!empty($id)) {
            // --- MODE UPDATE (Role tidak ikut diupdate di sini) ---
            if (!empty($pass)) {
                $pass_hash = password_hash($pass, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET nama_lengkap=?, username=?, password=? WHERE id=?");
                $stmt->execute([$nama, $user, $pass_hash, $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET nama_lengkap=?, username=? WHERE id=?");
                $stmt->execute([$nama, $user, $id]);
            }
            $_SESSION['message'] = "Data pengguna berhasil diperbarui.";
        } else {
            // --- MODE TAMBAH BARU ---
            $role = $_POST['role'];
            if ($role === 'siswa') {
                $_SESSION['error'] = "Role siswa hanya bisa ditambah melalui menu Nasabah.";
            } else {
                $cek = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                $cek->execute([$user]);
                if ($cek->fetchColumn() > 0) {
                    $_SESSION['error'] = "Username '$user' sudah digunakan!";
                } else {
                    $pass_hash = password_hash($pass, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO users (nama_lengkap, username, password, role) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$nama, $user, $pass_hash, $role]);
                    $_SESSION['message'] = "Pengguna baru berhasil ditambahkan.";
                }
            }
        }
    } catch (PDOException $e) {
        $_SESSION['error'] = "Terjadi kesalahan: " . $e->getMessage();
    }
    header("Location: pengguna.php"); exit();
}

// 2. PROSES HAPUS
if (isset($_POST['delete_id'])) {
    $id_hapus = $_POST['delete_id'];
    $stmt_check = $pdo->prepare("SELECT role FROM users WHERE id = ?");
    $stmt_check->execute([$id_hapus]);
    $role_del = $stmt_check->fetchColumn();

    if ($role_del === 'siswa') {
        $_SESSION['error'] = "User siswa hanya bisa dihapus melalui menu Nasabah.";
    } elseif ($id_hapus == $_SESSION['user_id']) {
        $_SESSION['error'] = "Anda tidak dapat menghapus akun sendiri!";
    } else {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id_hapus]);
        $_SESSION['message'] = "Pengguna berhasil dihapus.";
    }
    header("Location: pengguna.php"); exit();
}

include 'header.php';
$users = $pdo->query("SELECT * FROM users ORDER BY role ASC, nama_lengkap ASC")->fetchAll();
?>

<div class="content-card shadow-sm p-4 bg-white rounded">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h5 class="mb-0 fw-bold text-primary">Daftar Pengguna Sistem</h5>
            <small class="text-muted">Kelola akun Admin, Operator, & Akun Nasabah</small>
        </div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalUser" onclick="resetForm()">
            <i class="bi bi-person-plus me-1"></i> Tambah Pengguna
        </button>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-success alert-dismissible fade show"><?= $_SESSION['message']; unset($_SESSION['message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="table table-hover align-middle border">
            <thead class="table-light">
                <tr class="small text-uppercase">
                    <th width="5%">No</th>
                    <th>Nama Lengkap</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody class="small">
                <?php $no=1; foreach ($users as $u): ?>
                <tr>
                    <td><?= $no++ ?></td>
                    <td><strong><?= htmlspecialchars($u['nama_lengkap']) ?></strong></td>
                    <td><code><?= htmlspecialchars($u['username']) ?></code></td>
                    <td>
                        <span class="badge rounded-pill bg-<?= ($u['role']=='admin'?'danger':($u['role']=='operator'?'primary':'success')) ?>">
                            <?= strtoupper($u['role']) ?>
                        </span>
                    </td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-warning btn-edit" 
                                    data-bs-toggle="modal" data-bs-target="#modalUser"
                                    data-id="<?= $u['id'] ?>"
                                    data-nama="<?= $u['nama_lengkap'] ?>"
                                    data-user="<?= $u['username'] ?>"><i class="bi bi-pencil"></i></button>
                            
                            <?php if ($u['role'] !== 'siswa' && $u['id'] != $_SESSION['user_id']): ?>
                                <button class="btn btn-outline-danger btn-delete" data-id="<?= $u['id'] ?>" data-nama="<?= $u['nama_lengkap'] ?>"><i class="bi bi-trash"></i></button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalUser" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="modalTitle">Input Pengguna</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="id" id="user_id">
                <div class="mb-3"><label class="form-label">Nama Lengkap</label><input type="text" name="nama_lengkap" id="nama_lengkap" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Username</label><input type="text" name="username" id="username" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Password</label><input type="password" name="password" id="password" class="form-control" placeholder="Kosongkan jika tidak ganti"></div>
                
                <div class="mb-3" id="role_wrapper">
                    <label class="form-label">Role</label>
                    <select name="role" id="role" class="form-select">
                        <option value="admin">Admin</option>
                        <option value="operator">Operator</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Tutup</button>
                <button type="submit" name="simpan_user" class="btn btn-primary btn-sm">Simpan Data</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <form class="modal-content" method="POST">
            <div class="modal-body text-center py-4">
                <input type="hidden" name="delete_id" id="delete_id">
                <i class="bi bi-exclamation-octagon text-danger display-4"></i>
                <h5 class="mt-3">Hapus akun <b id="nama_del"></b>?</h5>
                <div class="d-flex justify-content-center gap-2 mt-4">
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-danger btn-sm">Ya, Hapus</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('user_id').value = '';
    document.getElementById('nama_lengkap').value = '';
    document.getElementById('username').value = '';
    document.getElementById('password').required = true;
    document.getElementById('modalTitle').innerText = 'Tambah Pengguna Baru';
    // Tampilkan kembali form role saat tambah data
    document.getElementById('role_wrapper').style.display = 'block';
    document.getElementById('role').disabled = false;
}

document.addEventListener('DOMContentLoaded', function() {
    const editBtns = document.querySelectorAll('.btn-edit');
    editBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            document.getElementById('modalTitle').innerText = 'Edit Data Pengguna';
            document.getElementById('user_id').value = this.dataset.id;
            document.getElementById('nama_lengkap').value = this.dataset.nama;
            document.getElementById('username').value = this.dataset.user;
            document.getElementById('password').required = false;
            
            // Sembunyikan form role saat edit
            document.getElementById('role_wrapper').style.display = 'none';
            document.getElementById('role').disabled = true; // Nonaktifkan agar tidak terkirim via POST
        });
    });

    const delBtns = document.querySelectorAll('.btn-delete');
    const delModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    delBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            document.getElementById('delete_id').value = this.dataset.id;
            document.getElementById('nama_del').textContent = this.dataset.nama;
            delModal.show();
        });
    });
});
</script>

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