$('#date').daterangepicker({
    locale: { cancelLabel: 'Sil', customRangeLabel: "Özel seçim" },
    buttonClasses: ' btn',
    applyClass: 'btn-primary',
    cancelClass: 'btn-secondary',
    ranges: {
        'Bugün': [moment(), moment()],
        'Dün': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Son 7 Gün': [moment().subtract(6, 'days'), moment()],
        'Son 30 Gün': [moment().subtract(29, 'days'), moment()],
        'Bu Ay': [moment().startOf('month'), moment().endOf('month')],
        'Geçen Ay': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    }
}, function (start, end, label) {
    document.getElementById('date_start').value = start.format('YYYY-MM-DD');
    document.getElementById('date_end').value = end.format('YYYY-MM-DD');
});

$('#date').on('cancel.daterangepicker', function (ev, picker) {
    document.getElementById('date_start').value = "";
    document.getElementById('date_end').value = "";
});

function initTable() {
    var table = new JSTable("#transactions-table", {
        serverSide : false,
        perPage : 15,
        labels: {
            placeholder: "Ara...",
            perPage: "sayfa başına kayıt",
            noRows: "Hiçbir kayıt bulunamadı!",
            info: "{rows} kayıttan {start} - {end} arası görüntüleniyor",
            loading: "Yükleniyor...",
            infoFiltered: "{rows} kayıttan {start} - {end} arası görüntüleniyor ({rowsTotal} kayıt arasından filtrelendi)"
        },
        layout: {
            top: "{search}",
            bottom: "{info}{pager}"
        }
    });
}
//initTable();

const pleaseWaitModal = new bootstrap.Modal(document.getElementById('please-wait-modal'));

document.getElementById('filter-form').addEventListener('submit', (e) => {
    e.preventDefault();
    pleaseWaitModal.show();
    var formData = new FormData();
    formData.append("date_start", document.getElementById('date_start').value);
    formData.append("date_end", document.getElementById('date_end').value);

    document.querySelector("#transactions-table tbody").innerHTML = "";

    request('/admin/common/api/paytr/list', formData, function (data) {
        try {
            data = JSON.parse(data);
            if (!(data instanceof Object)) {
                console.log('bad data');
                pleaseWaitModal.hide();
            } else {
                if (data['status']) {
                    var html = ""
                    data['result'].forEach((row) => {
                        var islem_tipi = "";
                        if(row['islem_tipi'] == "I") {
                            islem_tipi = "İade";
                        }else if(row['islem_tipi'] == "S") {
                            islem_tipi = "Satış";
                        }
                        html += `<tr>
                            <td>`+row['siparis_no']+`</td>
                            <td>`+row['islem_tarihi']+`</td>
                            <td>`+islem_tipi+`</td>
                            <td class="text-end">`+row['islem_tutari']+` `+row['para_birimi']+`</td>
                            <td class="text-end">`+row['odeme_tutari']+` `+row['para_birimi']+`</td>
                            <td class="text-end">`+row['kesinti_tutari']+` `+row['para_birimi']+` (%`+row['kesinti_orani']+`)</td>
                            <td class="text-end">`+row['net_tutar']+` `+row['para_birimi']+`</td>
                            <td>`+row['taksit']+`</td>
                            <td>`+row['kart_marka']+`</td>
                            <td>`+row['kart_no']+`</td><td>`;
                            if(row['islem_tipi'] == "S") {
                                html += `<button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#return-modal" data-siparis_no="`+row['siparis_no']+`" data-islem_tarihi="`+row['islem_tarihi']+`" data-islem_tutari="`+row['islem_tutari']+`"><i class="bi bi-trash"></i></button>`;
                            }
                            html += `</td></tr>`;
                    });
                    document.querySelector("#transactions-table tbody").innerHTML = html;
                    var clone = document.querySelector("#transactions-table").cloneNode(true);
                    document.getElementById("table-wrapper").innerHTML = "";
                    document.getElementById("table-wrapper").appendChild(clone);
                    initTable();
                    pleaseWaitModal.hide();
                }else{
                    pleaseWaitModal.hide();
                }
            }
        } catch (e) {
            pleaseWaitModal.hide();
            console.log(e);
        }
    });
});





const returnModal = document.getElementById('return-modal');
if (returnModal) {
    returnModal.addEventListener('show.bs.modal', event => {
        var button = event.relatedTarget;
        returnModal.querySelector('.modal-body #siparis_no').value = button.getAttribute('data-siparis_no');
        returnModal.querySelector('.modal-body #islem_tarihi').value = button.getAttribute('data-islem_tarihi');
        returnModal.querySelector('.modal-body #islem_tutari').value = button.getAttribute('data-islem_tutari');
    });
}

const returnForm = document.getElementById('return-form');
if (returnForm) {
    returnForm.addEventListener('submit', e => {
        e.preventDefault();
        pleaseWaitModal.show();
        var formData = new FormData();
        formData.append("merchant_oid", document.getElementById('siparis_no').value);
        formData.append("return_amount", document.getElementById('amount').value);

        request('/admin/common/api/paytr/return', formData, function (data) {
            try {
                data = JSON.parse(data);
                if (!(data instanceof Object)) {
                    console.log('bad data');
                    pleaseWaitModal.hide();
                } else {
                    if (data['status']) {
                        pleaseWaitModal.hide();
                        CustomAlert({
                            title: "İşlem Başarılı",
                            message: "İade tutarı müşteri hesabına gönderildi.",
                            type: "success",
                            close: true,
                            showCancelButton: false,
                            showCloseButton: true,
                            showConfirmButton: true,
                            cancelButtonText: '',
                            confirmButtonText: 'Tamam',
                            static: false
                        });
                    }else{
                        pleaseWaitModal.hide();
                        CustomAlert({
                            title: "İşlem Başarısız",
                            message: data['message'],
                            type: "danger",
                            close: true,
                            showCancelButton: false,
                            showCloseButton: true,
                            showConfirmButton: true,
                            cancelButtonText: '',
                            confirmButtonText: 'Tamam',
                            static: false
                        });
                    }
                }
            } catch (e) {
                pleaseWaitModal.hide();
                console.log(e);
            }
        });
    });
}

