var corporate_gift_idx = 0;
var corporate_gift_code_list = [];

var C_LIST_CORPORATE_GIFT = "76401";
var C_NEW_CORPORATE_GIFT  = "76402";

var corporate_gift_id = 0;

function addNewCorporateGift() {
    LoadingScreen("show");
    screen_index++;
    cust_policy_idx = 0;
    var data = { "type": C_NEW_CORPORATE_GIFT, "index": screen_index };
    var url = "index.pzx?c=" + corporate_gift_entry_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCorporateGift, null);
}

function reviewCorporateGift() {
    LoadingScreen("show");
    if (corporate_gift_id != 0) {
        screen_index++;
        var data = {
            "type"  : C_GET,
            "index" : screen_index,
            "id"    : corporate_gift_id,
        };
        var url = "index.pzx?c=" + corporate_gift_entry_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCorporateGift, null);
    }else{
        LoadingScreen("hide");
        swal.fire("Warning", "Please select a corporate gift", "warning")
    }
}

function deleteCorporateGift() {
    //get who checked into the list
    var lines = [];
    $("input[name='corporate_gift_chk[]']:checked").each(function (i) {
        lines[i] = $(this).val();
    });

    //confirmation and delete column
    if (lines.length > 0) {
       Swal.fire({
            title: "System Confirmation",
            text: "Are you sure you want to delete the selected record line?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "OK",
            cancelButtonText: "Cancel",
            customClass: {
                confirmButton: 'swal-btn-confirm',
                cancelButton: 'swal-btn-cancel'
            }
        }).then(function (result) {
            if (result.isConfirmed) {
                LoadingScreen("show");

                for (var i = 0; i < lines.length; i++) {
                    var id = $('#corporate_gift_id' + lines[i]).html();

                    var data = { "type": C_DELETE, "id": id, "index": screen_index };
                    var url = "index.pzx?c=" + corporate_gift_url + "&d=" + new Date().getTime();

                    callServer(url, "json", data, onResponseCorporateGift, null);
                }
            }
        });
    } else {
        return;
    }
}

function corporateGiftFilter() {
    LoadingScreen("show");
    var data = {
        "type": C_LIST_CORPORATE_GIFT,
        "index": screen_index,
        "sorts": sorts,
    };
    var url = "request.pzx?c=" + corporate_gift_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCorporateGift, null);
}

