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

<?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success">
        <?= session()->getFlashdata('success') ?>
    </div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-3 mb-md-0">Pengaturan Aplikasi</h4>
    </div>
</div>

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

                <h6 class="card-title">Update Pengaturan</h6>

                <form id="settingsForm" class="forms-sample" enctype="multipart/form-data">
                    <input type="hidden" id="level" name="level" value="<?= session()->get('level'); ?>">

                    <div class="row mb-3">
                        <label for="nama_aplikasi" class="col-sm-3 col-form-label">Nama Aplikasi</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="nama_aplikasi" name="nama_aplikasi" placeholder="Nama aplikasi">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="alamat" class="col-sm-3 col-form-label">Alamat</label>
                        <div class="col-sm-9">
                            <textarea class="form-control" id="alamat" name="alamat" placeholder="Alamat"></textarea>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <label for="keterangan" class="col-sm-3 col-form-label">Keterangan</label>
                        <div class="col-sm-9">
                            <textarea class="form-control" id="keterangan" name="keterangan" placeholder="Keterangan (Optional)"></textarea>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="logoSettings" class="col-sm-3 col-form-label">Logo</label>
                        <div class="col-sm-9">
                            <input type="file" class="form-control" id="logoSettings" name="logoSettings" accept="image/*">
                            <img id="logo" src="" alt="Logo" width="150" class="mt-2">
                        </div>
                    </div>
                    <button type="button" class="btn btn-primary me-2" onclick="updateSettings()">Update</button>
                </form>

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

<script>
    $(document).ready(function() {
        loadSettings(); // Muat Data Pengaturan saat halaman dimuat
    });

    // Fungsi Memuat Data Pengaturan
    function loadSettings() {
        var level = $('#level').val(); // Ambil level Pengaturan dari Sesi
        $.ajax({
            url: "<?= base_url('Settings/getSettings') ?>/" + level, // Panggil Controller
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#nama_aplikasi').val(response.settings.nama_aplikasi);
                    $('#alamat').val(response.settings.alamat);
                    $('#keterangan').val(response.settings.keterangan);

                    // Update logo jika ada
                    if (response.settings.logo) {
                        $('#logo').attr('src', "<?= base_url('/public/assets/images/faces/') ?>/" + response.settings.logo);
                    } else {
                        $('#logo').attr('src', "<?= base_url('/public/assets/images/faces/face9.jpg') ?>");
                    }

                } else {
                    alert('Data pengaturan tidak ditemukan!');
                }
            },
            error: function() {
                alert('Terjadi kesalahan saat memuat pengaturan');
            }
        });
    }

    // Fungsi Memperbarui Pengaturan
    function updateSettings() {
        var formData = new FormData($('#settingsForm')[0]);

        // Validasi sederhana untuk memeriksa apakah form terisi dengan benar
        var nama_aplikasi = $('#nama_aplikasi').val();
        var alamat = $('#alamat').val();
        if (!nama_aplikasi || !alamat) {
            Swal.fire({
                icon: 'error',
                title: 'Form Tidak Lengkap',
                text: 'Harap isi semua field!',
                timer: 2000,
                showConfirmButton: false
            });
            return; // Menghentikan eksekusi jika ada field yang kosong
        }
        // Konfirmasi SweetAlert sebelum mengirim data
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: 'Data pengaturan akan diperbarui.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Ya, perbarui!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {

                $.ajax({
                    url: '<?= base_url('/settings/updateSettings') ?>',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        if (response.success) {
                            $('#message').text(response.message).css('color', 'green');

                            // Perbarui gambar jika ada
                            if (response.logo) {
                                $('#logo').attr('src', "<?= base_url('/public/assets/images/faces/') ?>/" + response.logo);
                            }
                            // Tampilkan SweetAlert Sukses
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            // Tampilkan SweetAlert Gagal
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });
                        }
                    },
                    error: function() {
                        // Tampilkan SweetAlert Kesalahan Server
                        Swal.fire({
                            icon: 'error',
                            title: 'Kesalahan Server!',
                            text: 'Terjadi kesalahan saat memperbarui pengaturan',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }
                });
            }
        });
    }
</script>

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