var item_line_idx       = 0;
var delivery_line_idx   = 0;
var recipient_line_idx  = 0;

function cancelCorporateGiftEntry() {
    prevscreen('CorporateGift');
    corporateGiftFilter();
}

function addCorporateGift() {
    saveCorporateGiftEntry(C_ADD);
}
function updateCorporateGift() {
    saveCorporateGiftEntry(C_UPDATE);
}

function saveCorporateGiftEntry(type) {
    LoadingScreen("show");
    if (validateDelivery() && validateCorporateGiftEntry()) {
        var data = {
            "type"              : type,

            "id"                : $('#txtCorporateGiftID').val(),
            "name"              : $('#txtCorporateGiftName').val(),
            "active"            : ($('#chkCorporateGiftActive').is(':checked') ? '1' : '0'),
            "date_from"         : $('#txtCorporateGiftDateFrom').val(),
            "date_to"           : $('#txtCorporateGiftDateTo').val(),
            "cut_off"           : $('#txtCorporateGiftCutOff').val(),

            "email_subject"     : $('#txtCorporateGiftEmailSubject').val(),
            "email_button"      : $('#txtCorporateGiftEmailButton').val(),
            "email_content"     : $('#txtCorporateGiftEmailContent').val(),
            "email_footer"      : $('#txtCorporateGiftEmailFooter').val(),

            "items"             : getCorporateGiftNewItem(),
            "items_existing"    : getCorporateGiftItem(),
            "delivery"          : getCorporateGiftDelivery(),
            "header_images"     : getCompanyHeaderImage(),
            "recipient"         : getRecipient(),
        };
        var url = "index.pzx?c=" + corporate_gift_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCorporateGiftEntry, null);
        return false;
    } else {
        LoadingScreen("hide");
    }
}

