<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<nav class="page-breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><?= $Breadcumb ?></li>
        <li class="breadcrumb-item active" aria-current="page">Data <?= $Breadcumb ?></li>
    </ol>
</nav>

<div class="row">
    <div class="col-md-12 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">

                <div class="col-md-2 grid-margin stretch-card">

                    <?php if (session()->get('role') === 'admin') : ?>
                        <a class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#tambahModal">Tambah Data</a>
                    <?php endif; ?>
                    <!-- <a class="btn btn-success" data-bs-toggle="modal" data-bs-target="#importModal"> Import Data</a> -->
                </div>

                <h6 class="card-title">Data <?= $Breadcumb ?></h6>

                <div class="table-responsive">
                    <table id="dataTableExample" class="table table-bordered table-hover table no-wrap">
                        <thead class="table-info text-dark">
                            <tr>
                                <th style="width: 5%;">#</th>
                                <th>NIP</th>
                                <th>Nama</th>
                                <th>Telepon</th>
                                <th>Email</th>
                                <th>Jabatan</th>
                                <th>Unit Kerja</th>
                                <th>Atasan</th>
                                <th>Status Pegawai</th>
                                <th>Role</th>
                                <th>Status</th>
                                <th>Opsi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no = 1; ?>
                            <?php if (!empty($User)): ?>
                                <?php foreach ($User as $row): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= $row['nip'] ?></td>
                                        <td><?= $row['nama'] ?></td>
                                        <td><?= $row['nohape'] ?> </td>
                                        <td><?= $row['email'] ?> </td>
                                        <td><?= $row['nama_jabatan'] ?> </td>
                                        <td><?= $row['nama_unit'] ?> </td>
                                        <td><?= $row['nama_atasan'] ?? '-' ?></td>
                                        <td><?= $row['status_kepegawaian'] ?> </td>
                                        <td>
                                            <?php
                                            $roles = [
                                                'user' => 'Pegawai',
                                                'supervisor' => 'Atasan Langsung',
                                                'manager' => 'Ketua',
                                                'admin' => 'Admin Kepegawaian'
                                            ];
                                            echo $roles[$row['role']] ?? $row['role'];
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($row['status'] == 'aktif'): ?>
                                                <span class="badge bg-success"><?= $row['status'] ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-danger"><?= $row['status'] ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>

                                            <button type="button" class="btn btn-warning btn-sm" title="Edit Data" onclick="updateData('<?= $row['id_user'] ?>')">
                                                <i class="icon-md" data-feather="edit"></i>
                                            </button>

                                            <?php if ($row['id_user'] != $session_id_user): ?>
                                                <button type="button" class="btn btn-danger btn-sm" title="Hapus Data" onclick="deleteData('<?= $row['id_user'] ?>')">
                                                    <i class="icon-md" data-feather="trash-2"></i>
                                                </button>



                                                <?php if ($row['status'] == 'aktif'): ?>
                                                    <!-- Tombol Nonaktif -->
                                                    <button type="button" class="btn btn-warning btn-sm"
                                                        title="Nonaktifkan user"
                                                        onclick="changeStatus('<?= $row['id_user'] ?>', 'nonaktif')">
                                                        Nonaktif
                                                    </button>
                                                <?php else: ?>
                                                    <!-- Tombol Aktif -->
                                                    <button type="button" class="btn btn-success btn-sm"
                                                        title="Aktifkan user"
                                                        onclick="changeStatus('<?= $row['id_user'] ?>', 'aktif')">
                                                        Aktif
                                                    </button>
                                                <?php endif; ?>

                                            <?php else: ?>
                                                <!-- Tombol View Profil (Hanya Muncul Jika id_user == session_id_user) -->
                                                <a href="<?= base_url('profil/index/' . $row['id_user']) ?>" class="btn btn-info btn-sm" title="Lihat Profil">
                                                    View Profil
                                                </a>
                                                <!-- Tombol Tambah Tanda Tangan -->
                                                <button type="button" class="btn btn-success btn-sm" title="Tambah Tanda Tangan" onclick="openTTDModal('<?= $row['id_user'] ?>')">
                                                    <i class="icon" data-feather="edit-3"></i> Tanda Tangan
                                                </button>
                                                <button type="button" class="btn btn-secondary btn-sm" onclick="lihatTTD('<?= $row['id_user'] ?>')">
                                                    <i class="bi bi-eye"></i> Lihat TTD
                                                </button>
                                            <?php endif ?>

                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="12" class="text-center" style="background-color: #f9f9f9; color: #888; font-style: italic; padding: 20px;">
                                        <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i>
                                        <br>
                                        <span style="font-size: 16px; font-weight: bold;">Tidak ada data yang tersedia.</span>
                                        <br>
                                        <span style="font-size: 14px;">Silakan tambahkan data baru untuk mengisi tabel ini.</span>
                                    </td>
                                </tr>
                            <?php endif; ?>

                        </tbody>
                    </table>
                </div>
            </div>

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