function onResponseCorporateGift(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }
    if (resp.type == C_LIST_CORPORATE_GIFT) {
        corporate_gift_code_list = [];
        var myObj = JSON.parse(resp.data);
        showCorporateGiftList(myObj);
    } if (resp.type == C_GET) {
        showContentIndex(resp.data.htmlContent);

        $('#txtCorporateGiftID').val(resp.data.headerData.id);
        $('#txtCorporateGiftName').val(resp.data.headerData.name);
        $('#txtCorporateGiftName2').val(resp.data.headerData.name);

        if(resp.data.headerData.active == 1){
            $('#chkCorporateGiftActive').prop('checked', true);
        }else{
            $('#chkCorporateGiftActive').prop('checked', false);
        }
        $('#txtCorporateGiftDateFrom').val(resp.data.headerData.date_from);
        $('#txtCorporateGiftDateTo').val(resp.data.headerData.date_to);
        $('#txtCorporateGiftCutOff').val(resp.data.headerData.cut_off);
        $('#txtCorporateGiftEmailSubject').val(resp.data.headerData.email_subject);
        $('#txtCorporateGiftEmailButton').val(resp.data.headerData.email_button);
        $('#txtCorporateGiftEmailContent').val(resp.data.headerData.email_content);
        $('#txtCorporateGiftEmailFooter').val(resp.data.headerData.email_footer);

        items = resp.data.headerData.items;
        for (i in items) {
            $('#corporate-gift-table-body').append(
                "<tr id='lineItem"+i+"' class='existing_item'>"+
                    "<td id='line_num"+i+"' class='counter' style='display:none;'>"+ i +"</td>"+
                    "<td id='corporate_gift_item_id"+i+"' style='display:none;'>"+ items[i].item_id +"</td>"+
                    "<td style='padding: 10px !important;'>"+
                        "<span id='corporate_gift_item_name"+i+"'>"+ items[i].item_name +"</span><br><br>"+
                        "<img id='corporate_gift_item_image"+i+"' style='width:100px;height:100px;'/>"+
                    "</td>"+
                    "<td style='padding: 10px !important;'>"+
                        "<button onclick='deleteCorporateGiftItem("+i+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                    "</td>"+
                    "<td style='display:none;' id='corporate_gift_item_image_filename"+i+"'>"+ items[i].item_filename +"</td>"+
                    "<td style='display:none;' id='corporate_gift_item_image_file_ext"+i+"'></td>"+
                    "<td style='display:none;' id='corporate_gift_item_image_file_base64"+i+"'></td>"+
                "</tr>"
            );
            $('#corporate_gift_item_image' + i).attr('src',items[i].path_item);
            $("#corporate-gift-table-body tr").click(function () {
                showCorporateGiftItem($(this).find('td').eq(0).html());
                $(this).addClass('highlight').siblings().removeClass('highlight');
            });
            item_line_idx++;
        }

        delivery = resp.data.headerData.delivery;
        for (i in delivery) {
            $('#corporate-gift-delivery-table-body').append(
                "<tr id='lineDelivery"+i+"' class='existing_delivery'>"+
                    "<td id='line_num"+i+"' class='counter' style='display:none;'>"+ i +"</td>"+
                    "<td><input type='date' id='corporate_gift_delivery_date" + i + "' class='form-control'></td>" +
                    "<td><input id='corporate_gift_delivery_time1" + i + "' class='form-control' value='" + delivery[i].delivery_time1 + "'></td>" +
                    "<td><input id='corporate_gift_delivery_time2" + i + "' class='form-control' value='" + delivery[i].delivery_time2 + "'></td>" +
                    "<td style='text-align:center'>"+
                        "<button onclick='deleteCorporateGiftDelivery("+i+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                    "</td>"+
                "</tr>"
            );
            $('#corporate_gift_delivery_date' + i).val(delivery[i].delivery_date);
            delivery_line_idx++;
        }

        recipient = resp.data.headerData.recipient;
        for (i in recipient) {
            $('#corporate-gift-recipient-table-body').append(
                "<tr id='recipientLine"+i+"'>"+
                    "<td style='padding: 5px !important; display:none;' class='counter'>" + recipient_line_idx + "</td>" + 
                    "<td style='padding: 5px !important;'>" + recipient[i].customer_name + "</td>" + 
                    "<td style='padding: 5px !important;'>" + recipient[i].contact_name + "</td>" + 
                    "<td style='padding: 5px;'><input id='txtRecipientAmount" + recipient_line_idx + "' class='form-control' value='" + recipient[i].gift_amount + "'></td>" + 
                    "<td style='padding: 5px; display:none;' id='txtRecipientCustomer" + recipient_line_idx + "' class='form-control'>" + recipient[i].customer_id + "</td>" + 
                    "<td style='padding: 5px; display:none;' id='txtRecipientContact" + recipient_line_idx + "' class='form-control'>" + recipient[i].contact_id + "</td>" + 
                    "<td style='padding: 5px; text-align: center !important;'><button class='btn btn-danger btn-sm btn-icon btn-icon-md' type='button' id='btnDeleteRecipient' onclick='deleteRecipient(" + i + ");'><i class='fa fa-trash-o'></i></button></td>" + 
                "</tr>"
            );
            recipient_line_idx++;
        }
        $("#corporateGiftEmailHeaderImageDiv").append(resp.data.headerData.header);
        $("#btnSaveCorporateGiftEmail").attr("onclick", "updateCorporateGift();");
        $(".btnSaveCorporateGift").attr("onclick", "saveCorporateGiftItem();");
        $("#btnSaveDeliveryTime").attr("onclick", "updateCorporateGift();");
        $("#btnSaveRecipient").attr("onclick", "updateCorporateGift();");
    } else if (resp.type == C_DELETE) {
        swal.fire('Success', resp.mesg, 'success');
        corporateGiftFilter();
    } 
    else if (resp.type == C_NEW_CORPORATE_GIFT) {
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);
        $("#corporateGiftEmailHeaderImageDiv").append(resp.data.emailHeader);

        $("#btnSaveDeliveryTime").attr("onclick", "addCorporateGift();");
        $("#btnSaveCorporateGiftEmail").attr("onclick", "addCorporateGift();");
        $(".btnSaveCorporateGift").attr("onclick", "saveCorporateGiftItem();");
        $("#btnSaveRecipient").attr("onclick", "addCorporateGift();");
        $("#cmbCorporateGiftDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_CORPORATE_GIFT_READ_EXCEL") {
        $('#importCorporateGiftModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        corporateGiftFilter();
    }
}

function showCorporateGiftList(myObj) {
    corporate_gift_idx = 0;
    corporate_gift_id = 0;
    $('#corporategift-table-body').html('');

    for (i in myObj) {
        id                      = myObj[i].id;
        corporate_gift_name     = myObj[i].name;
        corporate_gift_status   = myObj[i].status;

        corporate_gift_code_list.push(corporate_gift_name);
        $('#corporategift-table-body').append(
            '<tr id="tr_corporate_gift' + corporate_gift_idx + '">' +
            '<td><input type="checkbox" id="corporate_gift_checkbox' + corporate_gift_idx + '" class="corporate_gift_checkbox" value="' + corporate_gift_idx + '" name="corporate_gift_chk[]" ></td>' +
            '<td><label id="corporate_gift_name' + corporate_gift_idx + '" class="corporate_gift_name" value="' + corporate_gift_name + '" >' + corporate_gift_name + '</label></td>' +
            '<td style="display:none" class="corporate_gift_id" id="corporate_gift_id' + corporate_gift_idx + '">' + id + '</td>' +
            '<td style="display:none" class="corporate_gift_idx" id="corporate_gift_idx' + corporate_gift_idx + '">' + corporate_gift_idx + '</td>' +
            '</tr>'
        );

        //set highlight function and get the journal type ID
        $("#corporategift-table-body tr").click(function () {
            corporate_gift_id = $(this).find('td').eq(2).html();
            $(this).addClass('highlight').siblings().removeClass('highlight');
        });

        corporate_gift_idx++;
    }
}

function checkCorporateGiftCode(obj){
    if($('#txtCorporateGiftID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, corporate_gift_code_list) > -1){
            swal.fire('Warning', "Corporate Gift already existed.", 'warning');
            return;
        }else{
            $("#txtCorporateGiftName2").val($("#txtCorporateGiftName").val());
        }
    }
}

function deleteCorporateGiftItem(item_id){
    $('#lineItem' + item_id).remove();
}

function deleteCorporateGiftDelivery(delivery_id){
    $('#lineDelivery' + delivery_id).remove();
}
