const customRound = v => {
    let dec = (v % 1) * 100;   // decimal in 0–99 range
    return dec >= 50 ? Math.ceil(v) : v.toFixed(2);
};
$(document).ready(function(){
    $('#search_value_stock_id, #search_value_sh, #search_value_wt, #search_value_col, #search_value_cla, #search_value_cut, #search_value_pol, #search_value_sym, #search_value_fl, #search_value_lab').multiselect({
      nonSelectedText: 'Select',
      enableFiltering: true,
      enableCaseInsensitiveFiltering: true,
      buttonWidth:'100px',
      maxHeight:'450',
      includeSelectAllOption: true
     });

    disable_enable_background(false)
});
/********* Common Delete Function For Master ************/

    function delete_master_item(id, path)
    {
        var ans = confirm("Are you sure? You want to delete item.");

        if(ans == true)
        {
            var update_path = base_url+"master/masterctrl/"+path+"/"+id;

            ajaxCall('POST',update_path,'','',resp =>
            {
                if(resp == 2)
                    {
                        alert("You can not delete this item!");
                    }
                    else
                    {
                        $("#table_reload").load(window.location + " .table");
                        $("#count_reload").load(window.location + " #total_rows");
                        // window.location.reload();
                    }

            },
            errmsg =>
            {});
        }
    }

    function clear_search_keyword()
    {
        $("#search_keyword").val("");
    }


/***************************** /Exchange Rate Master ******************************/
    function add_update_exchange_rate_popup(exchange_rate_id)
    {
        let today = new Date().toISOString().split('T')[0];

        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="exchange_rate_form">';

        data += '<div class="form-group" style="padding: 15px;">';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += ' <input type="date" name="exchange_rate_date" class="form-control floating-input cust_search_ip" id="exchange_rate_date" value="'+today+'">';   
        data += '<label class="text-uppercase">Date</label>';
        data += '<small class="form-text text-muted helper-text" id="exchange_rate_date_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += ' <input type="number" class="form-control floating-input" id="exchange_rate_buying_rate" name="exchange_rate_buying_rate" value="" />';   
        data += '<label class="text-uppercase">Buying Rate</label>';
        data += '<small class="form-text text-muted helper-text" id="exchange_rate_buying_rate_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += '<input type="number" class="form-control floating-input" id="exchange_rate_selling_rate" name="exchange_rate_selling_rate" value="" />';  
        data += '<label class="text-uppercase">Selling Rate</label>';
        data += '<small class="form-text text-muted helper-text" id="exchange_rate_selling_rate_msg"></small>';
        data += '</div>';

        if (exchange_rate_id == 0)
        {
            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_exchange_rate(0)" style="width:100%">Submit</button></div>';
        }else{

            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_exchange_rate('+exchange_rate_id+')" style="width:100%">Update</button></div>';
        }

        data += '<div class="col-sm-2"><button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal" style="width:100%">Cancel</button></div>';
        data += '</div>';
        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(exchange_rate_id == 0){
            $(".modal-title-sm").html("Add Exchange Rate");
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_exchange_rate/"+exchange_rate_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                $(`#exchange_rate_date`).val(resp[0][`exchange_rate_date`]);
                $(`#exchange_rate_buying_rate`).val(resp[0][`exchange_rate_buying_rate`]);
                $(`#exchange_rate_selling_rate`).val(resp[0][`exchange_rate_selling_rate`]);
            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update Exchange Rate");
        }

        $("#popup_modal_sm").modal('show');
    }

   function add_exchange_rate(id) {
    var check = 1;

    if ($("#exchange_rate_date").val() == '') {
        $("#exchange_rate_date").css({'border-color':'red'});
        check = 0;
    } else {
        $("#exchange_rate_date").css({'border-color':'#CCC'});
    }

    if ($("#exchange_rate_buying_rate").val() == '') {
        $("#exchange_rate_buying_rate").css({'border-color':'red'});
        check = 0;
    } else {
        $("#exchange_rate_buying_rate").css({'border-color':'#CCC'});
    }

    if ($("#exchange_rate_selling_rate").val() == '') {
        $("#exchange_rate_selling_rate").css({'border-color':'red'});
        check = 0;
    } else {
        $("#exchange_rate_selling_rate").css({'border-color':'#CCC'});
    }

    if (check == 0) {
        display_alert_popup('err', 'Oh snap! You forgot to enter some information');
        $("body, html").animate({'scrollTop':0}, 1000);
        return;
    }

    var path = base_url + "master/masterctrl/exchange_rate_insert/" + id;
    var form_data = $("#exchange_rate_form").serialize();

    ajaxCall('POST', path, form_data, 'JSON', resp => {

        if(resp.status === 'success') {
            display_alert_popup('succ', id == 0 ? 'Successfully added!' : 'Successfully updated!');

            // Close popup if new
            if(id == 0) {
                $("#exchange_rate_form")[0].reset();
                $("#popup_modal_sm").animate({'scrollTop':0},1000);
            } else {
                // Updated existing EXCHANGE RATE
                $("#popup_modal_sm").animate({'scrollTop':0},1000);
            }

        } else if(resp.status === 'exists') {
            display_alert_popup('err', 'EXCHANGE RATE already exists!');
            $("#popup_modal_sm").animate({'scrollTop':0},1000);

        } else {
            display_alert_popup('warn', 'Database Error! Please try again later.');
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
        }

    }, errmsg => {
        display_alert_popup('warn', 'AJAX Error! Please try again.');
        console.error(errmsg);
    });
}

/***************************** /Exchange Rate Master ******************************/


/********************************* City Master *********************************/
    function add_update_city_popup(city_id)
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="city_form">';

        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">City Name</label>';
        data += '<div class="col-sm-5"><input type="text" name="city_name" class="form-control cust_search_ip" id="city_name"></div>';

        if (city_id == 0)
        {
            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_city(0)" style="width:100%">Submit</button></div>';
        }else{

            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_city('+city_id+')" style="width:100%">Update</button></div>';
        }

        data += '<div class="col-sm-2"><button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal" style="width:100%">Cancel</button></div>';
        data += '</div>';
        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(city_id == 0){
            $(".modal-title-sm").html("Add City");
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_city/"+city_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                $("#city_name").val(resp[0]['city_name']);
            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update City");
        }

        $("#popup_modal_sm").modal('show');
    }

    function add_city(id)
    {
        var check = 1;
        if($("#city_name").val() == '')
        {
            $("#city_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#city_name").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {

            var path = base_url+"master/masterctrl/city_insert/"+id;
            var form_data = $("#city_form").serialize();


            ajaxCall('POST',path,form_data,'JSON',resp =>
            {
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);

                        $("#city_form")[0].reset();
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                }
                else if(resp == 2)
                {
                    var msg = 'City is already exists!';
                    display_alert_popup('err',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Database Error ! Please try again letter';
                    display_alert_popup('warn',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }



            },errmsg =>{});
        }
    }

/********************************* /City Master *********************************/


/********************************* State Master *********************************/
    function add_update_state_popup(state_id)
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="state_form">';

        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">State Name</label>';
        data += '<div class="col-sm-9"><input type="text" name="state_name" class="form-control cust_search_ip" id="state_name"></div>';
        data += '</div>';
        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">State Code</label>';
        data += '<div class="col-sm-9"><input type="text" name="state_code" class="form-control cust_search_ip" id="state_code"></div>';
        data += '</div>';
        data += '<div class="form-group" style="float:right">';
        if (state_id == 0)
        {
            data += '<div class="col-sm-12"><button type="button" class="btn btn-success" onClick="add_state(0)">Submit</button> ';
        }else{

            data += '<div class="col-sm-12"><button type="button" class="btn btn-success" onClick="add_state('+state_id+')">Update</button> ';
        }

        data += '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Cancel</button></div>';
        data += '</div>';
        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(state_id == 0){
            $(".modal-title-sm").html("Add State");
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_state/"+state_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                $("#state_name").val(resp[0]['state_name']);
            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update State");
        }

        $("#popup_modal_sm").modal('show');
    }

    function add_state(id)
    {
        var check = 1;
        if($("#state_name").val() == '')
        {
            $("#state_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#state_name").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {

            var path = base_url+"master/masterctrl/state_insert/"+id;
            var form_data = $("#state_form").serialize();


            ajaxCall('POST',path,form_data,'JSON',resp =>
            {
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);

                        $("#state_form")[0].reset();
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                }
                else if(resp == 2)
                {
                    var msg = 'State is already exists!';
                    display_alert_popup('err',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Database Error ! Please try again letter';
                    display_alert_popup('warn',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }



            },errmsg =>{});
        }
    }

/********************************* /State Master *********************************/


/********************************* Country Master *********************************/
    function add_update_country_popup(country_id)
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="country_form">';

        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">Country Name</label>';
        data += '<div class="col-sm-9"><input type="text" name="country_name" class="form-control cust_search_ip" id="country_name"></div>';
        data += '</div>';
        data += '<div class="form-group" style="float:right">';
        if (country_id == 0)
        {
            data += '<div class="col-sm-12"><button type="button" class="btn btn-success" onClick="add_country(0)">Submit</button> ';
        }else{

            data += '<div class="col-sm-12"><button type="button" class="btn btn-success" onClick="add_country('+country_id+')">Update</button> ';
        }

        data += '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Cancel</button></div>';
        data += '</div>';
        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(country_id == 0){
            $(".modal-title-sm").html("Add Country");
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_country/"+country_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                $("#country_name").val(resp[0]['country_name']);
            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update Country");
        }

        $("#popup_modal_sm").modal('show');
    }

    function add_country(id)
    {
        var check = 1;
        if($("#country_name").val() == '')
        {
            $("#country_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#country_name").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {

            var path = base_url+"master/masterctrl/country_insert/"+id;
            var form_data = $("#country_form").serialize();


            ajaxCall('POST',path,form_data,'JSON',resp =>
            {
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);

                        $("#country_form")[0].reset();
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                }
                else if(resp == 2)
                {
                    var msg = 'Country is already exists!';
                    display_alert_popup('err',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Database Error ! Please try again letter';
                    display_alert_popup('warn',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }



            },errmsg =>{});
        }
    }

/********************************* /Country Master *********************************/

/********************************* Hsn Master *********************************/
    function add_update_hsn_popup(hsn_id)
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="hsn_form">';

        data += '<div class="form-group" style="padding: 15px;">';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += ' <input type="text" name="hsn_code" class="form-control floating-input cust_search_ip" id="hsn_code">';   
        data += '<label class="text-uppercase">Hsn Code</label>';
        data += '<small class="form-text text-muted helper-text" id="hsn_code_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += ' <input type="number" class="form-control floating-input" id="hsn_sgst_per" name="hsn_sgst_per" value="0.00" onkeyup="calculate_gst()" placeholder=" " autocomplete="off"/>';   
        data += '<label class="text-uppercase">sgst per</label>';
        data += '<small class="form-text text-muted helper-text" id="hsn_sgst_per_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += '<input type="number" class="form-control floating-input" id="hsn_cgst_per" name="hsn_cgst_per" value="0.00" readonly/>';  
        data += '<label class="text-uppercase">cgst per</label>';
        data += '<small class="form-text text-muted helper-text" id="hsn_cgst_per_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += '<input type="number" class="form-control floating-input" id="hsn_igst_per" name="hsn_igst_per" value="0.00" readonly />';
        data += '<label class="text-uppercase">igst per</label>';
        data += '<small class="form-text text-muted helper-text" id="hsn_igst_per_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-8 col-lg-8 floating-label">';
        data += ' <input type="text" name="hsn_description" class="form-control floating-input cust_search_ip" id="hsn_description">';   
        data += '<label class="text-uppercase">Description</label>';
        data += '<small class="form-text text-muted helper-text" id="hsn_description_msg"></small>';
        data += '</div>';

        data += '<div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">';
        data += '</div>';


        if (hsn_id == 0)
        {
            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_hsn(0)" style="width:100%">Submit</button></div>';
        }else{

            data += '<div class="col-sm-2"><button type="button" class="btn btn-success" onClick="add_hsn('+hsn_id+')" style="width:100%">Update</button></div>';
        }

        data += '<div class="col-sm-2"><button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal" style="width:100%">Cancel</button></div>';
        data += '</div>';
        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(hsn_id == 0){
            $(".modal-title-sm").html("Add Hsn");
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_hsn/"+hsn_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                $("#hsn_code").val(resp[0]['hsn_code']);
                $(`#hsn_sgst_per`).val(resp[0][`hsn_sgst_per`]);
                $(`#hsn_cgst_per`).val(resp[0][`hsn_cgst_per`]);
                $(`#hsn_igst_per`).val(resp[0][`hsn_igst_per`]);
                $(`#hsn_description`).val(resp[0][`hsn_description`]);
            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update Hsn");
        }

        $("#popup_modal_sm").modal('show');
    }

    const calculate_gst = () => {
        let sgst_per = $("#hsn_sgst_per").val();
        let igst_per = parseFloat(sgst_per) * 2;
        if (isNaN(igst_per) || igst_per == "") igst_per = 0;
        $("#hsn_cgst_per").val(sgst_per);
        $("#hsn_igst_per").val(igst_per.toFixed(2));
    };

   function add_hsn(id) {
    var check = 1;

    if ($("#hsn_code").val() == '') {
        $("#hsn_code").css({'border-color':'red'});
        check = 0;
    } else {
        $("#hsn_code").css({'border-color':'#CCC'});
    }

    if ($("#hsn_sgst_per").val() == '') {
        $("#hsn_sgst_per").css({'border-color':'red'});
        check = 0;
    } else {
        $("#hsn_sgst_per").css({'border-color':'#CCC'});
    }

    if (check == 0) {
        display_alert_popup('err', 'Oh snap! You forgot to enter some information');
        $("body, html").animate({'scrollTop':0}, 1000);
        return;
    }

    var path = base_url + "master/masterctrl/hsn_insert/" + id;
    var form_data = $("#hsn_form").serialize();

    ajaxCall('POST', path, form_data, 'JSON', resp => {

        if(resp.status === 'success') {
            display_alert_popup('succ', id == 0 ? 'Successfully added!' : 'Successfully updated!');

            // Close popup if new
            if(id == 0) {
                $("#hsn_form")[0].reset();
                $("#popup_modal_sm").animate({'scrollTop':0},1000);
            } else {
                // Updated existing HSN
                $("#popup_modal_sm").animate({'scrollTop':0},1000);
            }

        } else if(resp.status === 'exists') {
            display_alert_popup('err', 'HSN already exists!');
            $("#popup_modal_sm").animate({'scrollTop':0},1000);

        } else {
            display_alert_popup('warn', 'Database Error! Please try again later.');
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
        }

    }, errmsg => {
        display_alert_popup('warn', 'AJAX Error! Please try again.');
        console.error(errmsg);
    });
}

