<?php
$page_title = "Manajemen Petugas";
include 'layout/header.php';
include 'layout/sidebar.php';
require_once '../config.php';

// Proteksi Khusus Administrator
if ($_SESSION['level'] != 'administrator') {
    echo "<script>alert('Akses Ditolak! Hanya Administrator.'); window.location.href='index.php';</script>";
    exit;
}

// Proses Tambah / Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $aksi = $_POST['aksi'];
    $nama = trim($_POST['nama_lengkap']);
    $nip = trim($_POST['nip']);
    $email = trim($_POST['email']);
    $jabatan = trim($_POST['jabatan']);
    $username = trim($_POST['username']);
    $level = $_POST['level'];

    if ($aksi == 'tambah') {
        $password = md5(trim($_POST['password']));
        $stmt = $pdo->prepare("INSERT INTO tbl_user (nama_lengkap, nip, email, jabatan, username, password, level) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$nama, $nip, $email, $jabatan, $username, $password, $level]);
        echo "<script>document.addEventListener('DOMContentLoaded', function() { Swal.fire({icon: 'success', title: 'Berhasil', text: 'User berhasil ditambahkan', timer: 2000, showConfirmButton: false, position: 'center'}); });</script>";
    } elseif ($aksi == 'edit') {
        $id = $_POST['id_user'];
        if (!empty($_POST['password'])) {
            $password = md5(trim($_POST['password']));
            $stmt = $pdo->prepare("UPDATE tbl_user SET nama_lengkap=?, nip=?, email=?, jabatan=?, username=?, password=?, level=? WHERE id=?");
            $stmt->execute([$nama, $nip, $email, $jabatan, $username, $password, $level, $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE tbl_user SET nama_lengkap=?, nip=?, email=?, jabatan=?, username=?, level=? WHERE id=?");
            $stmt->execute([$nama, $nip, $email, $jabatan, $username, $level, $id]);
        }
        echo "<script>document.addEventListener('DOMContentLoaded', function() { Swal.fire({icon: 'success', title: 'Berhasil', text: 'User berhasil diperbarui', timer: 2000, showConfirmButton: false, position: 'center'}); });</script>";
    } elseif ($aksi == 'hapus') {
        $id = $_POST['id_user'];
        if ($id != $_SESSION['user_id']) {
            $stmt = $pdo->prepare("DELETE FROM tbl_user WHERE id=?");
            $stmt->execute([$id]);
            echo "<script>document.addEventListener('DOMContentLoaded', function() { Swal.fire({icon: 'success', title: 'Berhasil', text: 'User berhasil dihapus', timer: 2000, showConfirmButton: false, position: 'center'}); });</script>";
        } else {
            echo "<script>document.addEventListener('DOMContentLoaded', function() { Swal.fire({icon: 'error', title: 'Gagal', text: 'Tidak dapat menghapus akun sendiri!', position: 'center'}); });</script>";
        }
    }
}

$users = $pdo->query("SELECT * FROM tbl_user ORDER BY nama_lengkap ASC")->fetchAll();
?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <h1 class="m-0">Manajemen Petugas & Administrator</h1>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <button class="btn btn-primary" data-toggle="modal" data-target="#modalTambah"><i class="fas fa-plus"></i> Tambah User Baru</button>
                </div>
                <div class="card-body">
                    <table class="table table-bordered table-hover datatable align-middle">
                        <thead class="bg-light">
                            <tr>
                                <th>No</th>
                                <th>Nama Lengkap</th>
                                <th>NIP</th>
                                <th>Email</th>
                                <th>Jabatan</th>
                                <th>Username</th>
                                <th>Level</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no=1; foreach($users as $u): ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= htmlspecialchars($u->nama_lengkap) ?></td>
                                <td><?= htmlspecialchars($u->nip) ?></td>
                                <td><?= htmlspecialchars($u->email) ?></td>
                                <td><?= htmlspecialchars($u->jabatan) ?></td>
                                <td><?= htmlspecialchars($u->username) ?></td>
                                <td>
                                    <?php if($u->level == 'administrator'): ?>
                                        <span class="badge badge-danger">Administrator</span>
                                    <?php else: ?>
                                        <span class="badge badge-primary">Operator</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick='editUser(<?= json_encode($u) ?>)'><i class="fas fa-edit"></i> Edit</button>
                                    <?php if($u->id != $_SESSION['user_id']): ?>
                                    <form action="" method="POST" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus user ini?');">
                                        <input type="hidden" name="aksi" value="hapus">
                                        <input type="hidden" name="id_user" value="<?= $u->id ?>">
                                        <button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i> Hapus</button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Modal Tambah/Edit -->
<div class="modal fade" id="modalTambah" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="manajemen_user.php" method="POST">
                <input type="hidden" name="aksi" id="f_aksi" value="tambah">
                <input type="hidden" name="id_user" id="f_id">
                
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="m_title">Tambah User</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama_lengkap" id="f_nama" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-6 form-group">
                            <label>NIP</label>
                            <input type="text" name="nip" id="f_nip" class="form-control">
                        </div>
                        <div class="col-6 form-group">
                            <label>Email</label>
                            <input type="email" name="email" id="f_email" class="form-control" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Jabatan</label>
                        <input type="text" name="jabatan" id="f_jabatan" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" name="username" id="f_username" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" name="password" id="f_password" class="form-control">
                        <small class="text-muted" id="f_pass_help">Biarkan kosong jika tidak ingin mengubah password (saat Edit).</small>
                    </div>
                    <div class="form-group">
                        <label>Level Akses</label>
                        <select name="level" id="f_level" class="form-control" required>
                            <option value="operator">Operator (Biasa)</option>
                            <option value="administrator">Administrator (Penuh)</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan User</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editUser(data) {
    document.getElementById('m_title').innerText = 'Edit User';
    document.getElementById('f_aksi').value = 'edit';
    document.getElementById('f_id').value = data.id;
    document.getElementById('f_nama').value = data.nama_lengkap;
    document.getElementById('f_nip').value = data.nip;
    document.getElementById('f_email').value = data.email;
    document.getElementById('f_jabatan').value = data.jabatan;
    document.getElementById('f_username').value = data.username;
    document.getElementById('f_level').value = data.level;
    document.getElementById('f_password').required = false; // tidak wajib isi kalau edit
    
    $('#modalTambah').modal('show');
}

// Reset form when modal closed
$('#modalTambah').on('hidden.bs.modal', function () {
    document.getElementById('m_title').innerText = 'Tambah User';
    document.getElementById('f_aksi').value = 'tambah';
    document.getElementById('f_id').value = '';
    document.getElementById('f_password').required = true;
    $(this).find('form')[0].reset();
});
</script>

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