<!-- Modal Tambah Data -->
<div class="modal fade" id="tambahModal" tabindex="-1" role="dialog" aria-labelledby="tambahModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tambahModalLabel">Tambah Data user</h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
            </div>
            <div class="modal-body">
                <form id="formTambahData">

                    <div class="mb-3">
                        <label for="nama">Nama Lengkap</label>
                        <input type="text" class="form-control" id="nama" name="nama" required>
                    </div>

                    <div class="mb-3">
                        <label for="nip">NIP</label>
                        <input type="text" class="form-control" id="nip" name="nip" required>
                    </div>

                    <div class="mb-3">
                        <label for="id_jabatan">Jabatan</label>
                        <select class="form-control" id="id_jabatan" name="id_jabatan" required>
                            <option value="" disabled selected>Pilih Jabatan</option>
                            <?php foreach ($jabatan as $row): ?>
                                <option value="<?= $row['id_jabatan'] ?>"><?= $row['nama_jabatan'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="id_unit">Unit Kerja</label>
                        <select class="form-control" id="id_unit" name="id_unit" required>
                            <option value="" disabled selected>Pilih Unit Kerja</option>
                            <?php foreach ($unitkerja as $row): ?>
                                <option value="<?= $row['id_unit'] ?>"><?= $row['nama_unit'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="id_atasan">Atasan</label>
                        <select class="form-control" name="id_atasan" id="id_atasan">
                            <option value="" selected disabled>Pilih Atasan</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="status_kepegawaian">Status Kepegawaian</label>
                        <select class="form-control" id="status_kepegawaian" name="status_kepegawaian" required>
                            <option value="" disabled selected>Pilih Status</option>
                            <option value="ASN">ASN</option>
                            <option value="Non-ASN">Non-ASN</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="nohape">Nomor HP</label>
                        <input type="text" class="form-control" id="nohape" name="nohape" required>
                    </div>

                    <div class="mb-3">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>

                    <div class="mb-3">
                        <label for="role">Role (Hak Akses)</label>
                        <select class="form-control" id="role" name="role" required>
                            <option value="" disabled selected>Pilih Role</option>
                            <option value="user">Pegawai</option>
                            <option value="supervisor">Atasan Langsung</option>
                            <option value="manager">Ketua</option>
                            <option value="admin">Admin Kepegawaian</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="status">Status Sistem</label>
                        <select class="form-control" id="status" name="status" required>
                            <option value="" disabled selected>Pilih Status</option>
                            <option value="aktif">Aktif</option>
                            <option value="nonaktif">Nonaktif</option>
                        </select>
                    </div>


                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Tambah</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Edit Data -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editModalLabel">Edit Data user</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
            </div>
            <div class="modal-body">
                <form id="formEditData">
                    <input type="hidden" id="edit_id_user" name="id_user">
                    <div class="mb-3">
                        <label for="edit_nama">Nama Lengkap</label>
                        <input type="text" class="form-control" id="edit_nama" name="nama" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_nip">NIP</label>
                        <input type="text" class="form-control" id="edit_nip" name="nip" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_id_jabatan">Jabatan</label>
                        <select class="form-control" id="edit_id_jabatan" name="id_jabatan" required>
                            <option value="" disabled selected>Pilih Jabatan</option>
                            <?php foreach ($jabatan as $row): ?>
                                <option value="<?= $row['id_jabatan'] ?>"><?= $row['nama_jabatan'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="edit_id_unit">Unit Kerja</label>
                        <select class="form-control" id="edit_id_unit" name="id_unit" required>
                            <option value="" disabled selected>Pilih Unit Kerja</option>
                            <?php foreach ($unitkerja as $row): ?>
                                <option value="<?= $row['id_unit'] ?>"><?= $row['nama_unit'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="edit_id_atasan">Atasan</label>
                        <select class="form-control" name="id_atasan" id="edit_id_atasan">
                            <option value="" selected disabled>Pilih Atasan</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="edit_status_kepegawaian">Status Kepegawaian</label>
                        <select class="form-control" id="edit_status_kepegawaian" name="status_kepegawaian" required>
                            <option value="" disabled selected>Pilih Status</option>
                            <option value="ASN">ASN</option>
                            <option value="Non-ASN">Non-ASN</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="edit_nohape">Nomor HP</label>
                        <input type="text" class="form-control" id="edit_nohape" name="nohape" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_email">Email</label>
                        <input type="email" class="form-control" id="edit_email" name="email" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_role">Role (Hak Akses)</label>
                        <select class="form-control" id="edit_role" name="role" required>
                            <option value="" disabled selected>Pilih Role</option>
                            <option value="user">Pegawai</option>
                            <option value="supervisor">Atasan Langsung</option>
                            <option value="manager">Ketua</option>
                            <option value="admin">Admin Kepegawaian</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="edit_status">Status Sistem</label>
                        <select class="form-control" id="edit_status" name="status" required>
                            <option value="" disabled selected>Pilih Status</option>
                            <option value="aktif">Aktif</option>
                            <option value="nonaktif">Nonaktif</option>
                        </select>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<!-- Modal Import Data -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">Import Data user</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="importForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="fileImport" class="form-label">Pilih File Excel</label>
                        <input type="file" class="form-control" id="fileImport" name="fileImport" accept=".xlsx, .xls, .csv" required>
                    </div>
                    <div class="alert alert-info" role="alert">
                        Format file harus sesuai dengan kolom berikut: <b>Nama, NIK, Tanggal Lahir, Jenis Kelamin, Alamat, Nama Ibu, Nama Ayah, Status Imunisasi, Berat Badan, Tinggi Badan</b>.
                    </div>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- untuk canvas tanda tangan -->
<div class="modal fade" id="modalTTD" tabindex="-1" aria-labelledby="modalTTDLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="formTTD">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="modalTTDLabel">Tambah Tanda Tangan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="id_user" id="ttd_id_user">
                    <canvas id="signature-pad" width="500" height="200" style="border:1px solid #ccc; width: 100%;"></canvas>
                    <button type="button" class="btn btn-warning btn-sm mt-2" id="clear-signature">Hapus Tanda Tangan</button>
                    <input type="hidden" name="ttd_user" id="ttd_user">
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Simpan Tanda Tangan</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- untuk liat tanda tangan -->
<div class="modal fade" id="modalLihatTTD" tabindex="-1" aria-labelledby="modalLihatTTDLabel">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalLihatTTDLabel">Tanda Tangan User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>
            <div class="modal-body text-center" id="ttdContent">
                <!-- Gambar tanda tangan akan ditampilkan di sini -->
            </div>
        </div>
    </div>
</div>

<!-- untuk ajax liat ttd -->
<script>
    function lihatTTD(id_user) {
        $.ajax({
            url: "<?= base_url('Users/getTTD') ?>/" + id_user,
            type: "GET",
            dataType: "json",
            success: function(response) {
                if (response.ttd_user) {
                    let ttdUrl = "<?= base_url('uploads/ttd') ?>/" + response.ttd_user;
                    $('#ttdContent').html(`<img src="${ttdUrl}" alt="TTD User" class="img-fluid rounded shadow" style="max-height:300px;">`);
                    $('#modalLihatTTD').modal('show');
                } else {
                    Swal.fire('Info', 'Anda belum buat tanda tangan.', 'warning');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal mengambil data tanda tangan.', 'error');
            }
        });
    }
</script>

<!-- untuk tambah tanda tangan -->
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.5/dist/signature_pad.umd.min.js"></script>
<script>
    let canvas = document.getElementById('signature-pad');
    let signaturePad = new SignaturePad(canvas);

    // Buka modal dan set id_user
    function openTTDModal(id_user) {
        $('#ttd_id_user').val(id_user);
        signaturePad.clear();
        $('#modalTTD').modal('show');
    }

    // Clear tanda tangan
    $('#clear-signature').click(function() {
        signaturePad.clear();
        $('#ttd_user').val('');
    });

    // Submit form tanda tangan
    $('#formTTD').submit(function(e) {
        e.preventDefault();

        if (!signaturePad.isEmpty()) {
            let dataURL = signaturePad.toDataURL();
            $('#ttd_user').val(dataURL);
        } else {
            Swal.fire('Oops!', 'Silakan isi tanda tangan dulu.', 'warning');
            return;
        }

        $.ajax({
            url: "<?= base_url('Users/simpanTTD') ?>",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success: function(response) {
                if (response.status === 'success') {
                    Swal.fire('Berhasil', response.message, 'success');
                    $('#modalTTD').modal('hide');
                    // Optional: reload data table
                    location.reload();
                } else {
                    Swal.fire('Gagal', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal menyimpan tanda tangan', 'error');
            }
        });
    });
</script>


<!-- Pengaturan untuk role -->
<script>
    function autoSetRole(jabatanSelector, roleSelector) {
        $(jabatanSelector).on('change', function() {
            let text = $(jabatanSelector + " option:selected").text().toLowerCase();
            if (text.includes('staf')) {
                $(roleSelector).val('user');
            }
        });
    }

    $(document).ready(function() {
        autoSetRole('#id_jabatan', '#role'); // Form tambah
        autoSetRole('#edit_id_jabatan', '#edit_role'); // Form edit
    });
</script>


<!-- untuk script untuk select2 -->
<script>
    $(document).ready(function() {
        // Ketika modal ditampilkan
        $('#tambahModal').on('shown.bs.modal', function() {
            // Inisialisasi Select2
            $('#id_jabatan, #id_unit,#id_atasan').select2({
                dropdownParent: $('#tambahModal'), // Memastikan dropdown muncul di dalam modal
                placeholder: "Pilih ",
                allowClear: true
            });
        });

        // Inisialisasi Select2 untuk modal edit
        $('#editModal').on('shown.bs.modal', function() {
            // Inisialisasi Select2
            $('#edit_id_jabatan, #edit_id_unit, #edit_id_atasan').select2({
                dropdownParent: $('#editModal'), // Memastikan dropdown muncul di dalam modal
                placeholder: "Pilih ",
                allowClear: true
            });
        });
    });
</script>

<!-- script import form -->
<script>
    $(document).ready(function() {
        $('#importForm').submit(function(e) {
            e.preventDefault();

            let formData = new FormData(this);

            $.ajax({
                url: '<?= base_url('user/importData') ?>',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // Jika berhasil import
                    if (response.status === 'success') {
                        Swal.fire({
                            title: 'Berhasil!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Menutup modal dan reset form
                                $('#importModal').modal('hide');
                                $('#formImportData')[0].reset();
                                // Lakukan refresh atau tindakan lain yang diperlukan
                            }
                        });
                    } else {
                        // Jika gagal import atau ada duplikasi
                        Swal.fire({
                            title: 'Gagal!',
                            text: response.message,
                            icon: 'error',
                            confirmButtonText: 'Tutup'
                        });
                    }
                },
                error: function() {
                    // Menangani error saat AJAX gagal
                    Swal.fire({
                        title: 'Terjadi Kesalahan!',
                        text: 'Silakan coba lagi.',
                        icon: 'error',
                        confirmButtonText: 'Tutup'
                    });
                }
            });
        });
    });
</script>


<!-- untuk form tambah data -->
<script>
    $(document).ready(function() {
        // Ketika form tambah data disubmit
        $('#formTambahData').submit(function(e) {
            e.preventDefault(); // Mencegah form untuk submit biasa

            var formData = $(this).serialize(); // Mengambil data form

            $.ajax({
                url: "<?= base_url('Users/tambahData') ?>", // Ganti dengan URL controller untuk tambah data
                type: "POST",
                data: formData,
                dataType: "json", // Menyatakan bahwa response yang diharapkan adalah JSON
                success: function(response) {
                    // Jika berhasil menambahkan data
                    if (response.status === 'success') {
                        Swal.fire({
                            title: 'Berhasil!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Menutup modal form
                                $('#tambahModal').modal('hide');

                                // Menyegarkan tabel data tanpa reload
                                location.reload(); // Atau panggil fungsi khusus untuk refresh tabel
                            }
                        });
                    } else if (response.status === 'error') {
                        // Jika terjadi kesalahan
                        Swal.fire({
                            title: 'Gagal!',
                            text: response.message,
                            icon: 'error',
                            confirmButtonText: 'Tutup'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    // Jika terjadi error pada request
                    Swal.fire({
                        title: 'Kesalahan!',
                        text: 'Terjadi kesalahan dalam proses. Silakan coba lagi.',
                        icon: 'error',
                        confirmButtonText: 'Tutup'
                    });
                }
            });
        });
    });
</script>

<!-- Ambil Data untuk nilai Update -->
<script>
    function loadAtasanByUnit(unitSelector, atasanSelector) {
        $(unitSelector).on('change', function() {
            const idUnit = $(this).val();
            if (idUnit) {
                $.ajax({
                    url: "<?= base_url('Users/atasanUnit') ?>/" + idUnit,
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        $(atasanSelector).empty().append('<option disabled selected>Pilih Atasan</option>');
                        if (data.length > 0) {
                            $.each(data, function(i, atasan) {
                                $(atasanSelector).append('<option value="' + atasan.id_user + '">' + atasan.nama + ' (' + atasan.role + ')</option>');
                            });
                        } else {
                            $(atasanSelector).append('<option value="">Tidak ada atasan di unit ini</option>');
                        }
                    }
                });
            } else {
                $(atasanSelector).html('<option disabled selected>Pilih Unit Terlebih Dahulu</option>');
            }
        });
    }

    $(document).ready(function() {
        // Tambah
        loadAtasanByUnit('#id_unit', '#id_atasan');

        // Edit
        loadAtasanByUnit('#edit_id_unit', '#edit_id_atasan');
    });

    // Fungsi untuk memuat data ke modal edit
    function updateData(id_user) {
        $.ajax({
            url: "<?= base_url('Users/getData') ?>/" + id_user, // URL untuk mendapatkan data berdasarkan ID
            type: "GET",
            dataType: "json",
            success: function(response) {
                if (response) {
                    $('#edit_id_user').val(response.id_user);
                    $('#edit_nama').val(response.nama);
                    $('#edit_nip').val(response.nip);
                    $('#edit_id_jabatan').val(response.id_jabatan);
                    $('#edit_id_unit').val(response.id_unit).trigger('change');
                    // Tunggu 500ms agar atasan terload terlebih dahulu
                    setTimeout(function() {
                        $('#edit_id_atasan').val(response.id_atasan);
                    }, 500);
                    $('#edit_status_kepegawaian').val(response.status_kepegawaian);
                    $('#edit_nohape').val(response.nohape);
                    $('#edit_email').val(response.email);
                    $('#edit_role').val(response.role);
                    $('#edit_status').val(response.status);
                    $('#editModal').modal('show'); // Tampilkan modal
                } else {
                    alert('Data tidak ditemukan!');
                }
            },
            error: function(xhr, status, error) {
                alert('Terjadi kesalahan. Silakan coba lagi.');
            }
        });
    }
</script>


<!-- // Fungsi untuk submit form update data -->
<script>
    $('#formEditData').submit(function(e) {
        e.preventDefault(); // Mencegah submit biasa

        var formData = $(this).serialize(); // Ambil data form

        $.ajax({
            url: "<?= base_url('Users/updateData') ?>", // URL untuk update data
            type: "POST",
            data: formData,
            dataType: "json",
            success: function(response) {
                // Jika berhasil menambahkan data
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Menutup modal form
                            $('#tambahModal').modal('hide');

                            // Menyegarkan tabel data tanpa reload
                            location.reload(); // Atau panggil fungsi khusus untuk refresh tabel
                        }
                    });
                } else if (response.status === 'error') {
                    // Jika terjadi kesalahan
                    Swal.fire({
                        title: 'Gagal!',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'Tutup'
                    });
                }
            },
            error: function(xhr, status, error) {
                // Jika terjadi error pada request
                Swal.fire({
                    title: 'Kesalahan!',
                    text: 'Terjadi kesalahan dalam proses. Silakan coba lagi.',
                    icon: 'error',
                    confirmButtonText: 'Tutup'
                });
            }
        });
    });
</script>

<!-- Untuk delete -->
<script>
    function deleteData(id_user) {
        // Konfirmasi untuk menghapus data
        Swal.fire({
            title: 'Apakah Anda yakin ingin menghapus data ini?',
            text: "Data yang dihapus tidak dapat dikembalikan.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Iya, Hapus!',
            cancelButtonText: 'Batal',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "<?= base_url('users/deleteData') ?>", // Ganti dengan URL endpoint controller Anda
                    type: "POST", // Menggunakan POST karena ini adalah penghapusan data
                    data: {
                        id_user: id_user, // Mengirimkan ID ke server
                        // Anda bisa menambahkan parameter lain jika diperlukan
                    },
                    dataType: "json", // Menentukan format data yang diterima (JSON)
                    success: function(response) {
                        // Jika berhasil menambahkan data
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Berhasil!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonText: 'OK'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Menutup modal form
                                    $('#tambahModal').modal('hide');

                                    // Menyegarkan tabel data tanpa reload
                                    location.reload(); // Atau panggil fungsi khusus untuk refresh tabel
                                }
                            });
                        } else if (response.status === 'error') {
                            // Jika terjadi kesalahan
                            Swal.fire({
                                title: 'Gagal!',
                                text: response.message,
                                icon: 'error',
                                confirmButtonText: 'Tutup'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        // Jika terjadi error pada request
                        Swal.fire({
                            title: 'Kesalahan!',
                            text: 'Terjadi kesalahan dalam proses. Silakan coba lagi.',
                            icon: 'error',
                            confirmButtonText: 'Tutup'
                        });
                    }
                });
            }
        });
    }