/********************************* /Hsn Master *********************************/

/********************************* Bank Rate Master *********************************/
    function add_update_bank_rate_popup(bank_rate_id)
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="bank_rate_form">';

        data += '<div class="form-group floating-form">';
        data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
        data += '<input type="text" name="bank_rate_date" class="form-control floating-input" id="bank_rate_date" placeholder=" " autocomplete="off">';
        data += '<label for="inputEmail3">Date</label>';
        data += '</div>';

        data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
        data += '<input type="number" step="0.01" name="bank_rate" value="0.00" class="form-control floating-input" id="bank_rate" placeholder=" " autocomplete="off">';
        data += '<label for="inputEmail3">Rate</label>';
        data += '</div>';

        data += '</div>';

        data += '<div class="form-group floating-form">';

        if (bank_rate_id == 0)
        {
            data += '<div class="col-sm-2 col-sm-offset-8">';
            data += '<button type="button" class="btn btn-success" onClick="add_bank_rate(0)" style="width:100%">Submit</button>';
            data += '</div>';
        }else{

            data += '<div class="col-sm-2 col-sm-offset-8">';
            data += '<button type="button" class="btn btn-success" onClick="add_bank_rate('+bank_rate_id+')" style="width:100%">Update</button>';
            data += '</div>';
        }

        data += '<div class="col-sm-2">';
        data += '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal" style="width:100%">Cancel</button>';
        data += '</div>';
        data += '</div>';

        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);
        if(bank_rate_id == 0){
            $(".modal-title-sm").html("Add Bank Rate");
            $("#bank_rate_date").datepicker({
                format: 'dd-mm-yyyy',
                todayHighlight: true,
            }).datepicker("setDate", new Date());
        }
        else
        {
            var update_path = base_url+"master/masterctrl/get_single_bank_rate/"+bank_rate_id;

            ajaxCall('POST',update_path,'','JSON',resp =>
            {
                // console.log(resp)
                if(resp['is_exists'] > 0)
                {
                    $("#bank_rate_date").val(resp['bank_rate_data'][0]['bank_rate_date'].split('-').reverse().join('-'));
                    $("#bank_rate_date").prop('readonly', 'readonly');
                    $("#bank_rate").val(resp['bank_rate_data'][0]['bank_rate']);
                    $("#bank_rate").prop('readonly', 'readonly');
                }
                else
                {
                    $("#bank_rate_date").val(resp['bank_rate_data'][0]['bank_rate_date'].split('-').reverse().join('-'));
                    $("#bank_rate").val(resp['bank_rate_data'][0]['bank_rate']);

                    $("#bank_rate_date").datepicker({
                        format: 'dd-mm-yyyy',
                        todayHighlight: true,
                    }).datepicker("setDate", new Date(resp['bank_rate_data'][0]['bank_rate_date']));
                }

            },
            errmsg =>
            {});

            $(".modal-title-sm").html("Update Bank Rate");
        }

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


    }

    function add_bank_rate(id)
    {
        var check = 1;
        if($("#bank_rate_date").val() == '')
        {
            $("#bank_rate_date").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#bank_rate_date").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {

            var path = base_url+"master/masterctrl/add_update_bank_rate/"+id;
            var form_data = $("#bank_rate_form").serialize();


            ajaxCall('POST',path,form_data,'JSON',resp =>
            {
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);

                        $("#bank_rate_form")[0].reset();
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                        $("#bank_rate_date").datepicker("setDate", new Date());
                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                }
                else if(resp == 2)
                {
                    var msg = 'Date is already exists!';
                    display_alert_popup('err',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Database Error ! Please try again letter';
                    display_alert_popup('warn',msg);

                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }



            },errmsg =>{});
        }
    }

/********************************* /Bank Rate Master *********************************/


/********************************* User Master *********************************/

    function add_update_user_popup(user_id){

        var path = base_url+"master/masterctrl/get_role";

        /*common ajax call written in public/assets/js/common.js*/
        ajaxCall('POST',path,'','JSON',resp =>
        {
            var data = '';

            data += '<div class="alert_msg_popup"></div>';
            data += '<div class="row">';
            data += '<div class="col-md-12">'
            data += '<form class="form-horizontal" id="user_form">';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">User Name<span style="color:red">*</span></label><div class="col-sm-9"><input type="text" name="user_name" class="form-control" id="user_name"></div></div>';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Full Name<span style="color:red">*</span></label><div class="col-sm-9"><input type="text" name="user_full_name" class="form-control" id="user_full_name"></div></div>';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Password<span style="color:red">*</span></label><div class="col-sm-9"><input type="password" name="user_password" class="form-control" id="user_password"></div></div>';

            if(session_role == 1)
            {
                data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Role<span style="color:red">*</span></label><div class="col-sm-9">';
                data += '<select name="user_role_id" id="user_role_id" class="form-control">';

                $.each(resp['role'], function(index, value){
                    data += '<option value="'+index+'">'+value+'</option>';
                });

                data += '</select>';
                data += '</div></div>';
            }

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Address</label><div class="col-sm-9"><textarea name="user_address" class="form-control" id="user_address"></textarea></div></div>';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Telephone</label><div class="col-sm-9"><input type="text" name="user_telephone" class="form-control" id="user_telephone"></div></div>';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Mobile</label><div class="col-sm-9"><input type="text" name="user_mobile" class="form-control" id="user_mobile"></div></div>';

            data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Email</label><div class="col-sm-9"><input type="email" name="user_email" class="form-control" id="user_email"></div></div>';

            data += '</form>';
            data += '</div>';
            data += '</div>';

            $(".modal-body-sm").html(data);

            var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

            if(user_id == 0)
            {
                sbt_btn += '<button type="button" class="btn btn-success" onClick="add_user(0)">Submit</button>';
                $(".modal-title-sm").html("Add User");
            }
            else
            {
                var update_path = base_url+"master/masterctrl/get_single_user/"+user_id;


                ajaxCall('POST',update_path,'','JSON',resp =>
                {
                    $("#user_name").val(resp[0]['user_name']);
                    $("#user_full_name").val(resp[0]['user_full_name']);
                    if(session_role == 1)
                    {
                        $("#user_role_id").val(resp[0]['user_role_id']);
                    }
                    $("#user_address").html(resp[0]['user_address']);
                    $("#user_mobile").val(resp[0]['user_mobile']);
                    $("#user_telephone").val(resp[0]['user_telephone']);
                    $("#user_email").val(resp[0]['user_email']);



                },errmsg =>{});

                sbt_btn += '<button type="button" class="btn btn-success" onClick="add_user('+user_id+')">Submit</button>';

                $(".modal-title-sm").html("Update User");
            }

            $(".modal-footer-sm").html(sbt_btn);


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

        },errmsg =>{});

    }

    function add_user(id)
    {
        var check = 1;

        if($("#user_name").val() == '')
        {
            $("#user_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#user_name").css({'border-color':'#CCC'});
        }

        if(id == 0)
        {
            if($("#user_password").val() == 0)
            {
                $("#user_password").css({'border-color':'red'});
                check = 0;
            }
            else
            {
                $("#user_password").css({'border-color':'#CCC'});
            }
        }

        if($("#user_full_name").val() == '')
        {
            $("#user_full_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#user_full_name").css({'border-color':'#CCC'});
        }
        // console.log($("#user_role_id").val())
        if($("#user_role_id").val() == 0 || $("#user_role_id").val() == null)
        {
            $("#user_role_id").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#user_role_id").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);

            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {
            var path = base_url+"master/masterctrl/user_insert/"+id;
            var form_data = $("#user_form").serialize();


            ajaxCall('POST',path,form_data,'JSON',resp =>
            {
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);
                        $("#user_form")[0].reset();
                        $("body, html").animate({'scrollTop':0},1000);
                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);
                        $("body, html").animate({'scrollTop':0},1000);
                    }
                }
                else if(resp == 2)
                {
                    var msg = 'User is already exists!';
                    display_alert_popup('err',msg);
                    $("body, html").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Database Error ! Please try again later';
                    display_alert_popup('warn',msg);
                    $("body, html").animate({'scrollTop':0},1000);
                }


            },errmsg =>{});
        }
    }
