<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">Chart of Account (COA)</h5>
                <button class="btn btn-warning btn-add">Tambah Akun</button>
            </div>

            <div class="table-responsive">
                <table id="tableAccounts" 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>Tipe</th>
                            <th>Posisi</th>
                            <th>Kategori</th>
                            <th width="15%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

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

<!-- MODAL -->
<div class="modal fade" id="modalAccount">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title">Tambah Akun</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">

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

                <label class="fw-semibold">Kode Akun</label>
                <input type="text" class="form-control" id="kode_akun">

                <label class="fw-semibold mt-2">Nama Akun</label>
                <input type="text" class="form-control" id="nama_akun">

                <label class="fw-semibold mt-2">Tipe</label>
                <select class="form-control" id="tipe">
                    <option value="asset">Asset</option>
                    <option value="liability">Liability</option>
                    <option value="equity">Equity</option>
                    <option value="revenue">Revenue</option>
                    <option value="expense">Expense</option>
                </select>

                <label class="fw-semibold mt-2">Parent</label>
                <select class="form-control" id="parent_id">
                    <option value="">-- Tanpa Parent --</option>
                    <?php foreach($parent_accounts as $p): ?>
                        <option value="<?= $p->id ?>">
                            <?= $p->kode_akun ?> - <?= $p->nama_akun ?>
                        </option>
                    <?php endforeach; ?>
                </select>

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

    let table = $('#tableAccounts').DataTable({
        processing: true,
        serverSide: true,
        responsive: true,
        autoWidth: false,
        order: [],
        ajax: {
            url: "<?= base_url('accounts/get_data'); ?>",
            type: "POST"
        },
        columns: [
            { data: 0, orderable:false },
            { data: 1 },
            { data: 2 },
            { data: 3 },
            { data: 4 },
            { data: 5 },
            { data: 6, orderable:false }
        ],
        language: {
            processing: `<div class="text-center"><div class="spinner-border text-warning"></div></div>`
        }
    });

    // ================= RESET FORM
    function resetForm(){
        $('#inputId').val('');
        $('#kode_akun').val('');
        $('#nama_akun').val('');
        $('#tipe').val('asset');
        $('#parent_id').val('');
        $('#modalAccount .modal-title').text('Tambah Akun');
    }

    // ================= OPEN MODAL
    $('.btn-add').click(function(){
        resetForm();
        $('#btnSimpan').data('action','add');
        $('#modalAccount').modal('show');
    });

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

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

        let data = {
            id: $('#inputId').val(),
            kode_akun: $('#kode_akun').val().trim(),
            nama_akun: $('#nama_akun').val().trim(),
            tipe: $('#tipe').val(),
            parent_id: $('#parent_id').val()
        };

        if(!data.kode_akun || !data.nama_akun){
            Swal.fire('Warning','Kode & Nama wajib diisi','warning');
            return;
        }

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

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

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

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

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

            $('#inputId').val(res.id);
            $('#kode_akun').val(res.kode_akun);
            $('#nama_akun').val(res.nama_akun);
            $('#tipe').val(res.tipe);
            $('#parent_id').val(res.parent_id);

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

            $('#modalAccount').modal('show');

        },'json');
    });

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

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

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

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

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

                },'json');
            }
        });
    });

});
</script>