<?= $this->extend('layout/main') ?>

<?= $this->section('page_title') ?>
<div class="row border-bottom">
    <div class="col-sm-6"><h3 class="mb-0">Pelunasan Invoice</h3></div>
    <div class="col-sm-6">
        <ol class="breadcrumb float-sm-end">
        <li class="breadcrumb-item"><a href="<?=base_url()?>">Home</a></li>
        <li class="breadcrumb-item active" aria-current="page">Pelunasan Invoice</li>
        </ol>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="row g-4">
    <div class="col-lg-8">
        <form name="f1" id="f1" action="<?=base_url()?>transaksi/proses_pelunasan_invoice" method="post" enctype="multipart/form-data">
            <div class="card card-warning card-outline mb-4">
                <div class="card-header">
                    <div class="card-title">Pelunasan Invoice</div>
                </div>
                <div class="card-body">
                    <div>
                        <span>Silahkan isi rentang periode invoice yang akan dilunasi :</span>
                    </div>
                    <hr/>
                    <div class="row mb-3">
                        <label for="id_grup_transaksi" class="col-sm-3 col-form-label">Grup Transaksi : </label>
                        <div class="col-sm-9 d-flex align-items-center">
                            <span class="form-control" id="id_grup_transaksi" class="text-secondary">- Pilih Grup Transaksi -</span>
                            <a id="b_cari_grup_transaksi" href="#" class="btn btn-primary">Pilih</a>
                            <input type="hidden" name="id_grup_transaksi">
                        </div>
                        <div id="eid_grup_transaksi" class="text-danger invalid-feedback text-end"></div>
                    </div>
                    <div class="row mb-3">
                        <label for="id_kk" class="col-sm-3 col-form-label">Rumah : </label>
                        <div class="col-sm-9 d-flex align-items-center">
                            <span class="form-control" id="id_kk" class="text-secondary">- Semua Rumah -</span>
                            <a id="b_cari_rumah" href="#" class="btn btn-primary">Pilih</a>
                            <input type="hidden" name="id_kk">
                        </div>
                        <div id="eid_grup_transaksi" class="text-danger invalid-feedback text-end"></div>
                    </div>
                    <div class="row mb-3">
                        <label for="start_date" class="col-sm-3 col-form-label">Tanggal Awal : </label>
                        <div class="col-sm-9">
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?=date("Y-m-d")?>">
                            <span id="estart_date" class="text-danger invalid-feedback"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="end_date" class="col-sm-3 col-form-label">Tanggal Akhir : </label>
                        <div class="col-sm-9">
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?=date("Y-m-d")?>">
                            <span id="eend_date" class="text-danger invalid-feedback"></span>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex">
                    <button type="submit" class="btn btn-primary">Proses</button>
                </div>
            </div>
        </form>        
    </div>
    <div class="col-lg-4">
        <div class="card card-danger">
            <div class="card-header">
                Perhatian
            </div>
            <div class="card-body">
                <p>Dianjurkan untuk melakukan generate invoice pada saat tidak ada transaksi untuk mencegah collision data dengan transaksi pembayaran. Serta pastikan proses generate selesai sebelum melakukan transaksi pembayaran.</p>

                <p>Rumah yang belum memiliki setup tarif tidak akan di-terbitkan invoicenya.</p>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('page_script') ?>
<?= $this->include('layout/css/sweetalert') ?>
<?= $this->include('layout/js/sweetalert') ?>

<?= $this->include('layout/css/draggable_dialog') ?>
<?= $this->include('layout/js/draggable_dialog') ?>
<?= $this->include('layout/js/datatables') ?>

<div id="dialogGrupTransaksi" class="dialog" style="min-width:500px; min-height:400px;">
	<div class="titlebar"></div>
	<button name="close"></button>
	<div class="content">
        <table id="tbl_dialog_grup_transaksi" class="table table-bordered table-sm nowrap">
            <thead>
                <tr>
                    <th>No.</th>
                    <th class="dt-filterable">Nama</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
	</div>
	<div class="buttonpane">
		<div class="buttonset">
			<button name="cancel">Cancel</button>
		</div>
	</div>
</div>

<div id="dialogRumah" class="dialog" style="min-width:500px; min-height:400px;">
	<div class="titlebar"></div>
	<button name="close"></button>
	<div class="content">
        <table id="tbl_dialog_rumah" class="table table-bordered table-sm nowrap">
            <thead>
                <tr>
                    <th>No.</th>
                    <th class="dt-filterable">Kode</th>
                    <th class="dt-filterable">Pemilik</th>
                    <th class="dt-filterable">Alamat</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
	</div>
	<div class="buttonpane">
		<div class="buttonset">
			<button name="cancel">Cancel</button>
		</div>
	</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
let totalWarga = 0;
let chunkSize = 10;
let totalPages = 0;
var id_grup_transaksi = 0;
var id_kk = 0;

function startProses(startDate, endDate) {
    Swal.fire({
        text: 'Memproses data.. Silahkan tunggu..',
        allowOutsideClick: false
    });
    Swal.showLoading();

    $.ajax({
        url: '<?=base_url()?>transaksi/proses_pelunasan_invoice',
        method: 'POST',
        data: {
            id_grup_transaksi:id_grup_transaksi,
            id_kk:id_kk,
            page: 1,
            limit: chunkSize,
            start_date: startDate,
            end_date: endDate
        },
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Selesai!',
                    text: 'Semua invoice berhasil dilunasi.'
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: response.message || 'Terjadi kesalahan saat proses.'
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Koneksi ke server gagal.'
            });
        }
    });
}