/********************************* /User Master *********************************/


/********************************* Account Master *********************************/
    function validate_multiple_img(element) {
        var element_id      = "#" + element.id;
        var len             = $(element_id).get(0).files.length;
        var validFileTypes  = ["image/gif", "image/jpeg", "image/png", "application/pdf"]; 
        var check           = 0;

        if (len > 5) {
            alert('Maximum file selection is five only');
            check = 1;
        } else {
            for (var i = 0; i < len; i++) {
                var fileType = $(element_id).get(0).files[i]['type'];

                // console.log($.inArray(fileType, validFileTypes));

                if ($.inArray(fileType, validFileTypes) < 0) {
                    alert('Only Images (gif, jpg, png) or PDF are allowed. Please select again.');
                    check = 1;
                    break;
                }
            }
        }

        if (check != 0) {
            $(element_id).val(''); // reset input
        }
    }

    function buildFilePreview(fileName, basePath, slotId, grp_id) {
        let ext = fileName.split('.').pop().toLowerCase();

        var fileUrl;
        if(grp_id == 6){
            fileUrl = basePath + '/supplier_kyc/' + fileName;
        }else{
            fileUrl = basePath + '/customer_kyc/' + fileName;
        }

        let html = '<td id="acc_kyc_img_' + slotId + '">';
        html += '<span><a href="' + fileUrl + '" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span><br>';
        html += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image1(' + slotId + ')" title="Remove"></span><br>';

        if (['jpg','jpeg','png','gif'].includes(ext)) {
            // Show image preview
            html += '<img class="img-responsive btn btn-basic pan" src="' + fileUrl + '" ' +
                    'data-big="' + fileUrl + '" style="width: 100px; height: 100px;" ' +
                    'onclick="zoom()" title="Double click to zoom in and out">';
        } else if (ext === 'pdf') {
            // PDF Preview placeholder (canvas)
            let canvasId = 'pdf-canvas-' + slotId;
            html += '<a href="' + fileUrl + '" target="_blank" title="Open PDF">' +
                    '<canvas id="' + canvasId + '" style="width:100px; height:100px; border:1px solid #ccc;"></canvas>' +
                    '</a>';

            // After rendering table, render PDF thumbnail
            setTimeout(function() {
                renderPdfThumbnail(fileUrl, canvasId);
            }, 100);
        }

        html += '<input type="hidden" name="kyc_photo[]" value="' + fileName + '"/>';
        html += '</td>';
        return html;
    }


    function renderPdfThumbnail(url, canvasId) {
        pdfjsLib.getDocument(url).promise.then(function(pdf) {
            pdf.getPage(1).then(function(page) {
                let scale = 0.2; // smaller = smaller preview
                let viewport = page.getViewport({ scale: scale });

                let canvas = document.getElementById(canvasId);
                let context = canvas.getContext('2d');

                canvas.width = viewport.width;
                canvas.height = viewport.height;

                let renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                page.render(renderContext);
            });
        });
    }


    function add_update_account_popup(acc_id, type){

        var data = '';

        var path = base_url+"master/masterctrl/get_account_assets";


        ajaxCall('POST',path,'','JSON',resp =>
        {
            data += '<div class="alert_msg_popup"></div>';
            data += '<div class="row">';
            data += '<div class="col-md-12">';
            data += '<form class="form-horizontal" id="account_form">';

            if(type == 5)
            {
            data += '<div class="form-group floating-form">';

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_diamond_type" name="acc_diamond_type[]" multiple="multiple">';
            data += '<option value="1">Natural</option>';
            data += '<option value="2">Labgrown</option>';
            data += '<option value="3">Colour Stone</option>';
            data += '<option value="4">Jewellery Mounting</option>';
            data += '</select>';
            data += '<label for="inputEmail3">Type of Diamond</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_name" class="form-control floating-input" id="acc_name" placeholder="" autocomplete="off">';
            data += '<label for="inputEmail3" >Company Name<span style="color:red">*</span></label>';
            data += '</div>'; //col-sm-10
            
            data += '</div>';
            }
            else if(type == 6)
            {
            data += '<div class="form-group floating-form">';

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_diamond_type" name="acc_diamond_type[]" multiple="multiple">';
            data += '<option value="1">Natural</option>';
            data += '<option value="2">Labgrown</option>';
            data += '<option value="3">Colour Stone</option>';
            data += '</select>';
            data += '<label for="inputEmail3">Type of Diamond</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" name="acc_broker_id" id="acc_broker_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['broker_data'], function(index, value){

            data += '<option value="'+value['broker_id']+'">'+value['broker_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">Broker<span style="color:red">*</span></label>';
            data += '</div>'; //col-sm-4
            
            data += '</div>';
            }
            else if (type == 23)
            {
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_name" class="form-control floating-input" id="acc_name" placeholder="" autocomplete="off">';
            data += '<label for="inputEmail3" >Broker Name<span style="color:red">*</span></label></div>';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_mobile" class="form-control floating-input" id="acc_mobile" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Broker Mobile</label>';
            data += '</div>';
            data += '</div>'; //col-sm-4
            }
            if(type == 5)
            {
            data += '<div class="form-group floating-form">';

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" name="acc_broker_id" id="acc_broker_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['broker_data'], function(index, value){

            data += '<option value="'+value['broker_id']+'">'+value['broker_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">Broker</label>';
            data += '</div>'; //col-sm-4


            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_owner" class="form-control floating-input" id="acc_owner" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3" >Owner Name</label>';
            data += '</div>'; //col-sm-4

            data += '</div>'; //form-group

            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_mobile" class="form-control floating-input" id="acc_mobile" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Owner Mobile</label>';
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
            }
            data += '<div class="form-group floating-form">';


            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_contact" class="form-control floating-input" id="acc_contact" placeholder=" " autocomplete="off">';
            if(type == 5)
            {
            data += '<label for="inputEmail3" >Autorised Person Name</label>';
            }
            else if(type == 23)
            {
             data += '<label for="inputEmail3" >Associate Person Name</label>';
            }
            else if(type == 6)
            {
             data += '<label for="inputEmail3" >Supplier Name</label>';
            }
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_aumobile" class="form-control floating-input" id="acc_aumobile" placeholder=" " autocomplete="off">';
            if(type == 5)
            {
            data += '<label for="inputEmail3">Authorised Person Mobile</label>';
            }
            else if(type == 23)
            {
             data += '<label for="inputEmail3">Associate Person Mobile</label>';
            }
            else if(type == 6)
            {
             data += '<label for="inputEmail3" >Supplier Mobile</label>';
            }
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group

            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_address" class="form-control floating-input" id="acc_address" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Address</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" name="acc_city_id" id="acc_city_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['city_data'], function(index, value){

            data += '<option value="'+value['city_id']+'">'+value['city_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">City</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 floating-label">';
            data += '<select class="form-control floating-select" name="acc_state_id" id="acc_state_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['state_data'], function(index, value){

            data += '<option value="'+value['state_id']+'">'+value['state_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">State</label>';
            data += '</div>'; //col-sm-4

             data += '<div class="col-sm-2 floating-label">';
            data += '<select class="form-control floating-select" name="acc_country_id" id="acc_country_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['country_data'], function(index, value){

            data += '<option value="'+value['country_id']+'">'+value['country_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">Country</label>';
            data += '</div>'; //col-sm-4

            data += '</div>'; //form-group
            if(type == 5)
            {
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_tel_1" class="form-control floating-input" id="acc_tel_1" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Q.B.C Mobile</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_tel_2" class="form-control floating-input" id="acc_tel_2" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Q.B.C Telephone </label>';
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
            }
            else if(type == 23)
            {
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_party1" class="form-control floating-input" id="acc_party1" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Party 1</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_party2" class="form-control floating-input" id="acc_party2" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Party 2</label>';
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
            }
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="hidden" name="acc_website" id="acc_website">';
            data += '<input type="text" name="acc_ref" class="form-control floating-input" id="acc_ref" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Refer By</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_ref2" class="form-control floating-input" id="acc_ref2" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Refer By 2</label>';
            data += '</div>';
            data += '</div>'; //col-sm-4

            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_email" class="form-control floating-input" id="acc_email" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Email</label>';
            data += '</div>'; //col-sm-4
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_status" name="acc_status">';
            data += '<option value="GOOD">GOOD</option>';
            data += '<option value="LIMITED">LIMITED</option>';
            data += '<option value="BLACKLISTED">BLACKLISTED</option>';
            data += '</select>';
            if(type == 5)
            {
            data += '<label for="inputEmail3">Company Status</label>';
            }
            else if(type == 23)
            {
             data += '<label for="inputEmail3">Broker Status</label>';
            }
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_type" name="acc_type">';
            data += '<option value="0">PLEASE SELECT</option>';
            data += '<option value="1">WITHIN STATE</option>';
            data += '<option value="2">OUTSIDE STATE</option>';
            data += '</select>';
            data += '<label for="inputEmail3">Type<span style="color : red;">*</span></label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 floating-label">';
            data += '<input type="hidden" name="acc_fax" id="acc_fax">';
            data += '<select class="form-control floating-select" id="acc_kyc" name="acc_kyc">';
            data += '<option value="0">NO</option>';
            data += '<option value="1">YES</option>';
            data += '</select>';
            data += '<label for="inputEmail3">KYC</label>';
            data += '</div>'; //col-sm-4



            if(type == 5)
            {
                data += '<div id="kyc_section" style="display:none;">';
                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="file" multiple="multiple" class="form-control floating-input" id="kyc_img" name="kyc_img[]" value="" placeholder=" " autocomplete="off" onchange="validate_multiple_img(this)" />';
                data += '<label for="inputEmail3">Document</label>';

                data += '<div class="col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 floating-label" id="kyc_img_preview">';

                data += '</div>'; //col-sm-4
                data += '</div>';
                data += '</div>'; // kyc_section


                data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_gst" class="form-control floating-input" id="acc_gst" placeholder=" " autocomplete="off">';
                data += '<label for="inputEmail3">GST</label>';
                data += '</div>';//col-sm-4
                data += '<div class="col-sm-2 floating-label">';
                data += '<input type="text" name="acc_pan" class="form-control floating-input" id="acc_pan" placeholder autocomplete="off">';
                data += '<label for="inputEmail3">PAN</label>';
                data += '</div>';//col-sm-4
                data += '<input type="hidden" name="acc_grp_id" id="acc_grp_id" value="5">';
            }
            else if(type == 6)
            {
                
                data += '<div id="kyc_section" style="display:none;">';
                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="file" multiple="multiple" class="form-control floating-input" id="kyc_img" name="kyc_img[]" value="" placeholder=" " autocomplete="off" onchange="validate_multiple_img(this)" />';
                data += '<label for="inputEmail3">Document</label>';

                data += '<div class="col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 floating-label" id="kyc_img_preview">';

                data += '</div>'; //col-sm-4
                data += '</div>';
                data += '</div>'; // kyc_section

                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_gst" class="form-control floating-input" id="acc_gst" placeholder=" " autocomplete="off">';
                data += '<label for="inputEmail3">GST</label>';
                data += '</div>';//col-sm-4

                data += '<input type="hidden" name="acc_grp_id" id="acc_grp_id" value="6">';
            }
            else if(type == 23)
            {
                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_pan" class="form-control floating-input" id="acc_pan" placeholder autocomplete="off">';
                data += '<label for="inputEmail3">PAN</label>';
                data += '</div>';//col-sm-4

                data += '<input type="hidden" name="acc_grp_id" id="acc_grp_id" value="23">';
            }
            data += '</div>'; //form-group

            if(type == 23)
            {
                data += '<div class="form-group floating-form" >';
                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="file" multiple="multiple" class="form-control floating-input" id="broker_img" name="broker_img[]" value="" placeholder=" " autocomplete="off" onchange="validate_multiple_img(this)" />';
                data += '<label for="inputEmail3">Photo</label>';
                data += '</div>'; //col-sm-4
                data += '</div>'; //form-group

                data += '<div class="form-group floating-form">';
                data += '<div class="col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 floating-label" id="brk_img_preview">';

                data += '</div>'; //form-group
            }

            data += '<div class="form-group floating-form">';

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_remark" class="form-control floating-input" id="acc_remark" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Remark</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_billing_address" class="form-control floating-input" id="acc_billing_address" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Address</label>';
            data += '</div>'; //col-sm-4

            if(type == 5 || type == 6)
            {
               // Heading
                data += '<div class="col-sm-12" style="margin-left: 59px; margin-bottom: 10px;">';
                data += '<label>Terms</label>'; // main heading/label
                data += '</div>';

                // First text field
                data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_days" class="form-control floating-input" id="acc_days" placeholder="" autocomplete="off">';
                data += '<label for="acc_days">Days</label>';
                data += '</div>';

                // Second text field
                data += '<div class="col-sm-2 floating-label">';
                data += '<input type="number" name="acc_discount" class="form-control floating-input" id="acc_discount" placeholder="" autocomplete="off">';
                data += '<label for="acc_discount">Discount</label>';
                data += '</div>';
            }

              //account status
               data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
               data += '<select class="form-control floating-select" id="acc_status1" name="acc_status1">';
               data += '<option value="1">ACTIVE</option>';
               data += '<option value="0">INACTIVE</option>';
               data += '</select>';
               data += '<label for="inputEmail3">Account Status</label></div>';


            if(type == 5 || type == 6)
            {
               // Heading
                data += '<div class="col-sm-12" style="margin-left: 59px; margin-bottom: 10px;">';
                data += '<label>Bank Details</label>'; // main heading/label
                data += '</div>';

                data += '<div class="col-sm-3 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_account_no" class="form-control floating-input" id="acc_account_no" placeholder="" autocomplete="off">';
                data += '<label for="acc_account_no">Account No.</label>';
                data += '</div>';

                data += '<div class="col-sm-3 floating-label">';
                data += '<input type="text" name="acc_bank_name" class="form-control floating-input" id="acc_bank_name" placeholder="" autocomplete="off">';
                data += '<label for="acc_bank_name">Bank Name</label>';
                data += '</div>';

                data += '<div class="col-sm-3 floating-label">';
                data += '<input type="text" name="acc_bank_branch" class="form-control floating-input" id="acc_bank_branch" placeholder="" autocomplete="off">';
                data += '<label for="acc_bank_branch">Bank Branch</label>';
                data += '</div>';

                data += '<div class="col-sm-3 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_ifsc_code" class="form-control floating-input" id="acc_ifsc_code" placeholder="" autocomplete="off">';
                data += '<label for="acc_ifsc_code">IFSC Code</label>';
                data += '</div>';

                data += '<div class="col-sm-3 floating-label">';
                data += '<input type="text" name="acc_holder_name" class="form-control floating-input" id="acc_holder_name" placeholder="" autocomplete="off">';
                data += '<label for="acc_holder_name">Account Holder Name</label>';
                data += '</div>';

                data += '<div class="col-sm-3 floating-label">';
                data += '<input type="text" name="acc_swift_code" class="form-control floating-input" id="acc_swift_code" placeholder="" autocomplete="off">';
                data += '<label for="acc_swift_code">Swift Code</label>';
                data += '</div>';
            }


            data += '</form>';
            data += '</div>'; // col-md-12
            data += '</div>'; // row

            $(".modal-body").html(data);

            $('#acc_diamond_type').multiselect({
                includeSelectAllOption: true,
                buttonWidth: '100%',
                nonSelectedText: 'Select'
            });

            $(document).on('change', '#acc_kyc', function() {
                if ($(this).val() == '1') { // YES
                    $('#kyc_section').css('display', 'block'); // show
                } else { // NO
                    $('#kyc_section').css('display', 'none');  // hide
                    $('#kyc_img_preview').html('');                      // clear previews
                    $('#kyc_img').val('');                               // reset file input
                }
            });

            var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

            if(acc_id == 0)
            {
                sbt_btn += '<button type="button" class="btn btn-success" onClick="add_account(0)">Submit</button>';

                $(".modal-title").html("Add Account");
            }
            else
            {

                var update_path = base_url+"master/masterctrl/get_single_account/"+acc_id;


                ajaxCall('POST',update_path,'','JSON',resp =>
                {
                    // set diamond type selections
                    let selectedDiamonds = resp['acc_data'][0]['acc_diamond_type']; // "1,2,3"
                    if (selectedDiamonds) {
                        let arr = selectedDiamonds.split(",");
                        $("#acc_diamond_type").val(arr);
                        $("#acc_diamond_type").multiselect('refresh');  // only if using bootstrap-multiselect
                    }

                    $("#acc_name").val(resp['acc_data'][0]['acc_name']);
                    $("#acc_broker_id").val(resp['acc_data'][0]['acc_broker_id']);
                    $("#acc_owner").val(resp['acc_data'][0]['acc_owner']);
                    $("#acc_grp_id").val(resp['acc_data'][0]['acc_grp_id']);
                    $("#acc_city_id").val(resp['acc_data'][0]['acc_city_id']);
                    $("#acc_state_id").val(resp['acc_data'][0]['acc_state_id']);
                    $("#acc_country_id").val(resp['acc_data'][0]['acc_country_id']);
                    $("#acc_contact").val(resp['acc_data'][0]['acc_contact']);
                    $("#acc_address").val(resp['acc_data'][0]['acc_address']);
                    $("#acc_tel_1").val(resp['acc_data'][0]['acc_tel_1']);
                    $("#acc_tel_2").val(resp['acc_data'][0]['acc_tel_2']);
                    $("#acc_fax").val(resp['acc_data'][0]['acc_fax']);
                    $("#acc_ref").val(resp['acc_data'][0]['acc_ref']);
                    $("#acc_ref2").val(resp['acc_data'][0]['acc_ref2']);
                    $("#acc_party1").val(resp['acc_data'][0]['acc_party1']);
                    $("#acc_party2").val(resp['acc_data'][0]['acc_party2']);
                    $("#acc_mobile").val(resp['acc_data'][0]['acc_mobile']);
                    $("#acc_aumobile").val(resp['acc_data'][0]['acc_aumobile']);
                    $("#acc_email").val(resp['acc_data'][0]['acc_email']);
                    $("#acc_website").val(resp['acc_data'][0]['acc_website']);
                    $("#acc_kyc").val(resp['acc_data'][0]['acc_kyc']);
                    $("#acc_status").val(resp['acc_data'][0]['acc_status']);
                    $("#acc_status1").val(resp['acc_data'][0]['acc_status1']);

                    $("#acc_account_no").val(resp['acc_data'][0]['acc_account_no']);
                    $("#acc_bank_name").val(resp['acc_data'][0]['acc_bank_name']);
                    $("#acc_bank_branch").val(resp['acc_data'][0]['acc_bank_branch']);
                    $("#acc_ifsc_code").val(resp['acc_data'][0]['acc_ifsc_code']);
                    $("#acc_holder_name").val(resp['acc_data'][0]['acc_holder_name']);
                    $("#acc_swift_code").val(resp['acc_data'][0]['acc_swift_code']);

                    if(resp['acc_data'][0]['acc_days'] != 0){
                        $("#acc_days").val(resp['acc_data'][0]['acc_days']);
                    }
                    $("#acc_discount").val(resp['acc_data'][0]['acc_discount']);
                    $("#acc_type").val(resp['acc_data'][0]['acc_type']);
                    $("#acc_gst").val(resp['acc_data'][0]['acc_gst']);
                    $("#acc_pan").val(resp['acc_data'][0]['acc_pan']);
                    $("#acc_billing_address").val(resp['acc_data'][0]['acc_billing_address']);

                    if (resp['acc_data'][0]['acc_kyc'] == '1') { // YES
                        $('#kyc_section').css('display', 'block'); // show
                    } else { // NO
                        $('#kyc_section').css('display', 'none');  // hide
                        // $('#kyc_img_preview').html('');                      // clear previews
                        // $('#kyc_img').val('');                               // reset file input
                    }
                    
                    var data1 = '';
                    data1 += '<table cellspacing="3" cellpadding="3">';
                    data1 += '<tr>';

                    if(resp['acc_data'][0]['acc_brk_img_1'] != '')
                    {
                        data1 += '<td id="acc_brk_img_1">';
                        data1 += '<span><a href="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_1']+'" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span></br>';
                        data1 += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image(1)" title="Remove"></span></br>';
                        data1 += '<img class="img-responsive btn btn-basic pan" src="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_1']+'" data-big="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_1']+'" style="width: 100; height: 100px;" onclick="zoom()" title="Double click to zoom in and out">';
                        data1 += '<input type="hidden" name="broker_photo[]" value="'+resp['acc_data'][0]['acc_brk_img_1']+'"/>';

                        data1 += '</td>'
                    }

                    if(resp['acc_data'][0]['acc_brk_img_2'] != '')
                    {
                        data1 += '<td id="acc_brk_img_2">';
                        data1 += '<span><a href="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_2']+'" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span></br>';
                        data1 += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image(2)" title="Remove"></span></br>';
                        data1 += '<img class="img-responsive btn btn-basic pan" src="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_2']+'" data-big="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_2']+'" style="width: 100; height: 100px;" onclick="zoom()" title="Double click to zoom in and out">';
                        data1 += '<input type="hidden" name="broker_photo[]" value="'+resp['acc_data'][0]['acc_brk_img_2']+'"/>';
                        data1 += '</td>'
                    }

                    if(resp['acc_data'][0]['acc_brk_img_3'] != '')
                    {
                        data1 += '<td id="acc_brk_img_3">';
                        data1 += '<span><a href="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_3']+'" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span></br>';
                        data1 += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image(3)" title="Remove"></span></br>';
                        data1 += '<img class="img-responsive btn btn-basic pan" src="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_3']+'" data-big="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_3']+'" style="width: 100; height: 100px;" onclick="zoom()" title="Double click to zoom in and out">';
                        data1 += '<input type="hidden" name="broker_photo[]" value="'+resp['acc_data'][0]['acc_brk_img_3']+'"/>';
                        data1 += '</td>'
                    }

                    if(resp['acc_data'][0]['acc_brk_img_4'] != '')
                    {
                        data1 += '<td id="acc_brk_img_4">';
                        data1 += '<span><a href="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_4']+'" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span></br>';
                        data1 += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image(4)" title="Remove"></span></br>';
                        data1 += '<img class="img-responsive btn btn-basic pan" src="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_4']+'" data-big="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_4']+'" style="width: 100; height: 100px;" onclick="zoom()" title="Double click to zoom in and out">';
                        data1 += '<input type="hidden" name="broker_photo[]" value="'+resp['acc_data'][0]['acc_brk_img_4']+'"/>';
                        data1 += '</td>'
                    }

                    if(resp['acc_data'][0]['acc_brk_img_5'] != '')
                    {
                        data1 += '<td id="acc_brk_img_5">';
                        data1 += '<span><a href="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_5']+'" class="glyphicon glyphicon-download" style="cursor:pointer;" title="Download" download></a></span></br>';
                        data1 += '<span class="glyphicon glyphicon-remove" style="cursor:pointer;" onclick="remove_selected_image(5)" title="Remove"></span></br>';
                        data1 += '<img class="img-responsive btn btn-basic pan" src="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_5']+'" data-big="'+resp['base_path']+'/'+resp['acc_data'][0]['acc_brk_img_5']+'" style="width: 100; height: 100px;" onclick="zoom()" title="Double click to zoom in and out">';
                        data1 += '<input type="hidden" name="broker_photo[]" value="'+resp['acc_data'][0]['acc_brk_img_5']+'"/>';
                        data1 += '</td>'
                    }
                    data1 += '</tr>';
                    data1 += '</table>';

                    $("#brk_img_preview").html(data1);




                    let basePath = resp['base_path'];
                    // remove trailing slash if exists
                    if(basePath.endsWith('/')) {
                        basePath = basePath.slice(0, -1);
                    }
                    // OR remove last path segment (after last '/')
                    basePath = basePath.substring(0, basePath.lastIndexOf('/'));

                    var data2 = '';
                    data2 += '<table cellspacing="3" cellpadding="3">';
                    data2 += '<tr>';
                    for (let i = 1; i <= 7; i++) {
                        let fileName = resp['acc_data'][0]['acc_kyc_img_' + i];
                        if (fileName && fileName !== '') {
                            let grp_id = resp['acc_data'][0]['acc_grp_id'];
                            data2 += buildFilePreview(fileName, basePath, i, grp_id);
                        }
                    }
                    data2 += '</tr>';
                    data2 += '</table>';

                    $("#kyc_img_preview").html(data2);

                },
                errmsg =>{});

                sbt_btn += '<button type="button" class="btn btn-success" onClick="add_account('+acc_id+')">Update</button>';

                $(".modal-title").html("Update Account");
            }

            $(".modal-footer").html(sbt_btn);


            $("#popup_modal_lg").modal('show');
        },
        errmsg =>{});

    }

