<div class="container mt-4">
    <div class="card modern-card shadow-sm border-0 rounded-4">
        <div class="card-body p-4">

            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Manajemen Pengguna</h5>

                <button class="btn btn-warning btn-add">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Pengguna
                </button>
            </div>

            <div class="table-responsive">
                <table id="tableUsers" class="table modern-table align-middle w-100">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Username</th>
                            <th>Nama</th>
                            <th>Role</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

        </div>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="modalUser">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4">

            <div class="modal-header bg-warning text-white rounded-top-4">
                <h5 class="modal-title">Tambah Pengguna</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">

                <input type="hidden" id="inputId">

                <div class="mb-3">
                    <label class="fw-semibold">Username</label>
                    <input type="text" class="form-control" id="inputUsername">
                </div>

                <div class="mb-3">
                    <label class="fw-semibold">Nama</label>
                    <input type="text" class="form-control" id="inputNama">
                </div>

                <div class="mb-3">
                    <label class="fw-semibold">Role</label>
                    <select class="form-control" id="inputRole">
                        <option value="">-- Pilih Role --</option>
                    </select>
                </div>

                <div class="password-group">
                    <div class="mb-3">
                        <label class="fw-semibold">Password</label>
                        <input type="password" class="form-control" id="inputPassword">
                    </div>
                </div>

            </div>

            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button class="btn btn-warning" id="btnSimpan">Simpan</button>
            </div>

        </div>
    </div>
</div>
<script>
$(document).ready(function () {

    let modal = new bootstrap.Modal(document.getElementById('modalUser'));

    // ======================
    // DATATABLE
    // ======================
    let table = $('#tableUsers').DataTable({
        processing: true,
        serverSide: true,
        responsive: true,
        ajax: {
            url: "<?= base_url('users/get_data'); ?>",
            type: "POST"
        },
        columns: [
            { data: 0 },
            { data: 1 },
            { data: 2 },
            { data: 3 },
            { data: 4, orderable: false }
        ]
    });

    // ======================
    // OPEN ADD MODAL
    // ======================
    $('.btn-add').on('click', function () {

        resetModal();

        $('#modalUser .modal-title').text('Tambah Pengguna');
        $('#btnSimpan').data('action', 'add');

        $('.password-group').show();

        modal.show();
    });

    // ======================
    // SAVE
    // ======================
    $('#btnSimpan').on('click', function () {

        let action = $(this).data('action');

        let formData = {
            id: $('#inputId').val(),
            username: $('#inputUsername').val(),
            nama: $('#inputNama').val(),
            role_id: $('#inputRole').val(),
            password: $('#inputPassword').val()
        };

        let url = (action === 'add')
            ? "<?= base_url('users/store'); ?>"
            : "<?= base_url('users/update'); ?>";

        $.ajax({
            url: url,
            type: "POST",
            data: formData,
            dataType: "json",
            success: function (res) {

                if (res.status) {
                    modal.hide();
                    table.ajax.reload(null, false);
                    Swal.fire('Sukses', res.message, 'success');
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }

            },
            error: function () {
                Swal.fire('Error', 'Server bermasalah', 'error');
            }
        });

    });

    // ======================
    // EDIT
    // ======================
    $('#tableUsers').on('click', '.btn-edit', function () {

        let id = $(this).data('id');

        $.ajax({
            url: "<?= base_url('users/edit'); ?>/" + id,
            type: "GET",
            dataType: "json",
            success: function (res) {

                if (res.status) {

                    resetModal();

                    $('#modalUser .modal-title').text('Edit Pengguna');
                    $('#btnSimpan').data('action', 'edit');

                    $('#inputId').val(res.data.id);
                    $('#inputUsername').val(res.data.username);
                    $('#inputNama').val(res.data.nama);

                    loadRole(res.data.role_id);

                    $('.password-group').hide();
                    $('#inputPassword').val('');

                    modal.show();

                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }

            },
            error: function () {
                Swal.fire('Error', 'Gagal load data edit', 'error');
            }
        });

    });

    // ======================
    // DELETE
    // ======================
    $('#tableUsers').on('click', '.btn-delete', function () {

        let id = $(this).data('id');

        Swal.fire({
            title: 'Hapus user?',
            text: "Data tidak bisa dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ya, hapus!'
        }).then((result) => {

            if (result.isConfirmed) {

                $.ajax({
                    url: "<?= base_url('users/delete'); ?>/" + id,
                    type: "POST",
                    dataType: "json",
                    success: function (res) {

                        if (res.status) {
                            table.ajax.reload(null, false);
                            Swal.fire('Terhapus', res.message, 'success');
                        } else {
                            Swal.fire('Gagal', res.message, 'error');
                        }

                    },
                    error: function () {
                        Swal.fire('Error', 'Server error', 'error');
                    }
                });

            }

        });

    });

    // ======================
    // LOAD ROLE (FIXED)
    // ======================
    function loadRole(selected = '') {

        $.ajax({
            url: "<?= base_url('users/get_role'); ?>",
            type: "GET",
            dataType: "json",
            success: function (res) {

                let select = $('#inputRole');
                select.empty();
                select.append('<option value="">-- Pilih Role --</option>');

                if (Array.isArray(res)) {
                    res.forEach(r => {
                        let selectedAttr = (r.id == selected) ? 'selected' : '';
                        select.append(`<option value="${r.id}" ${selectedAttr}>${r.nama_role}</option>`);
                    });
                }

            },
            error: function () {
                Swal.fire('Error', 'Gagal load role', 'error');
            }
        });

    }

    // ======================
    // RESET MODAL
    // ======================
    function resetModal() {
        $('#inputId').val('');
        $('#inputUsername').val('');
        $('#inputNama').val('');
        $('#inputPassword').val('');
        $('#inputRole').val('');

        loadRole();
    }

});
</script>