$("#f1").submit(function (e) {
    e.preventDefault();

    const startDate = $('#start_date').val();
    const endDate = $('#end_date').val();
    id_grup_transaksi = $("input[name='id_grup_transaksi']").val();
    id_kk = $("input[name='id_kk']").val();

    if (!startDate || !endDate || !id_grup_transaksi || !id_kk ) {
        Swal.fire({
            icon: 'warning',
            title: 'Input tidak lengkap',
            text: 'Harap isi tanggal awal dan akhir, grup transaksi serta rumah.'
        });
        return;
    }

    startProses(startDate, endDate);
});

});
</script>

<script>
var dialogGrupTransaksi;
var tbl_dialog_grup_transaksi;

function setDialogForInput(dialog, dialog_id, button, table_dialog, table_dialog_id, ajax_url, input, display){
    function showDialog() {
        if (!dialog) {
            dialog = new DialogBox(dialog_id, callbackDialog);
        }
        // Show Dialog Box
        dialog.showDialog();
        function callbackDialog(btnName) {
        }
    }

    $("#" + button).click(function(e){
        e.preventDefault();
        showDialog();
    });

    table_dialog = $("#" + table_dialog_id).DataTable({
        processing: true,
        serverSide: true,
        scrollX: true,
        pageLength:10,
        responsive:false,
        order: [[1, 'asc']],
        dom: 'frtip',
        language : {
            searchBuilder: {
                button: '<span class="fas fa-search"> Filter</span>',
                columns: [".dt-filterable"]
            }
        },
        ajax: {
            url : '<?=base_url()?>' + ajax_url,
            type : 'POST'
        },
        columns: [
            { data: null,
                    width: '1%',
                searchable : false,
                orderable : false,
            className: 'dt-center', targets: '_all' },
            { data: 'nama' },
            { data: null,
                searchable : false,
                orderable : false,
            className: 'dt-center', targets: '_all' },
        ],
        columnDefs: [
            {
                targets: 2,
                data: null,
                defaultContent: '<a href="#" class="btn-pilih btn btn-block btn-success btn-sm"><span class="fas fa-search"></span> Pilih</a>',
            },
        ],
        "initComplete": function(settings, json) {
        }
    });

    table_dialog.on( 'draw.dt', function () {
        var PageInfo = $('#' + table_dialog_id).DataTable().page.info();
        table_dialog.column(0, { page: 'current' }).nodes().each( function (cell, i) {
            cell.innerHTML = i + 1 + PageInfo.start;
        });
    });

    $('#' + table_dialog_id + ' tbody').on('click','.btn-pilih',function (e) {
        e.preventDefault();
        var data = table_dialog.row($(this).parents('tr')[0]).data();
        $("#" + display).html(data['nama']);
        $("input[name='" + input + "']").val(data[display]);
        dialog.close();
    });
}

setDialogForInput(dialogGrupTransaksi, 'dialogGrupTransaksi', 'b_cari_grup_transaksi', tbl_dialog_grup_transaksi, 'tbl_dialog_grup_transaksi', 'grup_transaksi/ajax_dt', 'id_grup_transaksi', 'id_grup_transaksi');
</script>

<script>
var dialogRumah;
var tbl_dialog_rumah;

function setDialogForInput3(dialog, dialog_id, button, table_dialog, table_dialog_id, ajax_url, input, display){
    function showDialog() {
        if (!dialog) {
            dialog = new DialogBox(dialog_id, callbackDialog);
        }
        // Show Dialog Box
        dialog.showDialog();
        function callbackDialog(btnName) {
        }
    }

    $("#" + button).click(function(e){
        e.preventDefault();
        showDialog();
    });

    table_dialog = $("#" + table_dialog_id).DataTable({
        processing: true,
        serverSide: true,
        scrollX: true,
        pageLength:10,
        responsive:false,
        order: [[1, 'asc']],
        dom: 'frtip',
        language : {
            searchBuilder: {
                button: '<span class="fas fa-search"> Filter</span>',
                columns: [".dt-filterable"]
            }
        },
        ajax: {
            url : '<?=base_url()?>' + ajax_url,
            type : 'POST'
        },
        columns: [
            { data: null,
                    width: '1%',
                searchable : false,
                orderable : false,
            className: 'dt-center', targets: '_all' },
            { data: 'kode' },
            { data: 'nama_pemilik' },
            { data: 'alamat' },
            { data: null,
                searchable : false,
                orderable : false,
            className: 'dt-center', targets: '_all' },
        ],
        columnDefs: [
            {
                targets: 4,
                data: null,
                defaultContent: '<a href="#" class="btn-pilih btn btn-block btn-success btn-sm"><span class="fas fa-search"></span> Next</a>',
            },
        ],
        "initComplete": function(settings, json) {
        }
    });

    table_dialog.on( 'draw.dt', function () {
        var PageInfo = $('#' + table_dialog_id).DataTable().page.info();
        table_dialog.column(0, { page: 'current' }).nodes().each( function (cell, i) {
            cell.innerHTML = i + 1 + PageInfo.start;
        });
    });

    $('#' + table_dialog_id + ' tbody').on('click','.btn-pilih',function (e) {
        e.preventDefault();
        var data = table_dialog.row($(this).parents('tr')[0]).data();
        $("#" + display).html("["+data['kode']+"] "+data['nama_pemilik']);
        $("input[name='" + input + "']").val(data[display]);
        dialog.close();
    });
}

setDialogForInput3(dialogRumah, 'dialogRumah', 'b_cari_rumah', tbl_dialog_rumah, 'tbl_dialog_rumah', 'kk/ajax_dt','id_kk','id_kk');
</script>
<?= $this->endSection() ?>