<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 mb-3">
                <h5 class="mb-0">Base Jurnal</h5>
                <button class="btn btn-warning btn-add">Tambah Template</button>
            </div>

            <div class="table-responsive">
                <table id="tableJurnal" class="table modern-table align-middle w-100">
                    <thead class="table-light">
                        <tr>
                            <th width="5%">No</th>
                            <th>Kode</th>
                            <th>Nama</th>
                            <th>Deskripsi</th>
                            <th>Status</th>
                            <th width="15%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

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

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

            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title">Tambah Base Jurnal</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">

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

                <!-- HEADER -->
                <div class="row">
                    <div class="col-md-4">
                        <label>Kode</label>
                        <input type="text" class="form-control" id="kode">
                    </div>
                    <div class="col-md-8">
                        <label>Nama</label>
                        <input type="text" class="form-control" id="nama">
                    </div>
                </div>

                <label class="mt-2">Deskripsi</label>
                <textarea class="form-control" id="deskripsi"></textarea>

                <hr>

                <!-- DETAIL -->
                <div class="d-flex justify-content-between mb-2">
                    <strong>Detail Akun</strong>
                    <button type="button" class="btn btn-sm btn-primary" id="btnAddRow">
                        + Tambah Baris
                    </button>
                </div>

                <table class="table table-bordered" id="tableDetail">
                    <thead>
                        <tr>
                            <th>Akun</th>
                            <th width="150">Posisi</th>
                            <th width="80">Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

            </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>
$(function(){

    // ================= DATATABLE
    let table = $('#tableJurnal').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "<?= base_url('basejurnal/get_data'); ?>",
            type: "POST"
        }
    });

    // ================= GLOBAL STATE
    let accountList = [];
    let isAccountLoaded = false;

    // ================= LOAD ACCOUNT (PROMISE)
    function loadAccounts(){
        return new Promise((resolve, reject) => {
            if(isAccountLoaded){
                resolve();
                return;
            }

            $.get("<?= base_url('basejurnal/get_list_account'); ?>", function(res){
                accountList = res;
                isAccountLoaded = true;
                resolve();
            }, 'json').fail(function(){
                reject();
            });
        });
    }

    // ================= RENDER OPTION
    function renderAccountOption(selected=null){
        let html = `<option value="">-- Pilih Akun --</option>`;

        accountList.forEach(a=>{
            html += `<option value="${a.id}" ${selected==a.id?'selected':''}>
                        ${a.kode_akun} - ${a.nama_akun}
                     </option>`;
        });

        return html;
    }

    // ================= ADD ROW
    function addRow(data=null){
        let row = `
        <tr>
            <td>
                <select class="form-control account_id">
                    ${renderAccountOption(data?.account_id)}
                </select>
            </td>
            <td>
                <select class="form-control posisi">
                    <option value="debit" ${data?.posisi=='debit'?'selected':''}>Debit</option>
                    <option value="kredit" ${data?.posisi=='kredit'?'selected':''}>Kredit</option>
                </select>
            </td>
            <td class="text-center">
                <button class="btn btn-danger btn-sm btn-remove">X</button>
            </td>
        </tr>
        `;

        $('#tableDetail tbody').append(row);
    }

    // ================= RESET FORM
    function resetForm(){
        $('#inputId, #kode, #nama, #deskripsi').val('');
        $('#tableDetail tbody').html('');
    }

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

        resetForm();

        try {
            await loadAccounts();
            addRow();
        } catch(e){
            Swal.fire('Error','Gagal load data akun','error');
            return;
        }

        $('#btnSimpan').data('action','add');
        $('#modalJurnal .modal-title').text('Tambah Base Jurnal');
        $('#modalJurnal').modal('show');
    });

    // ================= ADD ROW BUTTON
    $('#btnAddRow').click(async function(){
        if(!isAccountLoaded){
            await loadAccounts();
        }
        addRow();
    });

    // ================= REMOVE ROW
    $(document).on('click','.btn-remove',function(){
        $(this).closest('tr').remove();
    });

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

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

    let accounts = [];
    let posisi = [];

    $('#tableDetail tbody tr').each(function(){
        let acc = $(this).find('.account_id').val();
        let pos = $(this).find('.posisi').val();

        if(acc){ // skip kosong
            accounts.push(acc);
            posisi.push(pos ? pos : 'debit');
        }
    });

    let data = {
        id: $('#inputId').val(),
        kode: $('#kode').val().trim(),
        nama: $('#nama').val().trim(),
        deskripsi: $('#deskripsi').val().trim(),
        account_id: accounts,
        posisi: posisi
    };

    // VALIDASI
    if(!data.kode || !data.nama){
        Swal.fire('Warning','Kode & Nama wajib diisi','warning');
        return;
    }

    if(accounts.length === 0){
        Swal.fire('Warning','Minimal 1 akun harus dipilih','warning');
        return;
    }

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

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(res){
            if(res.status){
                $('#modalJurnal').modal('hide');
                table.ajax.reload(null,false);
                Swal.fire('Sukses', res.message, 'success');
            } else {
                Swal.fire('Error', res.message, 'error');
            }
        },
        error: function(xhr){
            console.log(xhr.responseText);
            Swal.fire('Error','Terjadi kesalahan server','error');
        }
    });

});

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

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

        resetForm();

        try {
            await loadAccounts();
        } catch(e){
            Swal.fire('Error','Gagal load akun','error');
            return;
        }

        $.get("<?= base_url('basejurnal/detail/'); ?>" + id, function(res){

            $('#inputId').val(res.header.id);
            $('#kode').val(res.header.kode);
            $('#nama').val(res.header.nama);
            $('#deskripsi').val(res.header.deskripsi);

            $('#tableDetail tbody').html('');

            if(res.detail.length > 0){
                res.detail.forEach(d=>{
                    addRow(d);
                });
            } else {
                addRow();
            }

            $('#btnSimpan').data('action','edit');
            $('#modalJurnal .modal-title').text('Edit Base Jurnal');
            $('#modalJurnal').modal('show');

        }, 'json');
    });

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

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

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

                $.ajax({
                    url: "<?= base_url('basejurnal/delete/'); ?>" + id,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res){
                        if(res.status){
                            table.ajax.reload(null,false);
                            Swal.fire('Sukses', res.message, 'success');
                        } else {
                            Swal.fire('Error', res.message, 'error');
                        }
                    },
                    error: function(xhr){
                        console.log(xhr.responseText);
                        Swal.fire('Error','Terjadi kesalahan server','error');
                    }
                });

            }
        });
    });

});
</script>