var C_GENERATE_INVOICE_NUMBER                       = "4001";
var C_INVOICE_PRINT_PREVIEW                         = "4003";
var C_RETRIEVE_INVOICE                              = "4004";

var C_EXPORT_INVOICE_FILTER                         = "5001";
var C_EXPORT_INVOICE_EXCEL                          = "5002";

function openModalInvoice(printed) {
    clearGenerateInvoice();
    $('#invoiceModal').modal('show');
    var data = { 
        "type"  : printed == 0 ? C_GENERATE_INVOICE_NUMBER : C_RETRIEVE_INVOICE,
        "id"    : $('#txtSalesQuotationID').val(),
        "bu"    : $('#cobSalesQuotationBU').val(),
        };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseInvoice,null) ;
}
function generateInvoice() {
    Swal.fire({
        title: "Generate Invoice Confirmation",
        text: "Are you sure you want to generate the invoice?'",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            if(validateInvoice()) {
                var select = printSelection();
                var invoice_detail = {
                    "invoice_number" : $('#txtInvoiceNumber').val(),
                    "running_number" : $('#txtInvoiceRunningNumber').val(),
                    "invoice_title" : $('#cobInvoiceTitle option:selected').text(),
                    "invoice_override" : ($('#txtInvoiceOverride').is(':checked') ? 1 : 0),
                    "invoice_type"  : $('#cobInvoiceType').val(),
                    "invoice_value" : $('#txtInvoiceValue').val(),
                    "customer_ref"  : $('#txtInvoiceCustomerReference').val(),
                    "payment_terms" : $('#cobInvoicePaymentTerms').val(),
                    "invoice_remarks" : $('#txtInvoiceRemark').val(),
                    "grand_total"   : $('#txtSalesQuotationGrandTotal').val(),
                };
                var url = "index.pzx?c=" + sales_quotation_url + "&id=" + $('#txtSalesQuotationID').val() + "&bu=" + $('#cobSalesQuotationBU').val() + "&t=" + C_INVOICE_PRINT_PREVIEW + "&r=1&iv="+JSON.stringify(invoice_detail)+ "&s=" + JSON.stringify(select);
                showReport(url) ;
                $('#invoiceModal').modal('hide');
                $('#btnProformaInvoiceSalesQuotation').attr('onclick',"openModalInvoice(1)"); 
            }
        }
    });
}
function retrieveInvoice() {
        var select = printSelection();
        var invoice_detail = {
            "invoice_number" : $('#txtInvoiceNumber').val(),
            "running_number" : -1,
            "invoice_title" : $('#cobInvoiceTitle option:selected').text(),
            "invoice_override" : ($('#txtInvoiceOverride').is(':checked') ? 1 : 0),
            "invoice_type"  : $('#cobInvoiceType').val(),
            "invoice_value" : $('#txtInvoiceValue').val(),
            "customer_ref"  : $('#txtInvoiceCustomerReference').val(),
            "payment_terms" : $('#cobInvoicePaymentTerms').val(),
            "invoice_remarks" : $('#txtInvoiceRemark').val(),
        };
        var url = "index.pzx?c=" + sales_quotation_url + "&id=" + $('#txtSalesQuotationID').val() + "&bu=" + $('#cobSalesQuotationBU').val() + "&t=" + C_INVOICE_PRINT_PREVIEW + "&r=1&iv="+JSON.stringify(invoice_detail)+ "&s=" + JSON.stringify(select);
        showReport(url) ;
}
function validateInvoice() {
    if ($('#txtInvoiceNumber').val()=="") {
        if($('#txtInvoiceOverride').is(':checked')) {
            Swal.fire({
                title:"Warning",
                text: "Invoice Number cannot be blank.",
                type: "warning"
            });
            return false;
        }
    }

    if($('#cobInvoiceTitle').val() == "") {
        Swal.fire({
            title:"Warning",
            text: "Invoice Title cannot be blank.",
            type: "warning"
        });
        return false;
    }

    if($('#cobInvoiceType').val() == "") {
        Swal.fire({
            title:"Warning",
            text: "Invoice Type cannot be blank.",
            type: "warning"
        });
        return false;
    }

    if($('#txtInvoiceValue').val() == "" || $('#txtInvoiceValue').val() == "0") {
        Swal.fire({
            title:"Warning",
            text: "Invoice Value cannot be blank.",
            type: "warning"
        });
        return false;
    }

    if($('#cobInvoicePaymentTerms').val() == "") {
        Swal.fire({
            title:"Warning",
            text: "Payment Terms cannot be blank.",
            type: "warning"
        });
        return false;
    }

    return true;
}
function clearGenerateInvoice() {
    $('#txtInvoiceNumber').val('');
    $('#txtInvoiceRunningNumber').val('');
    // $('#cobInvoiceTitle').val('');
    $('#txtInvoiceOverride').prop("checked", false);
    $('#cobInvoiceType').val('P');
    $('#txtInvoiceValue').val('0');
    $('#txtInvoiceCustomerReference').val('');
    // $('#cobInvoicePaymentTerms').val('');
    $('#txtInvoiceRemark').val('');
}
function disableInputInvoice(disable) {
    // $('#txtInvoiceNumber').prop("disabled", disable);
    $('#txtInvoiceRunningNumber').prop("disabled", disable);
    $('#cobInvoiceTitle').prop("disabled", disable);
    $('#txtInvoiceOverride').prop("disabled", disable);
    $('#cobInvoiceType').prop("disabled", disable);
    $('#txtInvoiceValue').prop("disabled", disable);
    $('#txtInvoiceCustomerReference').prop("disabled", disable);
    $('#cobInvoicePaymentTerms').prop("disabled", disable);
    $('#txtInvoiceRemark').prop("disabled", disable);
}
function overriedInvoiceNumber(obj) {
    $('#txtInvoiceNumber').prop("disabled", !$(obj).is(':checked'));
}
function changeInvoiceType(obj) {
    $('#txtInvoiceValue').val('0');
}
function changeInvoiceValue(obj) {
    if($('#cobInvoiceType').val() == 'A' && $(obj).val() != "") {
        var invoice_value = parseFloat($(obj).val()).toFixed(2);
        $(obj).val(invoice_value);
    }
}