// Open popup and load diamond data
function add_update_diamond_popup(dm_id) {
    const path = base_url + "master/masterctrl/get_single_diamond/" + dm_id;

    ajaxCall("POST", path, "", "JSON", (resp) => {

        var current_dollar_rate = resp.current_dollar_rate;
        var resp = resp.data;
         if (dm_id == 0 || !resp) {
           resp = {
                dm_category: "",

                dm_date: "",
                dm_code: "",
                dm_price_ct: "",
                dm_pc_amt: "",
                dm_dollar: "",
                dm_dollar_amt: "",
                dm_size: "",
                dm_pcs: "",
                dm_cpd: "",
                dm_sh: "",
                dm_lab: "",
                dm_cert_no: "",
                dm_carat: "",
                dm_col: "",
                dm_cla: "",
                dm_cut: "",
                dm_pol: "",
                dm_sym: "",
                dm_fl: "",
                dm_len: "",
                dm_wid: "",
                dm_hei: "",
                dm_nat_lab_grown: "",
                dm_disc: "",
                dm_rap: "",
                dm_video_link: "",

                dm_location: "",
                dm_dna: "",
                dm_tbl: "",
                dm_td_percentage: "",
                dm_l_w: "",
                dm_bic: "",
                dm_bis: "",
                dm_wic: "",
                dm_wis: "",
                dm_col_tinge: "",
                dm_lus: "",
                dm_remarks: "",
                dm_h_a: "",
                dm_girdle: "",
                dm_girdle_percentage: "",
                dm_girdle_cond: "",
                dm_ca: "",
                dm_ch: "",
                dm_pa: "",
                dm_pd: "",
                dm_str_ln: "",
                dm_lr_half: "",
                dm_culet: "",
                dm_kts: "",
                dm_rep_com: "",
                dm_cert_date: "",
                dm_image_link: "",
                dm_certificate_link: ""
            };
        }
        
    //    alert(1);
        let data = `
         <!-- Diamond Alerts -->
        <div id="diamond_alert" style="display:none;"></div>

        <form class="form-horizontal" id="diamond_form" autocomplete="off" onsubmit="save_diamond(${dm_id}); return false;">
            <div class="alert_msg_popup"></div>

            <div class="form-group floating-form row">
                <div class="col-md-6 floating-label">
                    <select id="rg_dm_category" name="rg_dm_category" class="form-control floating-select">
                        <option value="0">NON-CERTIFIED</option>
                        <option value="1">CERTIFIED</option>
                    </select>
                    <label>CATEGORY</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" class="form-control floating-input" name="rg_dm_dollar_rate" id="rg_dm_dollar_rate" value="${resp.dm_dollar_rate || current_dollar_rate}">
                    <label for="rg_dm_dollar_rate">Dollar Rate</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="date" class="form-control floating-input" name="rg_dm_date" id="rg_dm_date" value="${resp?.dm_date ? resp.dm_date : new Date().toISOString().slice(0, 10)}">
                    <label for="rg_dm_date">Date</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_location" id="rg_dm_location" value="${resp.dm_location || ""}">
                    <label for="rg_dm_location">Location</label>
                </div>


                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_code" id="rg_dm_code" value="${resp.dm_code || ""}">
                    <label for="rg_dm_code">STOCK ID / CERTIFICATE ID <span style="color:red;">*</span></label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_dna" id="rg_dm_dna" value="${resp.dm_dna || ""}">
                    <label for="rg_dm_dna">DNA</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_carat" id="rg_dm_carat" onkeyup="calculate_single_fields('carat')" value="${resp.dm_carat || ""}">
                    <label>Carat <span class="cert-field" style="color:red; display:none;">*</span></label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_ppc" id="rg_dm_ppc" onkeyup="calculate_single_fields('price_ct')" value="${resp.dm_price_ct || ""}">
                    <label>PRICE/CT <span style="color:red;">*</span></label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_pc_amt" id="rg_dm_pc_amt" onkeyup="calculate_single_fields('pc_amt')" value="${resp.dm_pc_amt || ""}" readonly>
                    <label>PC Amt</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_dollar" id="rg_dm_dollar" onkeyup="calculate_single_fields('dollar_ct')" value="${resp.dm_dollar || ""}">
                    <label>DOLLAR/CT <span style="color:red;">*</span></label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_dollar_amt" id="rg_dm_dollar_amt" onkeyup="calculate_single_fields('dollar_amt')" value="${resp.dm_dollar_amt || ""}" readonly>
                    <label>Dollar Amt</label>
                </div>

                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_size" id="rg_dm_size" value="${resp.dm_size || ""}">
                    <label>Size <span style="color:red;">*</span></label>
                </div>
                
                <div class="col-md-6 floating-label hide_fields">
                    <input type="number" class="form-control floating-input" name="rg_dm_pcs" id="rg_dm_pcs" value="${resp.dm_pcs || ""}">
                    <label>Pcs</label>
                </div>
                <div class="col-md-6 floating-label hide_fields">
                    <input type="text" class="form-control floating-input" name="rg_dm_cpd" id="rg_dm_cpd" value="${resp.dm_cpd || ""}">
                    <label>CPD</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_sh" id="rg_dm_sh" value="${resp.dm_sh || ""}">
                    <label>Shape <span style="color:red;">*</span></label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_lab" id="rg_dm_lab" value="${resp.dm_lab || ""}">
                    <label>Lab <span class="cert-field" style="color:red; display:none;">*</span></label>
                </div>
                
                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_cert_no" id="rg_dm_cert_no" value="${resp.dm_cert_no || ""}">
                    <label>Cert No</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_col" id="rg_dm_col" value="${resp.dm_col || ""}">
                    <label>Col <span style="color:red;">*</span></label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cla" id="rg_dm_cla" value="${resp.dm_cla || ""}">
                    <label>Clar. <span style="color:red;">*</span></label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cut" id="rg_dm_cut" value="${resp.dm_cut || ""}">
                    <label>Cut</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_pol" id="rg_dm_pol" value="${resp.dm_pol || ""}">
                    <label>Pol</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_sym" id="rg_dm_sym" value="${resp.dm_sym || ""}">
                    <label>Sym</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_fl" id="rg_dm_fl" value="${resp.dm_fl || ""}">
                    <label>Flur.</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_len" id="rg_dm_len" value="${resp.dm_len || ""}">
                    <label>Length</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_wid" id="rg_dm_wid" value="${resp.dm_wid || ""}">
                    <label>Width</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_hei" id="rg_dm_hei" value="${resp.dm_hei || ""}">
                    <label>Height</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" step="0.01" class="form-control floating-input" name="rg_dm_nat_lab_grown" id="rg_dm_nat_lab_grown" value="${resp.dm_nat_lab_grown || ""}">
                    <label>NAT/LAB GROWN <span style="color:red;">*</span></label>
                </div>
                <div class="col-md-6 floating-label hide_fields1" style="display:none;">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_disc" id="rg_dm_disc" value="${resp.dm_disc || ""}">
                    <label>Disc</label>
                </div>
                
                <div class="col-md-6 floating-label hide_fields1" style="display:none;">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_rap" id="rg_dm_rap" value="${resp.dm_rap || ""}">
                    <label>Rap</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_rap_dollar" id="rg_dm_rap_dollar" value="${resp.dm_rap_dollar || ""}">
                    <label>Rap dollar</label>
                </div>



                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_tbl" id="rg_dm_tbl" value="${resp.dm_tbl || ""}">
                    <label for="rg_dm_tbl">Tbl</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_td_percentage" id="rg_dm_td_percentage" value="${resp.dm_td_percentage || ""}">
                    <label for="rg_dm_td_percentage">TD %</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_l_w" id="rg_dm_l_w" value="${resp.dm_l_w || ""}">
                    <label for="rg_dm_l_w">L:W</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_bic" id="rg_dm_bic" value="${resp.dm_bic || ""}">
                    <label for="rg_dm_bic">BIC</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_bis" id="rg_dm_bis" value="${resp.dm_bis || ""}">
                    <label for="rg_dm_bis">BIS</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_wic" id="rg_dm_wic" value="${resp.dm_wic || ""}">
                    <label for="rg_dm_wic">WIC</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_wis" id="rg_dm_wis" value="${resp.dm_wis || ""}">
                    <label for="rg_dm_wis">WIS</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_col_tinge" id="rg_dm_col_tinge" value="${resp.dm_col_tinge || ""}">
                    <label for="rg_dm_col_tinge">Col Tinge</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_lus" id="rg_dm_lus" value="${resp.dm_lus || ""}">
                    <label for="rg_dm_lus">Lus</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_remarks" id="rg_dm_remarks" value="${resp.dm_remarks || ""}">
                    <label for="rg_dm_remarks">Remarks</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_h_a" id="rg_dm_h_a" value="${resp.dm_h_a || ""}">
                    <label for="rg_dm_h_a">H&A</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_girdle" id="rg_dm_girdle" value="${resp.dm_girdle || ""}">
                    <label for="rg_dm_girdle">Girdle</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_girdle_percentage" id="rg_dm_girdle_percentage" value="${resp.dm_girdle_percentage || ""}">
                    <label for="rg_dm_girdle_percentage">Girdle %</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_girdle_cond" id="rg_dm_girdle_cond" value="${resp.dm_girdle_cond || ""}">
                    <label for="rg_dm_girdle_cond">Girdle Cond</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_ca" id="rg_dm_ca" value="${resp.dm_ca || ""}">
                    <label for="rg_dm_ca">CA</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_ch" id="rg_dm_ch" value="${resp.dm_ch || ""}">
                    <label for="rg_dm_ch">CH</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_pa" id="rg_dm_pa" value="${resp.dm_pa || ""}">
                    <label for="rg_dm_pa">PA</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_pd" id="rg_dm_pd" value="${resp.dm_pd || ""}">
                    <label for="rg_dm_pd">PD</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_str_ln" id="rg_dm_str_ln" value="${resp.dm_str_ln || ""}">
                    <label for="rg_dm_str_ln">Str Ln</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_lr_half" id="rg_dm_lr_half" value="${resp.dm_lr_half || ""}">
                    <label for="rg_dm_lr_half">Lr Half</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_culet" id="rg_dm_culet" value="${resp.dm_culet || ""}">
                    <label for="rg_dm_culet">CULET</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_kts" id="rg_dm_kts" value="${resp.dm_kts || ""}">
                    <label for="rg_dm_kts">KTS</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_rep_com" id="rg_dm_rep_com" value="${resp.dm_rep_com || ""}">
                    <label for="rg_dm_rep_com">Rep Com</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="date" class="form-control floating-input" name="rg_dm_cert_date" id="rg_dm_cert_date" value="${resp.dm_cert_date || ""}">
                    <label for="rg_dm_cert_date">Cert Date</label>
                </div>



                <div class="col-md-6 floating-label hide_fields1" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_video_link" id="rg_dm_video_link" value="${resp.dm_video_link || ""}">
                    <label>Video Link</label>
                </div>


                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_image_link" id="rg_dm_image_link" value="${resp.dm_image_link || ""}">
                    <label for="rg_dm_image_link">Image Link</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_certificate_link" id="rg_dm_certificate_link" value="${resp.dm_certificate_link || ""}">
                    <label for="rg_dm_certificate_link">Certificate Link</label>
                </div>


            </div>

            <input type="hidden" name="rg_dm_id" id="rg_dm_id" value="${dm_id}">
        </form>
        `;

        $(".modal-body").html(data);

        let sbt_btn = `
            <button type="button" form="diamond_form" class="btn btn-success" onclick="save_diamond(${dm_id})">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        `;

        $(".modal-title").html(dm_id == 0 ? "Add Diamond" : "Update Diamond");
        $(".modal-footer").html(sbt_btn);
        $("#popup_modal_lg").modal("show");


        // When editing/loading data
        if(resp.dm_category){
            $("#rg_dm_category").val(resp.dm_category).trigger("change");

            if (resp.dm_category == "1") {
                $(".cert-field").show();

                $('.hide_fields').css('display', 'none');
                $('.hide_fields1').css('display', 'block');
            } else {
                $(".cert-field").hide();

                $('.hide_fields').css('display', 'block');
                $('.hide_fields1').css('display', 'none');
            }
        }

        // On change, show/hide certified fields
        $(document).on("change", "#rg_dm_category", function () {
            let val = $(this).val();
            
            if (val == "1") {
                $(".cert-field").show();
   
                $('.hide_fields').css('display', 'none');
                $('.hide_fields1').css('display', 'block');
            } else {
                $(".cert-field").hide();
                
                $('.hide_fields').css('display', 'block');
                $('.hide_fields1').css('display', 'none');
            }
        });

    });
}
 
