var offset = 0;
var page = 1;
var limit = 100;
var load = true;
var sendRequest = true;
var newRequest = true;
var sort_column = "";
var sort_type = "";

$(document).ready(function(){
    
    loadMoreData();
    //alert(segment1)
});

function resetForm() {
    document.getElementById("filter_form").reset();

    $(".shape-box").each(function(){
        $(this).removeClass("active");
    });
    $(".btn-box").each(function(){
        $(this).removeClass("active");
    });

    priceSliderReset();
    caratSliderReset();
}
function submitForm() {
    $("#add_data").html("");
    /*load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 100;
    sort_column = "";
    sort_type = "";
    defaultSort();*/
    loadMoreData();
}
function sortData(column,type) {
    $("#add_data").html("");
    load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 50;
    sort_column = column;
    sort_type = type;
    loadMoreData();
}

function validateInput(event) {
    var keycode = event.keyCode
    if(keycode != 46 && (keycode < 48 || keycode > 57)) {
        event.preventDefault();
    }  
}
function validateInputValue(id,index,text) {
    var from_val = $("#"+id+"_from").val();
    var to_val = $("#"+id+"_to").val();
    
    if(parseFloat(from_val) > parseFloat(to_val))  {
        notify('error','From '+text+' can not be greater than To '+text+' ');
        $("#"+id+"_to").val(from_val);
    }
}

let jsonBody = {};

const pushFilterIn = function (key, field = key) {
    const arr = [];
    $.each($("input[name='"+field+"[]']:checked"), function(){            
        arr.push($(this).val());
    });
    if(!arr.length) {
        return;
    }
    jsonBody[key] = arr.toString();
}
const pushFilterBtw = function(key, field = key) {
    const str_from = $("input[name='"+field+"_from']").val();
    let str_to = $("input[name='"+field+"_to']").val();

    if(!str_from && !str_to) {
        return;
    }

    if(field == 'carat') {
        str_to = (str_to == '6+') ? '100' : str_to;
    } else if(field == 'price') {
        str_to = (str_to == '1000000+') ? '10000000' : str_to;        
    }

    if(str_from.trim()!="" && str_to.trim()!="") {
        if(parseFloat(str_from) <= parseFloat(str_to)) {
            jsonBody[key] = str_from+"-"+str_to;
        }
    }
}

function getForm() {
    //var value_form = $('#form').serialize();

    const stock = $("input[name='stock']").val();
    jsonBody = {
        stock,
        page,
        limit,        
        sort_column,
        sort_type
    };

}

$(function () {
    $("#checkAll").click(function () {
        if ($("#checkAll").is(':checked')) {
            $(".tr_checkbox").prop("checked", true);
        } else {
            $(".tr_checkbox").prop("checked", false);
        }
    });
}); 

const checkEmpty = (val) => {
    return (val != null) ? val : '';
}

const checkDisc = (val) => {
    return (val > 0) ? '+' + val : val;
}

const pagination = (totalItems) => {
    let linkHtml = '';
    let totalPages = Math.ceil(totalItems / limit);

    if(page > 1) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page - 1})">Prev</a>`;        
    }
    for (let i = 1; i <= totalPages; i++) {
        if(i <= page + 2 && i > page - 3) {
            let activeClass = (page == i) ? 'active' : '';
            linkHtml += `<a href="javascript:void(0)" class="${activeClass}" onclick="onPaging(${i})">${i}</a>`;
        }
    }
    if(page < totalPages) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page + 1})">Next</a>`;        
    }
    document.getElementById('pagination').innerHTML = linkHtml;
}
const onPaging = (inPage) => {
    page = +inPage;

    loadMoreData();
}