function getCompanyHeaderImage(){
    var arrays = [];
    $('.companyEmailHeaderImage').each(function () {
        var comp_id = $(this).find('.companyProfileId').val();

        var data = {
            "comp_id"            : comp_id,
            "header_filename"    : $('#txtCorporateGiftHeaderImageFilename'+comp_id).val(),
            "header_file_ext"    : $('#txtCorporateGiftHeaderImageFileExt'+comp_id).val(),
            "header_file_base64" : $('#txtCorporateGiftHeaderImageFileBase64'+comp_id).html()
        }
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

//Header Delivery
//========================================
function addDelivery(){
    $('#corporate-gift-delivery-table-body').append(
        "<tr id='lineDelivery"+delivery_line_idx+"'>" +
            "<td class='counter' style='display:none;'>" + delivery_line_idx + "</td>" +
            "<td><input type='date' id='corporate_gift_delivery_date" + delivery_line_idx + "' class='form-control'></td>" +
            "<td><input id='corporate_gift_delivery_time1" + delivery_line_idx + "' class='form-control'></td>" +
            "<td><input id='corporate_gift_delivery_time2" + delivery_line_idx + "' class='form-control'></td>" +
            "<td style='text-align: center;'>"+
                "<button onclick='deleteCorporateGiftDelivery("+delivery_line_idx+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
            "</td>" + 
        "</tr>"
    )
    delivery_line_idx++;
}

function validateDelivery() {
    var status = true;
    var delivery_tr = $('#corporate-gift-delivery-table-body tr');
    delivery_tr.each(function () {
        var idx = $(this).find(".counter").html();

        if($('#corporate_gift_delivery_date'+idx).blank()){
            swal.fire("Warning", "Delivery Date cannot be blank", "warning");
            status = false;
        }
        if($('#corporate_gift_delivery_time1'+idx).blank()){
            swal.fire("Warning", "Delivery Time 1 cannot be blank", "warning");
            status = false;
        }
        if($('#corporate_gift_delivery_time2'+idx).blank()){
            swal.fire("Warning", "Delivery Time 2 cannot be blank", "warning");
            status = false;
        }
    });
    return status;
}

function getCorporateGiftDelivery() {
    var arrays = [];
    var data = {};
    var delivery_tr = $('#corporate-gift-delivery-table-body tr');
    delivery_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {
            "idx"               : idx,
            "delivery_date"     : $('#corporate_gift_delivery_date'+idx).val(),
            "delivery_time1"    : $('#corporate_gift_delivery_time1'+idx).val(),
            "delivery_time2"    : $('#corporate_gift_delivery_time2'+idx).val(),
        };
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

function showCorporateGiftTestEmailModal(){
    $('#emailTestModal').modal('show');
}

function sendTestingEmail(){

    var data = {
		"type"		    : "SEND_EMAIL_TESTING",
		"id"		    : $('#txtCorporateGiftID').val(),
		"email_from"    : $('#cobCorporateGiftTestEmailFrom').val(),
		"email_to"	    : $('#cobCorporateGiftTestEmailTo').val(),
	};
	var url = "request.pzx?c=" + corporate_gift_entry_url + "&d=" + new Date().getTime();
	callServer(url, "json", data, onResponseCorporateGiftEntry, null);
}

//Header Item
//========================================
function saveCorporateGiftItem(item_line_id = 'newline') {
    if(item_line_id == 'newline'){
        if(!$('#txtCorporateGiftItemName').blank() && ($('#txtCorporateGiftItemImageFileBase64').blank() && $('#txtCorporateGiftItemImageFilename').blank())){
            swal.fire("Warning", "Item Image cannot be blank", "warning");
            return;
        }
    }

    var item_name     = $('#txtCorporateGiftItemName').val();
    var filename      = $('#txtCorporateGiftItemImageFilename').val();
    var file_ext      = $('#txtCorporateGiftItemImageFileExt').val();
    var file_base64   = $('#txtCorporateGiftItemImageFileBase64').val();
    var image         = $('#imgCorporateGiftItemImage').attr('src');

    if(item_name != ""){
        if(item_line_id == 'newline'){
            item_line_idx++;
            var item_newline = "<tr id='lineItem"+item_line_idx+"' class='new_item'>"+
                                    "<td id='line_num"+item_line_idx+"' class='counter' style='display:none;'>"+ item_line_idx +"</td>"+
                                    "<td id='corporate_gift_item_id"+item_line_idx+"' style='display:none;'></td>" +
                                    "<td style='padding: 10px !important;'>"+
                                        "<span id='corporate_gift_item_name"+item_line_idx+"'>"+ item_name +"</span><br><br>"+
                                        "<img src='"+image+"' id='corporate_gift_item_image"+item_line_idx+"' style='width:100px;height:100px;'/>"+
                                    "</td>"+
                                    "<td style='padding: 10px !important;'>"+
                                        "<button onclick='deleteCorporateGiftItem("+item_line_idx+")' 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"+item_line_idx+"'>"+filename+"</td>"+
                                    "<td style='display:none;' id='corporate_gift_item_image_file_ext"+item_line_idx+"'>"+file_ext+"</td>"+
                                    "<td style='display:none;' id='corporate_gift_item_image_file_base64"+item_line_idx+"'>"+file_base64+"</td>"+
                                "</tr>";
            $('#corporate-gift-table-body').append(item_newline);
            $('#corporate-gift-table-body tr').click(function() {
                showCorporateGiftItem($(this).find('td').eq(0).html());
                $(this).addClass('highlight').siblings().removeClass('highlight');
            });
            clearCorporateGiftItem();
        }else{
            $('#corporate_gift_item_name'+item_line_id).html(item_name);
            $('#corporate_gift_item_image_filename'+item_line_id).html(filename);
            $('#corporate_gift_item_image_file_ext'+item_line_id).html(file_ext);
            $('#corporate_gift_item_image_file_base64'+item_line_id).html(file_base64);
            $('#corporate_gift_item_image'+item_line_id).attr('src', image);
            clearCorporateGiftItem();
        }
    }
    if($('#txtCorporateGiftID').val() == 0 || $('#txtCorporateGiftID').val() == ''){
        addCorporateGift();
    }else{
        updateCorporateGift();
    }
}

function getCorporateGiftNewItem() {
    var arrays = [];
    var data = {};
    var item_tr = $('#corporate-gift-table-body tr.new_item');
    item_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {            
            "idx"               : idx,
            "item_name"         : $('#corporate_gift_item_name'+idx).html(),
            "item_filename"     : $('#corporate_gift_item_image_filename'+idx).html(),
            "item_file_ext"     : $('#corporate_gift_item_image_file_ext'+idx).html(),
            "item_file_base64"  : $('#corporate_gift_item_image_file_base64'+idx).html(),
        };
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

function getCorporateGiftItem() {
    var arrays = [];
    var data = {};
    var item_tr = $('#corporate-gift-table-body tr.existing_item');
    item_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {
            "idx"               : idx,
            "item_id"           : $('#corporate_gift_item_id'+idx).html(),
            "item_name"         : $('#corporate_gift_item_name'+idx).html(),
            "item_filename"     : $('#corporate_gift_item_image_filename'+idx).html(),
            "item_file_ext"     : $('#corporate_gift_item_image_file_ext'+idx).html(),
            "item_file_base64"  : $('#corporate_gift_item_image_file_base64'+idx).html(),
        };
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

function validateCorporateGiftEntry() {
    if ($('#txtCorporateGiftName').blank()) {
        swal.fire("Warning", "Gift Name cannot be blank", "warning");
        return false;
    }

    if ($('#txtCorporateGiftEmailSubject').blank()) {
        swal.fire("Warning", "Email Subject cannot be blank", "warning");
        return false;
    }
    
    if ($('#txtCorporateGiftEmailButton').blank()) {
        swal.fire("Warning", "Email Button cannot be blank", "warning");
        return false;
    }

    return true;
}

function onResponseCorporateGiftEntry(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }

    if (resp.type == C_ADD) {
        swal.fire('Success', resp.mesg, 'success');
        $("#txtCorporateGiftID").val(resp.data.id);

        data = resp.data.item;
        for(i in data){
            $('#corporate_gift_item_id' + data[i].idx).html(data[i].id);
            $('#corporate_gift_item_image_filename' + data[i].idx).html(data[i].filename);
            $('#lineItem' + data[i].idx).attr('class', 'existing_item');
        }
        
        data = resp.data.delivery;
        for(i in data){
            $('#corporate_gift_delivery_id' + data[i].idx).html(data[i].id);
            $('#lineDelivery' + data[i].idx).attr('class', 'existing_delivery');
        }

        $("#btnSaveDeliveryTime").attr("onclick", "updateCorporateGift();");
        $("#btnSaveCorporateGiftEmail").attr("onclick", "updateCorporateGift();");
        $("#btnSaveRecipient").attr("onclick", "updateCorporateGift();");
    }
    if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');

        data = resp.data.item_id;
        for(i in data){
            $('#corporate_gift_item_id' + data[i].idx).html(data[i].id);
            $('#corporate_gift_item_image_filename' + data[i].idx).html(data[i].filename);
            $('#lineItem' + data[i].idx).attr('class', 'existing_item');
        }
        data = resp.data.delivery_id;
        for(i in data){
            $('#corporate_gift_delivery_id' + data[i].idx).html(data[i].id);
            $('#lineDelivery' + data[i].idx).attr('class', 'existing_delivery');
        }
    }
    if(resp.type == "C_GET_CUSTOMER_CONTACTS"){
        $('#cobCorporateGiftRecipientContact').html(resp.data);
        $('#cobCorporateGiftRecipientContact').select2({
            width: '100%'
        });
    }
    if(resp.type=="SEND_EMAIL_TESTING") {
        swal.fire("Success",resp.mesg, "success") ;
        $('#emailTestModal').modal('hide');
    }
}

function showCorporateGiftItem(item_id){
    item_name       = $('#corporate_gift_item_name' + item_id).html();
    item_filename   = $('#corporate_gift_item_image_filename' + item_id).html();
    image_path      = $('#corporate_gift_item_image' + item_id).attr('src');
    $('#txtCorporateGiftItemName').val(item_name);
    $('#txtCorporateGiftItemImageFilename').val(item_filename);
    $('#imgCorporateGiftItemImage').attr('src', image_path);
    $('.btnSaveCorporateGift').attr('onclick', 'saveCorporateGiftItem('+item_id+')');
}

function clearCorporateGiftItem(){
    $('#txtCorporateGiftItemName').val('');
    $('#txtCorporateGiftItemImage').val('');
    $('#txtCorporateGiftItemImageFilename').val('');
    $('#txtCorporateGiftItemImageFileExt').val('');
    $('#txtCorporateGiftItemImageFileBase64').val('');
    $('#imgCorporateGiftItemImage').attr('src', '../web/picture/default/default.png');
    $('.btnSaveCorporateGift').attr('onclick', 'saveCorporateGiftItem()');
    $('#corporate-gift-table-body .highlight').removeClass('highlight');
}

//========================================

//Header Image
//========================================
function hasExtensionCorporateGiftHeaderImage(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCorporateGiftHeaderImage(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCorporateGiftHeaderImage(event, coy_id) {
    var filesSelected = document.getElementById("txtCorporateGiftHeaderImage" + coy_id).files;
    if (!hasExtensionCorporateGiftHeaderImage('txtCorporateGiftHeaderImage' + coy_id, ['.jpg', '.jpeg', '.png'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png' ");
        $("#txtCorporateGiftHeaderImage" + coy_id).val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCorporateGiftHeaderImage(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCorporateGiftHeaderImageFileBase64' + coy_id).html(srcData);
            $('#txtCorporateGiftHeaderImageFileExt' + coy_id).val(fileExt);
            $('#txtCorporateGiftHeaderImageFilename' + coy_id).val(filesSelected[0].name);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCorporateGiftHeaderImage'+ coy_id).attr('src', src);
}

function removeCorporateGiftHeaderImage() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company Header Image?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_CORPORATE_GIFT_HEADER_IMAGE", "id": 0, "path": $('#imgCorporateGiftHeaderImage').attr('src') };
            var url = "index.pzx?c=" + corporate_gift_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCorporateGiftHeaderImage, null);
        }
    });
}

function onResponseCorporateGiftHeaderImage(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire("Warning", resp.mesg, 'warning');
        return;
    }

    if (resp.type == "DELETE_CORPORATE_GIFT_HEADER_IMAGE") {
        $('#txtCorporateGiftHeaderImageFilename').val("");
        $("#imgCorporateGiftHeaderImage").attr("src", resp.data.src);
    }
}
//========================================

//item Image
//========================================
function hasExtensionCorporateGiftItemImage(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCorporateGiftItemImage(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCorporateGiftItemImage(event) {
    var filesSelected = document.getElementById("txtCorporateGiftItemImage").files;
    if (!hasExtensionCorporateGiftItemImage('txtCorporateGiftItemImage', ['.jpg', '.jpeg', '.png'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png' ");
        $("#txtCorporateGiftItemImage").val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCorporateGiftItemImage(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCorporateGiftItemImageFileBase64').val(srcData);
            $('#txtCorporateGiftItemImageFileExt').val(fileExt);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCorporateGiftItemImage').attr('src', src);
}

function removeCorporateGiftItemImage() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the item image?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_ITEM_IMAGE", "id": 0, "path": $('#imgCorporateGiftItemImage').attr('src') };
            var url = "index.pzx?c=" + corporate_gift_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCorporateGiftItemImage, null);
        }
    });
}
//========================================

//Recipient
//========================================
function changeContactName(){
    data = {
        "type"  : "C_GET_CUSTOMER_CONTACTS",
        "id"    : $('#cobCorporateGiftRecipientCustomer').val()
    }
    var url = "index.pzx?c=" + corporate_gift_entry_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCorporateGiftEntry, null);
    return false;
}

function addRecipient(){
    if($('#cobCorporateGiftRecipientCustomer').blank()){
        swal.fire("Warning", "Customer Name cannot be blank", 'warning');
        return;
    }
    if($('#cobCorporateGiftRecipientContact').blank()){
        swal.fire("Warning", "Contact Name cannot be blank", "warning");
        return;
    }
    var customer_name   = $('#cobCorporateGiftRecipientCustomer option:selected').text();
    var customer_id     = $('#cobCorporateGiftRecipientCustomer').val();

    var contact_name    = $('#cobCorporateGiftRecipientContact option:selected').text();
    var contact_id      = $('#cobCorporateGiftRecipientContact').val();
    
    var is_exist = false;
    recipient_table = $('#corporate-gift-recipient-table-body tr');
    recipient_table.each(function () {
        var idx = $(this).find(".counter").html();
        
        if($('#txtRecipientCustomer'+idx).html() == customer_id && $('#txtRecipientContact'+idx).html() == contact_id){
            is_exist = true;
        }
    });

    if(is_exist){
        swal.fire("Warning", "Recipient already exist in table", "warning");
        return;
    }
    $('#corporate-gift-recipient-table-body').prepend(
        "<tr id='recipientLine" + recipient_line_idx + "'>" + 
            "<td style='padding: 5px !important; display:none;' class='counter'>" + recipient_line_idx + "</td>" + 
            "<td style='padding: 5px !important;'>" + customer_name + "</td>" + 
            "<td style='padding: 5px !important;'>" + contact_name + "</td>" + 
            "<td style='padding: 5px;'><input id='txtRecipientAmount" + recipient_line_idx + "' type='number' step='1' value='0' class='form-control'></td>" + 
            "<td style='padding: 5px; display:none;' id='txtRecipientID" + recipient_line_idx + "' class='form-control'>-1</td>" + 
            "<td style='padding: 5px; display:none;' id='txtRecipientCustomer" + recipient_line_idx + "' class='form-control'>" + customer_id + "</td>" + 
            "<td style='padding: 5px; display:none;' id='txtRecipientContact" + recipient_line_idx + "' class='form-control'>" + 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(" + recipient_line_idx + ");'><i class='fa fa-trash-o'></i></button></td>" + 
        "</tr>"
    );
    recipient_line_idx++;
}

function getRecipient(){
    var arrays = [];
    var data = {};

    recipient_table = $('#corporate-gift-recipient-table-body tr');
    recipient_table.each(function () {
        var idx = $(this).find(".counter").html();
        data = {            
            "customer_id"   : $('#txtRecipientCustomer' + idx).html(),
            "contact_id"    : $('#txtRecipientContact' + idx).html(),
            "gift_amt"      : $('#txtRecipientAmount' + idx).val(),
        };
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

function deleteRecipient(idx){
    $('#recipientLine' + idx).remove();
}
//========================================