// Save diamond AJAX
function save_diamond(dm_id) {
    const form = document.getElementById("diamond_form");
    const formData = new FormData(form);

    const dm_category = $("#rg_dm_category").val().trim();

      // ✅ Validate stock_id before saving
    const stock_id = $("#rg_dm_code").val().trim();
    if (stock_id === "") {
        display_alert_popup('err', 'Please enter Stock ID!');
        $("#rg_dm_code").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_code").css("border-color", "#ccc");
    }

    if (dm_category == 1) {
        const dm_carat = $("#rg_dm_carat").val().trim();
        if (dm_carat === "") {
            display_alert_popup("err", "Please enter CARAT!");
            $("#rg_dm_carat").css("border-color", "red").focus();
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
            return false;
        } else {
            $("#rg_dm_carat").css("border-color", "#ccc");
        }
    }

    const dm_ppc = $("#rg_dm_ppc").val().trim();
    if (dm_ppc == 0) {
        display_alert_popup("err", "Please enter PRICE/CT!");
        $("#rg_dm_ppc").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_ppc").css("border-color", "#ccc");
    }

    const dm_dollar = $("#rg_dm_dollar").val().trim();
    if (dm_dollar == 0) {
        display_alert_popup("err", "Please enter DOLLAR/CT!");
        $("#rg_dm_dollar").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_dollar").css("border-color", "#ccc");
    }

    const dm_size = $("#rg_dm_size").val().trim();
    if (dm_size === "") {
        display_alert_popup("err", "Please enter SIZE!");
        $("#rg_dm_size").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_size").css("border-color", "#ccc");
    }

    const dm_sh = $("#rg_dm_sh").val().trim();
    if (dm_sh === "") {
        display_alert_popup("err", "Please enter SHAPE!");
        $("#rg_dm_sh").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_sh").css("border-color", "#ccc");
    }

    if (dm_category == 1) {
        const dm_lab = $("#rg_dm_lab").val().trim();
        if (dm_lab === "") {
            display_alert_popup("err", "Please enter CARAT!");
            $("#rg_dm_lab").css("border-color", "red").focus();
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
            return false;
        } else {
            $("#rg_dm_lab").css("border-color", "#ccc");
        }
    }

    const dm_col = $("#rg_dm_col").val().trim();
    if (dm_col === "") {
        display_alert_popup("err", "Please enter COL!");
        $("#rg_dm_col").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_col").css("border-color", "#ccc");
    }

    const dm_cla = $("#rg_dm_cla").val().trim();
    if (dm_cla === "") {
        display_alert_popup("err", "Please enter CLAR.!");
        $("#rg_dm_cla").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_cla").css("border-color", "#ccc");
    }

    const dm_nat_lab_grown = $("#rg_dm_nat_lab_grown").val().trim();
    if (dm_nat_lab_grown === "") {
        display_alert_popup("err", "Please enter NAT/LAB GROWN!");
        $("#rg_dm_nat_lab_grown").css("border-color", "red").focus();
        $("#popup_modal_sm").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#rg_dm_nat_lab_grown").css("border-color", "#ccc");
    }

    $.ajax({
        url: base_url + "master/masterctrl/save_diamond/" + dm_id,
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json", 

        success: function(resp) {
            $("#popup_modal_lg").animate({'scrollTop': 0},1000);
            if (resp.status == "success") {

                let msg = (dm_id == 0)
                    ? "Diamond added successfully!"
                    : "Diamond updated successfully!";

                display_alert_popup('succ',msg);

                setTimeout(() => {
                    $("#popup_modal_lg").modal("hide");
                    location.reload(); // refresh listing
                }, 1000);

            }
            else if (resp.status == "error") {
                display_alert_popup('err',resp.message || "STOCK ID already exists. Please use a different one.");
            } 
            else {
                display_alert_popup('err',resp.message || "Something went wrong!");
            }
        },

        error: function() {
            display_alert_popup('err',"Server error!");
        }
    });
}