function loadMoreData(){ 

    getForm();    

    $.ajax({         
        url: BASE_URL+"admin/product/data",
        method: "POST",
        data: jsonBody,
        dataType: "json",
        success: function(data){
            let html = "";
            const details = data.records; 
            const total_records = data.total; 
            const details_length = details.length;

            pagination(total_records);

            for(let i=0; i < details_length; i++)
            {  

                html += `<tr>`;
                html += `<td></td>`;
                html += `<td>${checkEmpty(details[i].title)}`;

                if(details[i].status == 'active') {
                    const shopUrl = `https://aristovintage.com/products/${details[i].handle}`;
                    html += `    <a href="${shopUrl}" target="_blank"><i class="fa fa-eye" title="View on Store"></i></a>`;
                }

                html += `</td>`;
                html += `<td>${checkEmpty(details[i].sku)}</td>`;
                html += `<td>${checkEmpty(details[i].product_type)}</td>`;
                html += `<td>${checkEmpty(details[i].inventory_quantity)}</td>`;

                html += `<td>`;
                if(details[i].status == 'active') {
                    html += `<span class="badge bg-success">Active</span>`;
                } else if(details[i].status == 'draft') {
                    html += `<span class="badge bg-info">Draft</span>`;
                } else if(details[i].status == 'archived') {
                    html += `<span class="badge bg-danger">Archived</span>`;
                }
                html += `</td>`;

                html += `<td><button onclick="details('${details[i].product_id}')" class="btn btn-info btn-sm"><i class="fa fa-book"></i> Details</button></td>`;
                
                html += `</tr>`;

            }

            /*<a href="${BASE_URL}admin/employee/edit/${details[i].product_id}" class="btn btn-primary btn-sm">
                    <i class="fa fa-edit"></i> Edit</a>*/

            if(newRequest) { 
                document.getElementById('total_records').innerHTML = total_records;
            }            
            //document.getElementById('add_data').insertAdjacentHTML('beforeend',html);
            document.getElementById('add_data').innerHTML = html;
            $("#list_div").show();
            $("#filter_div").hide();

            html = '';
            // offset = parseInt(offset)+parseInt(limit);
            // limit = 50;
            load = (total_records) ? true : false;

            if(!details_length) {
                if(newRequest) { 
                    $("#sticky-button").hide();
                    $("#list_section").hide();
                    $("#no_list_section").show();
                }
            } else {
                $("#sticky-button").show();
                $("#list_section").show();
                $("#no_list_section").hide();
            }
        },
        beforeSend: function () {            
            if(newRequest) {                
                $("#loading").show();
            }
        },
        complete: function () {
            $("#loading").hide();
        }
    });
}

const details = (product_id) => {

    $.ajax({         
        url: BASE_URL+"admin/product/details",
        method: "GET",
        data: { product_id },
        dataType: "json",
        success: function(data){
            let html = "";
            const details = data.records; 
            const images = data.images; 

            html += `<div class="row"><span class="title">Title:</span> <span>${checkEmpty(details[0].title)}</span></div>`;
            html += `<div class="row"><span class="title">Description:</span> <span>${checkEmpty(details[0].body_html)}</span></div>`;
            html += `<div class="row"><span class="title">Price:</span> <span>${checkEmpty(details[0].price)}</span></div>`;
            html += `<div class="row"><span class="title">Compare at Price:</span> <span>${checkEmpty(details[0].compare_at_price)}</span></div>`;
            html += `<div class="row"><span class="title">Cost per Item:</span> <span>${checkEmpty(details[0].cost)}</span></div>`;
            html += `<div class="row">
                <span class="title">Sku:</span> <span>${checkEmpty(details[0].sku)}</span></div>
                <div class="row"><span class="title">Barcode:</span> <span>${checkEmpty(details[0].barcode)}</span>
            </div>`;
            html += `<div class="row"><span class="title">Status:</span> <span>${checkEmpty(details[0].status)}</span></div>`;
            html += `<div class="row"><span class="title">Product type:</span> <span>${checkEmpty(details[0].product_type)}</span></div>`;
            html += `<div class="row"><span class="title">Inventory quantity:</span> <span>${checkEmpty(details[0].inventory_quantity)}</span></div>`;
            html += `<div class="row"><span class="title">Media:</span> <div class="image-container">`;
            
            images.forEach((el) => {
                html += `<div class="image"><img src="${el.src}" /> </div>`;
            });
            html += `</div></div>`;
            document.getElementById('details_modal_body').innerHTML = html;
            html = '';
            
        },
        beforeSend: function () {     
            $("#loading").show();
        },
        complete: function () {
            $("#loading").hide();
        }
    });

    $("#details_modal").modal('show');

}

function print(html)
{
    //alert(html);
    var mywindow = window.open();
    mywindow.document.write('<html><head><title>print stone</title>');            
    mywindow.document.write('</head><body >');
    mywindow.document.write(html);
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();

    return true;
}

function open_windows(src)
{   
    window.open(src, "Diamond", "width=800, height=800");
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function exportList()
{
    var stock_arr = [];
    $.each($("input[name='check_stock[]']:checked"), function(){            
        stock_arr.push($(this).val());
    });
    var stock_str=stock_arr.toString();
    var stock_type = $("input[name='stock_type']").val();

    if(stock_str)
    {
        location.href=BASE_URL+'export-diamond?stock='+stock_str   
    }
    else
    {
        alertify.confirm(SITENAME, 'Do You Want To Download All Record ?', 
        function(){ 
          location.href=BASE_URL+'export-diamond?stock=&stock_type='+stock_type   
        }, 
        function(){  });                
    } 
}