//export excel
function openExportInvoiceModal() {
    $('#exportInvoiceView').modal('show');
}

function filterExportInvoice() {
    var data = { 
        "type"          : C_EXPORT_INVOICE_FILTER, 
        // "coy_id"        : $('#cmbExportInvoiceCoyFilter').val(), 
        // "prospect"      : $('#txtExportInvoiceProspectFilter').val(),
        "from_date"     : $('#txtExportInvoiceFromDateFilter').val(),
        "to_date"       : $('#txtExportInvoiceToDateFilter').val(),
    } ;
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_EXPORT_INVOICE_FILTER  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseInvoice,null) ;
}

function exportInvoiceExcel() {
    var url = "report.pzx?c=" + sales_quotation_url + "&id=0&fdate=" + $('#txtExportInvoiceFromDateFilter').val() + "&tdate=" +  $('#txtExportInvoiceToDateFilter').val() + "&t=" + C_EXPORT_INVOICE_EXCEL + "&r=1";
    showReport(url) ;
}

//response
function onResponseInvoice(obj,resp){
    if (resp.status != C_OK ) {
        Swal.fire('Error', resp.mesg, "error");
        return;
    }

    if(resp.type == C_GENERATE_INVOICE_NUMBER) {
        $('#txtInvoiceNumber').val(resp.data.invoice_number);
        $('#txtInvoiceRunningNumber').val(resp.data.invoice_running_number);
        
        disableInputInvoice(false);
        
        $('#btnGenerateInvoice').show();
        $('#btnRetrieveInvoice').hide();
    } else if(resp.type == C_RETRIEVE_INVOICE) {
        $('#txtInvoiceNumber').val(resp.data.invoice_number);
        // $('#cobInvoiceTitle').text(resp.data.invoice_title);
        $('#txtInvoiceOverride').prop("checked", resp.data.invoice_override);
        $('#cobInvoiceType').val(resp.data.invoice_type);
        $('#txtInvoiceValue').val(resp.data.invoice_value);
        $('#txtInvoiceCustomerReference').val(resp.data.customer_reference);
        $('#cobInvoicePaymentTerms').val(resp.data.payment_terms);
        $('#txtInvoiceRemark').val(resp.data.invoice_remarks);

        $('#cobInvoiceTitle option').each(function() {
            if($(this).text() == resp.data.invoice_title) {
                $(this).attr('selected', 'selected');            
              }
        });

        disableInputInvoice(true);

        $('#btnGenerateInvoice').hide();
        $('#btnRetrieveInvoice').show();
    }  else if(resp.type == C_EXPORT_INVOICE_FILTER) {
        $('#exportInvoiceView').modal('show');
        $('#export-invoice-list-table').html('');
        $('#export-invoice-list-table').append(resp.data);
    }
}