function diamond_alert(type, msg) {
    const alertBox = document.getElementById("diamond_alert");

    let alertClass = (type === "succ") ? "alert-success" : "alert-danger";

    alertBox.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible show" role="alert" style="padding:10px; margin-bottom:10px; font-size:14px;">
            ${msg}
        </div>
    `;
    alertBox.style.display = "block";

    // Auto-hide after 5 seconds
    // setTimeout(() => {
    //     $(alertBox).fadeOut(500, function () {
    //         $(this).html("").show(); // clear but keep ready
    //         location.reload();       // ✅ reload page
    //     });
    // }, 1000);
}

const set_diamond_field = (id) => {
  const url = `master/masterctrl/get_single_diamond/${id}`;

  ajax({
    url,
    type: "POST",
    success: (resp) => {
      const data = resp;
      if (data) {
        $("#dm_date").val(data.dm_date);
        $("#dm_code").val(data.dm_code);
        $("#dm_ppc").val(data.dm_price_ct);
        $("#dm_pc_amt").val(data.dm_pc_amt);
        $("#dm_id").val(id);

        $("#popup_modal_sm").modal("show");
      }
    },
  });
};

    function remove_selected_image(cnt)
    {
        $("#acc_brk_img_"+cnt).remove();
    }
    function remove_selected_image1(cnt)
    {
        $("#acc_kyc_img_"+cnt).remove();
    }
    function zoom()
    {
        $(".pan").pan();
    }

    function add_account(id){

        var check = 1;

        if($("#acc_name").val() == '')
        {
            $("#acc_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#acc_name").css({'border-color':'#CCC'});
        }

        if($("#acc_grp_id").val() == '')
        {
            $("#acc_grp_id").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#acc_grp_id").css({'border-color':'#CCC'});
        }

        if($("#acc_grp_id").val() == 6)
        {
        if($("#acc_broker_id").val() == '')
        {
            $("#acc_broker_id").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#acc_broker_id").css({'border-color':'#CCC'});
        }
        }

        if($("#acc_type").val() == 0)
        {
            $("#acc_type").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#acc_type").css({'border-color':'#CCC'});
        }

        // if($("#acc_kyc").val() == 1)
        // {
        //     if($("#acc_gst").val() == '')
        //     {
        //         $("#acc_gst").css({'border-color':'red'});
        //         check = 0;
        //     }
        //     else
        //     {
        //         $("#acc_gst").css({'border-color':'#CCC'});
        //     }
        // }else
        // {
        //     $("#acc_gst").css({'border-color':'#CCC'});
        // }

        // if($("#acc_pan").val() == '')
        // {
        //     $("#acc_pan").css({'border-color':'red'});
        //     check = 0;
        // }
        // else
        // {
        //     $("#acc_pan").css({'border-color':'#CCC'});
        // }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);

            $("#popup_modal_lg").animate({'scrollTop': 0},1000);
        }
        else
        {
            var path        = base_url+"master/masterctrl/account_insert/"+id;
            var form_id     = document.getElementById('account_form');
            var form_data   = new FormData(form_id);


            fileUpAjaxCall('POST',path,form_data,'JSON',resp =>
            {
                // console.log(resp)
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_lg").animate({

                            'scrollTop': 0
                        },1000);

                        $("#account_form")[0].reset();

                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert_popup('succ',msg);

                        $("#popup_modal_lg").animate({

                            'scrollTop': 0
                        },1000)  ;

                    }

                    $("#table_reload").load(window.location + " .table");
                    $("#count_reload").load(window.location + " #total_rows");
                }
                else if(resp == 2)
                {
                    var msg = 'Account already exists!';
                    display_alert_popup('err',msg);

                    $("#popup_modal_lg").animate({

                        'scrollTop': 0
                    },1000);
                }
                else
                {
                    var msg = 'Unknown error ! Please try again later';
                    display_alert_popup('warn',msg);
                    $("#popup_modal_lg").animate({

                        'scrollTop': 0
                    },1000);
                }
            },
            errmsg =>{});
        }
    }
/********************************* Account Master *********************************/
function get_checkbox_val(ck)
{
    var id = $('#check_flag_'+ck).attr('id');

    if($('#'+id).is(':checked')) 
    {
        $('#check_flag_'+ck).val(ck);
    }
    else
    {
        $('#check_flag_'+ck).val(0);
    }
}

/*diamond master*/
    function import_diamond_stock()
    {
        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="diamond_form">';

        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">*.xlxs (Only)</label>';
        data += '<div class="col-sm-6">';
        data += '<input type="file" class="form-control" name="diamond_import" id="diamond_import" value="" autocomplete="off" onchange="is_excel(this)">';
        data += '</div>';
        data += '</div>';

        data += '<div class="form-group">';
        data += '<div class="col-sm-10 col-sm-offset-1">';
        data += '<table class="table table-responsive" id="set_imported_result">';
        data += '</table>';
        data += '</div>';
        data += '</div>';

        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);

        var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

        sbt_btn += '<button type="button" class="btn btn-success" onClick="add_diamond(0)">Submit</button>';

        $(".modal-title-sm").html("Add Diamond");
        $(".modal-footer-sm").html(sbt_btn);
        $("#popup_modal_sm").modal('show');
    }
    // function is_excel
    function is_excel(element)
    {

        var element_id = "#"+element.id;
        var excelPath  = $(element_id)[0].value;
        var extn = excelPath.substring(excelPath.lastIndexOf('.') + 1).toLowerCase();
        if (extn == "xlx" || extn == "xlsx")
        {
            if (typeof (FileReader) != "undefined")
            {

            }
            else
            {
                alert("This browser does not support FileReader.");
            }
        }
        else
        {
            alert("Pls select only excel");
            $(element_id).val('');
        }
    }
    
    function add_diamond(id)
    {
        var check = 1;
        if($("#diamond_import").val() == '')
        {
            $("#diamond_import").css({'border-color':'red'});
            $("#diamond_import").addClass('shake');
            $('#diamond_import').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#diamond_import').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#diamond_import").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert_popup('err',msg);

            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {
            let category = $('#search_value_category').val();

            var form_id = document.getElementById('diamond_form');
            var form_data = new FormData(form_id);

            var path = base_url+"master/masterctrl/import_diamond/";

            fileUpAjaxCall('POST',path,form_data,'JSON',resp =>
            {

                if(resp['resp'] == 1)
                {
                    var msg = 'Successfully imported!';
                    display_alert_popup('succ',msg);
                    $("#diamond_import").val('');
                    $("#popup_modal_sm").animate({'scrollTop':0},1000);

                    $("#table_reload").load(window.location + " .table");
                    $("#count_reload").load(window.location + " #total_rows");
                    // $("#pagination").load(window.location);

                    var data = '';
                    var total_count = parseInt(resp['add_cnt']) + parseInt(resp['edit_cnt']) + parseInt(resp['not_add_cnt']);
                    var cnt = 0;

                    data += '<tr>';
                    data += '<th>';
                    data += 'NEW ADDED';
                    data += '</th>';

                    data += '<th>';
                    data += 'EXISTING UPADTED';
                    data += '</th>';

                    data += '<th>';
                    data += 'NOT ADDED';
                    data += '</th>';

                    data += '<th>';
                    data += 'TOTAL COUNT';
                    data += '</th>';

                    data += '<tr>';
                    data += '<td>';
                    data += resp['add_cnt'];
                    data += '</td>';

                    data += '<td>';
                    data += resp['edit_cnt'];
                    data += '</td>';

                    data += '<td>';
                    data += resp['not_add_cnt'];
                    data += '</td>';

                    data += '<td>';
                    data += total_count+'';
                    data += '</td><br/>';

                    data += '</tr>';



                    if(resp['not_add_cnt'] > 0)
                    {
                        data += '<tr>';
                        data += '<th colspan="3" align="center">';
                        data += 'LIST OF NOT ADDED STOCK ID';
                        data += '</th>';
                        data += '</tr>';

                        data += '<tr>';
                        data += '<th>';
                        data += 'SR NO';
                        data += '</th>';

                        data += '<th>';
                        data += 'STOCK ID';
                        data += '</th>';

                        data += '<th>';
                        data += 'STATUS';
                        data += '</th>';
                        data += '</tr>';
                        $.each(resp['not_added'], (index, value) => {
                            cnt = parseInt(cnt) + 1;
                            status = '';
                            if(value['dm_status'] == 1)
                            {
                                status = 'ISSUE';
                            }
                            else if(value['dm_status'] == 2)
                            {
                                status = 'HOLD';
                            }
                            else if(value['dm_status'] == 3)
                            {
                                status = 'SOLD';
                            }
                            else if(value['dm_status'] == 4)
                            {
                                status = 'RETURN';
                            }
                            else
                            {
                                status = 'AVAILABLE';
                            }
                            data += '<tr>';
                            data += '<td>';
                            data += cnt;
                            data += '</td>';

                            data += '<td>';
                            data += value['dm_code'];
                            data += '</td>';


                            data += '<td>';
                            data += status;
                            data += '</td>';
                            data += '</tr>';

                            cnt++;
                        });

                    }
                    $("#set_imported_result").html(data);

                }
                else if(resp['resp'] == 2)
                {
                    var msg = 'No data in excel file';
                    display_alert_popup('err',msg);
                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
                else
                {
                    var msg = 'Unknown Error ! Please try again letter';
                    display_alert_popup('warn',msg);
                    $("#popup_modal_sm").animate({'scrollTop':0},1000);
                }
             },
             errmsg => {});
        }
    }
    
    function get_challan_data(dm_id, ct_id)
    {
        var path = base_url+"master/masterctrl/get_challan_data?dm_id="+dm_id+"&ct_id="+ct_id;
        ajaxCall('POST',path,'','JSON',resp =>
        {

            let broker = resp[0]['broker'] == null ? '-' : resp[0]['broker'];

            var data = '';
            data += '<div class="row">';
            data += '<div class="col-md-12">'
            data += '<table class="table table-responsive">';
            data += '<tr>';

            data += '<th> ISSUE NO </th>';
            data += '<th> ISSUE DATE </th>';
            data += '<th> PARTY</th>';
            data += '<th> BROKER</th>';
            data += '<th> THROUGH</th>';

            data += '</tr>';

            data += '<tr>';

            data += '<td> '+resp[0]['cm_entry_no']+'</td>';
            data += '<td> '+resp[0]['cm_entry_date']+'</td>';
            data += '<td> '+resp[0]['customer']+'</td>';
            data += '<td> '+broker +'</td>';
            data += '<td> '+resp[0]['cm_through']+'</td>';

            data += '</tr>';
            data += '</table>';
            data += '</div>';
            data += '</div>';

            $(".modal-body-sm").html(data);

            var sbt_btn = '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';

            $(".modal-title-sm").html("ISSUE DETAIL");


            $(".modal-footer-sm").html(sbt_btn);


            $("#popup_modal_sm").modal('show');
        },
        errmsg => {});
    }
    function get_challan_return_data(dm_id, crt_id)
    {
        var path = base_url+"master/masterctrl/get_challan_return_data?dm_id="+dm_id+"&crt_id="+crt_id;
        ajaxCall('POST',path,'','JSON',resp =>
        {


            var data = '';
            data += '<div class="row">';
            data += '<div class="col-md-12">'
            data += '<table class="table table-responsive">';
            data += '<tr>';

            data += '<th> ISSUE NO </th>';
            data += '<th> ISSUE DATE </th>';
            data += '<th> PARTY</th>';
            data += '<th> BROKER</th>';
            data += '<th> THROUGH</th>';

            data += '</tr>';

            data += '<tr>';

            data += '<td> '+resp[0]['crm_entry_no']+'</td>';
            data += '<td> '+resp[0]['crm_entry_date']+'</td>';
            data += '<td> '+resp[0]['customer']+'</td>';
            data += '<td> '+resp[0]['broker']+'</td>';
            data += '<td> '+resp[0]['crm_through']+'</td>';

            data += '</tr>';
            data += '</table>';
            data += '</div>';
            data += '</div>';

            $(".modal-body-sm").html(data);

            var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

            $(".modal-title-sm").html("ISSUE DETAIL");


            $(".modal-footer-sm").html(sbt_btn);


            $("#popup_modal_sm").modal('show');
        },
        errmsg => {});
    }
    
        function set_r2net(dm_id, value)
    {
        var path = base_url+"master/masterctrl/set_r2net?dm_id="+dm_id+"&r2net="+value;
        ajaxCall('POST',path,'','JSON',resp =>
        {
            // $("#table_reload").load(window.location + " .table");
            // $("#count_reload").load(window.location + " #total_rows");
            $("#search_btn").trigger('click');
        },
        errmsg => {});
    }

     function set_suspense(dm_id, value)
    {
        var path = base_url+"master/masterctrl/set_suspense?dm_id="+dm_id+"&suspense="+value;
        ajaxCall('POST',path,'','JSON',resp =>
        {
            // $("#table_reload").load(window.location + " .table");
            // $("#count_reload").load(window.location + " #total_rows");
            $("#search_btn").trigger('click');
        },
        errmsg => {});
    }

/*/diamond master*/


/************* Rapaport Master ******************/
    function update_rp_rate(type)
    {
        var update_path = base_url+"rapaportctrl/update_rp_rate/"+type;
        ajaxCall('GET',update_path,'','JSON',resp =>
        {
            if(resp['resp'] == 1)
            {
                var msg = 'Successfully updated!';
                display_alert('succ',msg);
                setTimeout(function(){location.reload();},1000);
            }
            else
            {
                var msg = 'Database Error ! Please try again letter';
                display_alert('warn',msg);
            }
        },
        errmsg =>{}
        );
    }
    
    /************* /Rapaport Master ******************/

/* Group Master */

    function add_update_group_popup(grp_id){

        var data = '';

        var path = base_url+"master/masterctrl/get_dealers";


        $.ajax({
            type:'POST',
            url:path,
            dataType:'json',
            success:resp =>
            {
                data += '<div class="alert_msg"></div>';
                data += '<div class="row">';
                data += '<div class="col-md-12">'
                data += '<form class="form-horizontal" id="group_form">';

                data += '<div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">Group Name<span style="color:red">*</span></label><div class="col-sm-4"><input type="text" name="grp_name" class="form-control" id="grp_name"></div>';

                data += '<label for="inputEmail3" class="col-sm-2 control-label">Group Default Value<span style="color:red">*</span></label><div class="col-sm-4">';

                data += '<select name="grp_default" class="form-control" id="grp_default">';
                data += '<option value="TRUE">TRUE</option>';
                data += '<option value="FALSE">FALSE</option>';
                data += '</select>';

                data += '</div></div>';

                data += '<div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">Group Summary<span style="color:red">*</span></label><div class="col-sm-10"><textarea name="grp_tbsummery" class="form-control" id="grp_tbsummery"></textarea></div></div>';

                data += '<div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">Balance Sheet Entry<span style="color:red">*</span></label><div class="col-sm-4">';
                data += '<select name="grp_bs" class="form-control" id="grp_bs">';
                data += '<option value="1">YES</option>';
                data += '<option value="0">NO</option>';
                data += '</select>';

                data += '</div>';

                data += '<label for="inputEmail3" class="col-sm-2 control-label">Profit Sheet Entry<span style="color:red">*</span></label><div class="col-sm-4">';
                data += '<select name="grp_pl" class="form-control" id="grp_pl">';
                data += '<option value="1">YES</option>';
                data += '<option value="0">NO</option>';
                data += '</select>';

                data += '</div>';

                data += '</form>';
                data += '</div>';
                data += '</div>';

                $(".modal-body").html(data);

                var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

                if(grp_id == 0){

                    sbt_btn += '<button type="button" class="btn btn-success" onClick="add_group(0)">Submit</button>';

                    $(".modal-title").html("Add Group");
                }
                else
                {

                    var update_path = base_url+"master/masterctrl/get_single_group/"+grp_id;

                    $.ajax({
                        type:'POST',
                        url:update_path,
                        dataType:'json',
                        success:resp =>
                        {
                            $("#grp_name").val(resp[0]['grp_name']);
                            $("#grp_belong").val(resp[0]['grp_belong']);
                            $("#grp_default").val(resp[0]['grp_default']);
                            $("#grp_tbsummery").val(resp[0]['grp_tbsummery']);
                            $("#grp_bs").val(resp[0]['grp_bs']);
                            $("#grp_pl").val(resp[0]['grp_pl']);

                        },
                        error:errmsg =>{}
                    });

                    sbt_btn += '<button type="button" class="btn btn-success" onClick="add_group('+grp_id+')">Submit</button>';

                    $(".modal-title").html("Update Group");
                }

                $(".modal-footer").html(sbt_btn);


                $("#popup_modal_lg").modal('show');
            },
            error:errmsg => {}
        });
    }

    function add_group(id){

        var check = 1;

        if($("#grp_name").val() == '')
        {
            $("#grp_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#grp_name").css({'border-color':'#CCC'});
        }

        if($("#grp_belong").val() == '')
        {
            $("#grp_belong").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#grp_belong").css({'border-color':'#CCC'});
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);
        }
        else
        {

            var path = base_url+"master/masterctrl/group_insert/"+id;
            var form_data = $("#group_form").serialize();

            $.ajax({
                type:'POST',
                url:path,
                data:form_data,
                success:resp =>
                {


                    if(resp == 1)
                    {
                        if(id == 0)
                        {
                            var msg = 'Successfully added!';
                            display_alert('succ',msg);

                            $("#group_form")[0].reset();
                        }
                        else
                        {
                            var msg = 'Successfully updated!';
                            display_alert('succ',msg);
                        }
                    }
                    else if(resp == 2)
                    {
                        var msg = 'Group is already exists!';
                        display_alert('err',msg);
                    }
                    else
                    {
                        var msg = 'Unknown error ! Please try again later';
                        display_alert('warn',msg);
                    }

                },
                error:errmsg => {

                }
            });
        }
    }

    function diamond_master()
    {
        var path        = base_url+"master/masterctrl/diamond_master_excel/";
        var form_data   = $("#search_form").serialize();

        ajaxCall('POST',path,form_data,'JSON',resp =>
        {
        },
        errmsg => {});
    }
    
/********************************* Group Master End*********************************/


    /************** Product Master  **************/

    function add_update_product_popup(pm_id)
    {       var data = '';                      
                data += '<div class="alert_msg"></div>';                      
                data += '<div class="row">';
                data += '<div class="col-md-12">'
                data += '<form class="form-horizontal" id="pro_form">';
                
                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">Product Name</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_name" class="form-control" id="pro_name"></div>'; 
                data += '</div>';
                
                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">Product Description</label>'; 
                data += '<div class="col-sm-9"><textarea type="text" name="pro_desc" class="form-control" id="pro_desc"></textarea></div>'; 
                data += '</div>';

                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">HSN Code</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_hsn_code" class="form-control" id="pro_hsn_code"></div>'; 
                data += '</div>';

                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">Rate</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_rate" class="form-control" id="pro_rate"></div>'; 
                data += '</div>';

                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">CGST %</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_cgst" class="form-control" id="pro_cgst" onkeyup="get_gst_value()"></div>'; 
                data += '</div>';

                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">SGST %</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_sgst" class="form-control" id="pro_sgst" readonly></div>'; 
                data += '</div>';

                data += '<div class="form-group">'; 
                data += '<label class="col-sm-3 control-label">IGST %</label>'; 
                data += '<div class="col-sm-9"><input type="text" name="pro_igst" class="form-control" id="pro_igst" readonly></div>'; 
                data += '</div>';

                data += '<div class="form-group"><label  class="col-sm-3 control-label">Status</label><div class="col-sm-9">';
                data += '<select type="text" name="pro_status" class="form-control" id="pro_status">';
                data += '<option value="">PLEASE SELECT</option>'
                data += '<option value="1">ACTIVE</option>'
                data += '<option value="0">INACTIVE</option>'
                data += '</select>';
                data += '</div></div>';

                data += '</form>';
                data += '</div>';
                data += '</div>';

                $(".modal-body-sm").html(data);

                var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';  
                
                if(pm_id == 0){

                    sbt_btn += '<button type="button" class="btn btn-success" id="pro_btn" onClick="add_pro(0)">Submit</button>';

                    $(".modal-title-sm").html("Add Item");
                }
                else
                {

                    var update_path = base_url+"master/masterctrl/get_single_pro/"+pm_id;
                    
                    $.ajax({
                        type:'POST',
                        url:update_path,
                        dataType:'json',
                        success:function(resp)
                        {
                            $("#pro_name").val(resp[0]['pro_name']);
                            $("#pro_hsn_code").val(resp[0]['pro_hsn_code']);
                            $("#pro_desc").val(resp[0]['pro_desc']);
                            $("#pro_rate").val(resp[0]['pro_rate']);
                            $("#pro_cgst").val(resp[0]['pro_cgst']);
                            $("#pro_sgst").val(resp[0]['pro_sgst']);
                            $("#pro_igst").val(resp[0]['pro_igst']);
                            $("#pro_status").val(resp[0]['pro_status']);
                        },
                        error:function(resp)
                        {
                            console.log(resp);
                        }
                    });

                    sbt_btn += '<button type="button" class="btn btn-success" id="pro_btn" onClick="add_pro('+pm_id+')">Submit</button>';

                    $(".modal-title-sm").html("Update product");
                }

                $(".modal-footer-sm").html(sbt_btn);

                $("#loading").hide();
                $("#popup_modal_sm").modal('show');
    }

    function get_gst_value()
    {
        var pro_cgst = $("#pro_cgst").val();
        var pro_igst = 2*pro_cgst;
        $("#pro_sgst").val(pro_cgst);
        $("#pro_igst").val(pro_igst);
    }

    function add_pro(pm_id)
    {
        var check = 1;

        if($("#pro_name").val() == '')
        {
            $("#pro_name").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#pro_name").css({'border-color':'#CCC'});
        }


        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
        }
        else
        {
            var path = base_url+"master/masterctrl/pro_insert/"+pm_id;   
            var form_data = $("#pro_form").serialize();

            $("#loading").show();
            $.ajax({
                type:'POST',
                url:path,
                data:form_data,
                success:function(resp)
                {
                    if(resp == 1)
                    {
                        if(pm_id == 0)
                        {
                            var msg = 'Successfully added!';
                            display_alert('succ',msg);
                            $("#pro_form")[0].reset();
                            $("#popup_modal_sm").animate({'scrollTop':0},1000);
                        }
                        else
                        {
                            var msg = 'Successfully updated!';
                            display_alert('succ',msg);
                            $("#popup_modal_sm").animate({'scrollTop':0},1000);
                        }
                    }
                    else if(resp == 2)
                    {
                        var msg = 'Product already exists!';
                        display_alert('err',msg);
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                    else
                    {
                        var msg = 'Database Error ! Please try again letter';
                        display_alert('warn',msg);
                        $("#popup_modal_sm").animate({'scrollTop':0},1000);
                    }
                    $("#loading").hide();
                },
                error:function(resp){
                    console.log(resp);
                }   
            });
        }
    }


    function delete_diamond(dm_id)
    {     
            let text=confirm('Are you sure you want to delete?');
            if(text)
            {
              var path = base_url+"master/masterctrl/diamond_delete_data/"+dm_id;
              ajaxCall('POST',path,'','JSON',resp => 
              {
              var msg = 'Successfully deleted';
              display_alert('err',msg);
              $("body, html").animate({'scrollTop':0},1000);
                setInterval(function(){window.location.reload(); },2000); 
             },errmsg=>{});
           }
    }


    function calculate_single_fields(changedField = '') {

        let current_dollar_rate = $("#rg_dm_dollar_rate").val();
        if (current_dollar_rate == 0) {
            $("#rg_dm_dollar_rate").css({'border-color':'red'});
            display_alert_popup('err', 'Please enter current dollar rate!!!');
            $("#popup_modal_sm").animate({'scrollTop':0},1000);
            return false;
        } else {
            $("#rg_dm_dollar_rate").css({'border-color':'#000'});
        }

        let pcs          = parseFloat($("#rg_dm_carat").val()) || 0;
        let price_ct     = parseFloat($("#rg_dm_ppc").val()) || 0;
        let pc_amt       = parseFloat($("#rg_dm_pc_amt").val()) || 0;
        let dollar_ct    = parseFloat($("#rg_dm_dollar").val()) || 0;
        let dollar_amt   = parseFloat($("#rg_dm_dollar_amt").val()) || 0;

        // Prevent divide-by-zero
        // if (pcs === 0) pcs = 1;

        // -------------------------
        // PRIORITY CALCULATIONS
        // -------------------------
        if (changedField === 'price_ct') {
            pc_amt     = price_ct * pcs;
            dollar_ct  = price_ct / current_dollar_rate;
            dollar_amt = dollar_ct * pcs;
        }
        if (changedField === 'dollar_ct') {
            price_ct   = dollar_ct * current_dollar_rate;
            pc_amt     = price_ct * pcs;
            dollar_amt = dollar_ct * pcs;
            
        }
        
        if(pcs > 0){
            if (changedField === 'pc_amt') {
                price_ct   = pc_amt / pcs;
                dollar_ct  = price_ct / current_dollar_rate;
                dollar_amt = dollar_ct * pcs;
            }
            
            if (changedField === 'dollar_amt') {
                dollar_ct  = dollar_amt / pcs;
                price_ct   = dollar_ct * current_dollar_rate;
                pc_amt     = price_ct * pcs;
            }
        }
    
        if (changedField === 'carat') {
            // price_ct   = dollar_ct * current_dollar_rate;
            // dollar_ct  = price_ct / current_dollar_rate;

            pc_amt     = price_ct * pcs;
            dollar_amt = dollar_ct * pcs;
        }

        // --------------------------------------------------
        // UPDATE BACK TO INPUT FIELDS
        // --------------------------------------------------
        if (changedField !== 'price_ct')
            $("#rg_dm_ppc").val(customRound(price_ct));

        if (changedField !== 'pc_amt')
            $("#rg_dm_pc_amt").val(customRound(pc_amt));

        if (changedField !== 'dollar_ct')
            $("#rg_dm_dollar").val(customRound(dollar_ct));

        if (changedField !== 'dollar_amt')
            $("#rg_dm_dollar_amt").val(customRound(dollar_amt));
    }
    //temp data to update