</script>

<!-- untuk tombol status user -->
<script>
    function changeStatus(id_user, status) {
        Swal.fire({
            title: "Konfirmasi",
            text: "Apakah Anda yakin ingin mengubah status user ini?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Ya, Ubah!",
            cancelButtonText: "Batal",
        }).then((result) => {
            if (result.isConfirmed) {
                // Kirim permintaan AJAX ke server
                $.ajax({
                    url: '<?= base_url('users/changeStatus') ?>', // Sesuaikan dengan route aplikasi Anda
                    type: 'POST',
                    data: {
                        id_user: id_user,
                        status: status
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            Swal.fire({
                                title: "Berhasil!",
                                text: response.message,
                                icon: "success",
                                confirmButtonText: "OK"
                            }).then(() => {
                                location.reload(); // Reload halaman setelah berhasil
                            });
                        } else if (response.status === 'error') {
                            Swal.fire({
                                title: "Gagal!",
                                text: response.message,
                                icon: "error",
                                confirmButtonText: "OK"
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: "Kesalahan!",
                            text: "Terjadi kesalahan pada server. Silakan coba lagi nanti.",
                            icon: "error",
                            confirmButtonText: "OK"
                        });
                    }
                });
            }
        });
    }
</script>


<?= $this->endSection(); ?>