var table ,  block = $(".content-wrapper").parent();
    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                          window.print();
                          window.onload = function() { window.print(); }
                        </script>
                        `;
    var HTML_Table = `
                      <!DOCTYPE html>
                      <html lang="ar" dir="rtl">
                      <head>
                        <meta charset="utf-8">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge">
                        <style>

                          .print {  
                            -webkit-print-color-adjust: exact;
                          }
                          
                          .table0_td {
                            
                            border:none;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          .table0_td1 {
                            
                            border:none;
                            border-bottom:solid #984806 1.0pt;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          
                          
                          .table1_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .last_td {
                            border-left-color: #984806 !important;
                          }
                          
                          .table1_td1 {
                            
                            border:solid #984806 1.0pt;
                            border-top:none;
                            background:white;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .table2_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in;
                            
                          }
                          
                          .td_head {
                            text-align: center;
                            
                            color : white;
                            height: .3in;
                          }
                          
                          .td_body {
                            text-align: center;
                            
                            color : black;
                            height: .2in;
                            border:solid #984806 1.0pt;
                          }
                          
                          #inv_table tr:nth-child(odd) {
                            background-color: #FDE9D9;
                          }
                          
                          @font-face {
                            font-family: "Noto Kufi Arabic";
                            src: url(assets/custom_font/NotoKufiArabic-Regular.ttf) format("truetype");
                            }
                          
                          .badge {
                            display: inline-block;
                            min-width: 10px;
                            padding: 3px 7px;
                            font-size: 12px;
                            font-weight: 500;
                            color: #fff;
                            line-height: 1.5384616;
                            vertical-align: middle;
                            white-space: nowrap;
                            text-align: center;
                            background-color: #999999;
                            border-radius: 10px;
                          } 

                          .label {
                              display: inline-block;
                              font-weight: 500;
                              padding: 2px 5px 1px 5px;
                              line-height: 1.5384616;
                              border: 1px solid transparent;
                              text-transform: uppercase;
                              text-align: center;

                              font-size: 10px;
                              letter-spacing: 0.1px;
                              border-radius: 2px;
                          }
                          
                          .badge {
                            padding: 1px 1px 1px 1px;
                            font-size: 10px;
                            letter-spacing: 0px;
                            vertical-align: baseline;
                            
                            
                            
                          }
                          
                          .bg-orange-400 {
                            background-color: #FFA726;
                            border-color: #FFA726;
                            color: #fff;
                          }

                          .bg-success-400 {
                            background-color: #4CAF50;
                            border-color: #4CAF50;
                            color: #fff;
                          }

                          .col-sm-12 {
                            width: 100%;
                          }
                          .col-sm-6 {
                            width: 50%;
                          }

                          .col-sm-4 {
                            width: 33.33333333%;
                          }
                          
                          .col-sm-3 {
                            width: 25%;
                          }

                        </style>

                      </head>

                      <body class="print" style=" font-family: 'Noto Kufi Arabic', Times, serif;">
                        <div align=center>
                      `;

    
    var HTML_Sticker = `
                        <!DOCTYPE html>
                        <html lang="ar" dir="rtl">
                          <head>
                            <meta charset="utf-8">
                            <meta http-equiv="X-UA-Compatible" content="IE=edge">
                            <style>

                              @media print and (width: 10cm) and (height: 5cm) {
                                 @page {
                                  margin: .3cm;
                                 }
                              }
                              .print {  
                                  -webkit-print-color-adjust: exact;
                                  }
                                  
                              @page {
                                  size:  1.968in 3.937in landscape;
                                  }

                                  .page-break  {
                                                  clear: left;
                                                  display:block;
                                                  page-break-after:always;
                                              }
                            </style>


                          </head>

                          <body lang=ar>

                              <div class=WordSection1>

                                <p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi: embed'><span dir=LTR style='font-size:4.0pt'>&nbsp;</span></p>

                                <div align=center>
                        `;
    

    function edit_items(itemid,qty,pric,date_,pro,note){
            console.log(pro);
            note = decodeURIComponent(note);
            get_Products();
            $("#edit_product_id").html($("#product_id").html());
            $("#edit_objid").val(itemid);
            $("#edit_product_id").val(pro);
            //$('#edit_product_id option[value='+pro+']').attr('selected','selected');
            $("#edit_created_at").val(date_);
            $("#edit_quantity").val(qty);
            $("#edit_buy_price").val(pric);
            $("#edit_note").val(note);

            // because we didnt have it in table so we cant set it in edit_items we will set it from here
            for(var j=0 ; j< products_array_values.length; j++ ){
             if(pro == products_array_values[j]['id']){

                var sellPrice    = products_array_values[j]['sell_price'];
                var sellPricePer = products_array_values[j]['sell_price_percentage'];
                var avgPrice     = products_array_values[j]['average_price'];
                var oldtotalQty  = products_array_values[j]['remained_quantity'];

                $("#edit_average_price_old").val(avgPrice);
                $("#edit_total_quantity_old").val(oldtotalQty);
                $("#edit_sell_price").val(sellPrice);
                $("#edit_sell_price_percentage").val(sellPricePer);
                $("#edit_quantity_save").val(oldtotalQty-qty); // prevoius remainded quantity before add the current editing quantity of this purchase
                // returning the previous values of average price before adding this editing quantity
                var totalPrice_before_edit = oldtotalQty * avgPrice - qty * pric;
                var avgPrice_before_edit   = totalPrice_before_edit /(oldtotalQty - qty);
                if(isNaN(avgPrice_before_edit)){avgPrice_before_edit = avgPrice}
                $("#edit_average_price_old_prev").val(avgPrice_before_edit)
              }
            }


            $('#edit_form_cont').modal('toggle');
            calc_sell_price_edit();
    }

    function edit_items1(itemid,itemName,part,made,sell,sellpercent,cat,avg,come_type){
        //$("#edit_category_id").html($("#category_id").html());
        $("#edit_objid").val(itemid);
        $("#edit_category_id").val(cat);
        //$('#edit_category_id option[value='+cat+']').attr('selected','selected');
        $('#edit_category_id').selectpicker('val',cat);
        $('#edit_category_id').selectpicker('refresh');
        $("#edit_product_name").val(itemName);
        $("#edit_part_number").val(part);
        $("#edit_made_in").val(made);
        $("#edit_sell_price").val(sell);
        $("#edit_sell_price_percentage").val(sellpercent);
        $("#edit_average_price").val(avg);
        if(come_type ==1){
          $("#come_type").attr('style','display: none;');
        }else{
          $("#come_type").attr('style','');
        }
        $('#edit_form_cont').modal('toggle');

    }

    function delete_items(itemid,pid) {
        block = $("#list_of_items_tbl");
        // bootstrap modal confirmation box
          swal({
              title: "Are you sure?",
              text: "You will not be able to recover this record!1",
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: "Yes, delete it!",
              cancelButtonText: "No, cancel",
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_purchase1.php",
                  type:"POST",
                  data: {"type":"delete","obj_id":itemid,product_id:pid} ,
                  complete:function(){
                    //hideLoader();
                  },
                  beforeSend:function(){
                    //showLoader("Deleting Purchase");
              },
                  success: function(res) {
                    if(res == 1){
                      get_Products();
                      swal({
                                  title: "Deleted!",
                                  text: "Purchase has been deleted.",
                                  confirmButtonColor: "#66BB6A",
                                  type: "success"
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: "Cancelled",
                                  text: "Your record file is safe, some thing went wrong.",
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              }
          }); // /confirm
    }

    function Checks(id,types=null,min=null,max=null,badge=null){
        var name = $("#"+id).val();
        var placeholder = $("#"+id).attr('placeholder');
        if(types == null){  // it mean string

              if(min !=null && max !=null){
                  if(name =='' || name.length < min || name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min + " and maximum length " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name ==''  || name.length < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min ,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name ==''  ||  name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with  maximum length of " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name ==''){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "حقل " + placeholder + " لا يجب ان يبقى فاغ",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }else if(types == 'No'){  // it mean numbers

              if(min !=null && max !=null){
                  if(name !='' && isNaN(name) || name < min || name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value between "+ min + " and " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null && badge !=null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).removeClass('badge-primary');
                    $("#"+id).addClass('badge-warning');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Greater than "+ min,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).removeClass('badge-warning');
                      $("#"+id).addClass('badge-primary');
                      return true;
                  }


                }else if(min !=null && max ==null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');
                    
                    noty({
                            width: 200,
                            text: "الرجاء قم بادخال قيمة عددية اكبر او تساوي "+ min + " في حقل " + placeholder,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name !='' && isNaN(name) ||  name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Less than " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name !='' && isNaN(name)){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }
    }

    
    function show_invoice(itm,printing=null,detail_show=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";

          $.ajax({
                url : 'models/crul_invoice_curt.php',
                type : 'POST',
                data : {type:'show_invoice', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                        headers =`

                                    <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                                       style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: left; font-size: 20px;" id="inv_slogan">`+COMPANY_NAME+`</span>
                                        </td>
                                       </tr>
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                                        </td>
                                        <td width=295 colspan=3 rowspan=2 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_logo">  </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                       `+Translation('موبايل')+`  : <span dir="ltr" id="inv_phone"> `+COMPANY_PHONE+` </span>
                                        <br>
                                       `+Translation('البريد الالكتروني')+`  : <span dir="ltr" id="inv_email"> `+COMPANY_EMAIL+` </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=118 style='width:88.55pt;' class="table0_td1">
                                       `+Translation('رقم الوصل')+`  :
                                        </td>
                                        <td width=139 style='width:1.45in;' class="table0_td1">
                                        <span id="inv_num" style="color:red;">`+response.invoice[0].invoice_number+`</span>
                                        </td>
                                        <td width=77 colspan=2 style='width:.8in;' class="table0_td1">
                                        
                                        </td>
                                        <td width=116 style='width:87.3pt;' class="table0_td1">
                                       `+Translation('التــــــــــــاريخ')+`  :     
                                        </td>
                                        <td width=140 style='width:104.95pt;' class="table0_td1">
                                        <span id="inv_date">`+response.invoice[0].invoice_date+`</span>
                                        </td>
                                       </tr>
                                       
                                       
                                      </table>
                                      <br>
                                          `;
                        
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:6.2in;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:443.5pt;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=57 style='width:42.75pt;' class="table2_td">
                                    
                                   `+Translation('الارتفاع')+` 
                                    </td>
                                    <td width=57 style='width:42.75pt;' class="table2_td">
                                   `+Translation('العرض')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('الطول الكلي  / المساحة')+` 
                                    </td>
                                    <td width=73 style='width:54.9pt;' class="table2_td">
                                   `+Translation('سعر الوحدة')+`  
                                    </td>
                                    <td width=73 style='width:54.9pt;' class="table2_td">
                                   `+Translation('سعر متر الديكور')+`  
                                    </td>
                                    <td width=79 style='width:58.95pt;' class="table2_td">
                                   `+Translation('التنزيلات')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td last_td">
                                   `+Translation('المجموع')+` 
                                    </td>
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){

                          
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          if(response.invoice[i].total_area > 0){
                            total_row_price = +(response.invoice[i].total_area * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_price_per_meter) - response.invoice[i].actual_discount;
                            total_row_price = currency_format_display(total_row_price);
                          }else{
                            total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                            total_row_price = currency_format_display(total_row_price);
                          }
                          
                        }



                        if(response.invoice[i].product_id_fk > 0){
  
                          // we should Check for total area if greater than 0 it mean its curtain and we should show the width else we show just height and collpase td
                          
                          if(response.invoice[i].total_area > 0){

                            // display sell item details
                            var attach_height ='';
                            var attach_width ='';
                            // i will show just one height and width because we have quantity
                            for(var j=0 ; j < response.details.length;j++){
                              var sell_id = response.invoice[i].sell_item_id;

                              if(sell_id == response.details[j].sell_item_id_fk){
                                // attach_height = attach_height + ` <input types="text"  class="badge bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                                // attach_width  = attach_width  + ` <input types="text"  class="badge bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_width+`" readonly> `;
                                attach_height =  ` <input types="text"  class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                                attach_width  =  ` <input types="text"  class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_width+`" readonly> `;
                              
                              }
                            }


                            attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=57 style='width:42.75pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                                      `+attach_height+`
                                                      </span>
                                                    </td>
                                                    <td width=57 style='width:42.75pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                                      `+attach_width+`
                                                      </span>
                                                    </td>
                                                
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+parseFloat(response.invoice[i].total_area).toFixed(2)+` م<sup>2</sup> </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].item_sell_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].decorate_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <span  id="inv_discount">`+ disss +` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                   </tr>
                                                  `;

                          }else{ // raw products

                            // display sell item details
                        
                            var Det = '';
                            if(detail_show != null){

                              // display sell item details
                              for(var j=0 ; j < response.details.length;j++){
                                var sell_id = response.invoice[i].sell_item_id;

                                if(sell_id == response.details[j].sell_item_id_fk){
                                  Det = Det + ` <input types="text"  class="badge bg-orange-400 col-sm-4" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                                }
                              }
                            }

                            attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td colspan="2" width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                            `+Det+`   </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].total_length+` م </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].item_sell_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].decorate_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <span  id="inv_discount">`+ disss +` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                   </tr>
                                                  `;


                          }
                          
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td colspan="2" width=114 style='width:85.5pt;'>
                                                      <span  id="inv_details">
                                                      </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length">  </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].item_sell_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price">  </span>
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <span  id="inv_discount">`+ disss +` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                      if(printing != null){
                        print_attach = `
                                        <script>
                                          window.print();
                                          window.onload = function() { window.print(); }
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }

                      footers =`<tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=439 colspan=8  style='width:329.05pt;border-top:solid #984806 1.0pt;
                                  border-left:solid #984806 1.0pt;border-bottom:none;border-right:none;
                                  background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                 `+Translation('التنزيلات')+` 
                                  </td>
                                  <td width=79 style='width:58.95pt;border:solid #984806 1.0pt;border-right:
                                  none;padding:0pt 0in 0pt 0in;height:.1in;text-align: center;'>
                                  `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                  <td width=74 style='width:55.5pt;border:solid #984806 1.0pt;border-right:
                                  none;padding:2.15pt .15in 2.15pt .15in;height:.1in'>
                                  
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=9 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=9 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=9 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=10  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note"> `+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=9  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                       HTML_VIEW = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                        window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

     function show_sticker(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice_curt.php',
                type : 'POST',
                data : {type:'show_sticker', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                       
                       
                     
                      // show all stickers                       
                      for(var i=0 ; i < response.sticker.length;i++){

                          attach = attach + `
                                            <table class=MsoNormalTable dir=rtl border=0 cellspacing=0 cellpadding=0 width=353 style='width:264.8pt;border-collapse:collapse; font-weight: bolder;'>
                                               <tr style='height:19.9pt; text-align: center;'>
                                                  <td width=245 colspan=3 style='width:183.75pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+COMPANY_NAME+`
                                                  </td>
                                                  <td width=108 style='width:81.05pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].invoice_date+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الزبون')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].customer_full_name+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الرمز')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].product_name+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('العرض (م)')+` :
                                                  </td>
                                                  <td width=67 style='width:50.5pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].sell_item_detail_width+`
                                                  </td>
                                                  <td width=108 style='width:81.05pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الارتفاع (م)')+` :
                                                  </td>
                                                  <td width=83 style='width:62.0pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].sell_item_detail_height+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('ملاحظات')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].sell_item_notes+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('المستلم')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].sell_item_delivery_name+`
                                                  </td>
                                               </tr>
                                               
                                            </table>
                                            <div class="page-break"></div>
                                            <br>
                                                  `;
                      
                       
                      } // for i

                      if(printing != null){
                        print_attach = `
                                        <script>
                                          window.print();
                                          window.onload = function() { window.print(); }
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }

                      footers =`        </div>

                                      </div>

                                  </body>

                                </html>

                                `+print_attach+`
                               `;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      
                        $("#sticker_show").html(HTML_VIEW_PAY);
                        $("#sticker_inv_numb").val(itm);

                        $('#show_sticker_modal').modal('toggle');
                      
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    function add_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice_curt.php',
                type : 'POST',
                data : {type:'show_payments_for_add', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                        
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:90%;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('رقم الوصل')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].invoice_number+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:90%;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('مجموع السعر')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;'  class="table2_td">
                                   `+Translation('المبلغ المدفوع لهذه المادة')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td ">
                                   `+Translation('الدفعة الجديدة')+` 
                                    </td>
                                    <td width=79 style='width:58.95pt;' class="table2_td">
                                   `+Translation('الباقي')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td last_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;
                        var total_row_price_no_format = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price_no_format = total_row_price;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          
                          if(response.invoice[i].total_area > 0){ // it mean its curtain
                            total_row_price = +(response.invoice[i].total_area * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_price_per_meter) - response.invoice[i].actual_discount;
                            total_row_price_no_format = total_row_price;
                            
                            total_row_price = currency_format_display(total_row_price);
                          }else{
                            total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                            total_row_price_no_format = total_row_price;
                          
                            total_row_price = currency_format_display(total_row_price);

                          }
                        }




                        // calculate remained price 

                        var remianed_pay = total_row_price_no_format - response.invoice[i].total_paid_per_product;

                        if(response.invoice[i].product_id_fk > 0){
  
                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>

                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product_`+i+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`"> `+response.invoice[i].product_name+` </span>
                                                    </td>

                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>

                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <input type="text" id="product_row_total_`+i+`" name="product_row_total_`+i+`" data-actual-row-price="`+total_row_price_no_format+`" class="form-control text-center" value="`+total_row_price+`" placeholder="`+Translation('مجموع السعر')+`" readonly >
                                                    </td>

                                                    <td width=74 style='width:55.5pt;' >
                                                      <input type="text" id="inv_total_paid_`+i+`" data-old-paid-price="`+response.invoice[i].total_paid_per_product+`" name="inv_total_paid_`+i+`" class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_paid_per_product)+`" placeholder="`+Translation('المبلغ المدفوع لهذه المادة')+`" readonly >
                                                    </td>

                                                    <td width=87  style='width:65.25pt;'>
                                                      <input type="text" id="inv_paid_price_`+i+`" name="inv_paid_price_`+i+`" class="form-control text-center text-success" placeholder="`+Translation('الدفعة الجديدة')+`" onchange="compute_remain_price(this.value,this.id);" >  
                                                    </td>
                                                    
                                                    <td width=79 style='width:58.95pt;'>
                                                      <input type="text" id="inv_row_remaind_price_`+i+`" name="inv_row_remaind_price_`+i+`" class="form-control text-center" value="`+currency_format_display(remianed_pay)+`"  placeholder="`+Translation('الباقي')+`" readonly >
                                                    </td>

                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <textarea type="text" id="pay_note_`+i+`" name="pay_note_`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" ></textarea> 
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product_other" data-sell-id-fk="`+response.invoice[i].sell_item_id+`"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      
                                                      <input type="text" id="product_row_total_other" data-actual-row-price="`+total_row_price_no_format+`" name="product_row_total_other" class="form-control text-center" value="`+total_row_price+`" placeholder="`+Translation('مجموع السعر')+`" readonly >

                                                    </td>
                                                    <td width=74 style='width:55.5pt;'>
                                                      <input type="text" id="inv_total_paid_other" data-old-paid-price="`+response.invoice[i].total_paid_per_product+`" name="inv_total_paid_other" class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_paid_per_product)+`" placeholder="`+Translation('المبلغ المدفوع لهذه المادة')+`" readonly >
                                                      
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <input type="text" id="inv_paid_price_other" name="inv_paid_price_other" class="form-control text-center" placeholder="`+Translation('الدفعة الجديدة')+`" onchange="compute_remain_price(this.value,this.id);" >  
                                                      
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <input type="text" id="inv_row_remaind_price_other" name="inv_row_remaind_price_other" class="form-control text-center" value="`+currency_format_display(remianed_pay)+`"   placeholder="`+Translation('الباقي')+`" readonly >
                                                    </td>
                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <textarea type="text" id="pay_note_other" name="pay_note_other" class="form-control" placeholder="`+Translation('ملاحظات')+`" ></textarea> 
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                      

                      // total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('التنزيلات')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   <span class="text-info text-black" id="total_inv_actual" data-total-inv-actual='`+response.invoice[0].invoice_total_price_actual+`'>`+currency_format_display(response.invoice[0].invoice_total_price_actual)+`</span>
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  <span class="text-green text-black" id="total_inv_paid" data-total-inv-paid='`+response.invoice[0].total_paid+`'>`+currency_format_display(response.invoice[0].total_paid)+`</span>
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  <span class="text-warning text-black" id="total_inv_remain">`+currency_format_display(response.invoice[0].total_remained)+`</span>
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=8  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      
                        $("#invoice_pay_add").html(HTML_VIEW_PAY);
                        $("#inv_numb_pay").val(itm);

                        $('#add_payments_modal').modal('toggle');
                      
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    function show_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice_curt.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                        headers =`

                                    <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                                       style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: left; font-size: 20px;" id="inv_slogan">`+COMPANY_NAME+`</span>
                                        </td>
                                       </tr>
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                                        </td>
                                        <td width=295 colspan=3 rowspan=2 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_logo">  </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                       `+Translation('موبايل')+`  : <span dir="ltr" id="inv_phone"> `+COMPANY_PHONE+` </span>
                                        <br>
                                        البريد الالكتروني : <span dir="ltr" id="inv_email"> `+COMPANY_EMAIL+` </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=118 style='width:88.55pt;' class="table0_td1">
                                       `+Translation('رقم الوصل')+`  :
                                        </td>
                                        <td width=139 style='width:1.45in;' class="table0_td1">
                                        <span id="inv_num" style="color:red;">`+response.invoice[0].invoice_number+`</span>
                                        </td>
                                        <td width=77 colspan=2 style='width:.8in;' class="table0_td1">
                                        
                                        </td>
                                        <td width=116 style='width:87.3pt;' class="table0_td1">
                                       `+Translation('التــــــــــــاريخ')+`  :     
                                        </td>
                                        <td width=140 style='width:104.95pt;' class="table0_td1">
                                        <span id="inv_date">`+response.invoice[0].invoice_date+`</span>
                                        </td>
                                       </tr>
                                       
                                       
                                      </table>
                                      <br>
                                          `;
                        
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:6.2in;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:443.5pt;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('مجموع السعر')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('المبلغ المدفوع')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('تاريخ الدفع')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td last_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          
                          if(response.invoice[i].total_area > 0){ // it mean its curtain
                            total_row_price = +(response.invoice[i].total_area * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_price_per_meter) - response.invoice[i].actual_discount;                            
                            total_row_price = currency_format_display(total_row_price);
                          }else{
                            total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                            total_row_price = currency_format_display(total_row_price);


                          }

                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' >
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <span  id="inv_details">`+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;' class="last_td">
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                      if(printing != null){
                        print_attach = `
                                        <script>
                                          window.print();
                                          window.onload = function() { window.print(); }
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('')+` التنزيلات
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("هذه الوصل لا يحتوي على اي دفوعات"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#invoice_show").html(HTML_VIEW_PAY);
                        $("#inv_numb").val(itm);

                        $('#show_payments_modal').modal('toggle');
                      }
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }


    function edit_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice_curt.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                       
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:90%;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:90%;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('مجموع السعر')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('المبلغ المدفوع')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('تاريخ الدفع')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td last_td">
                                   `+Translation('العمليات')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          if(response.invoice[i].total_area > 0){ // it mean its curtain
                            total_row_price = +(response.invoice[i].total_area * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_price_per_meter) - response.invoice[i].actual_discount;                            
                            total_row_price = currency_format_display(total_row_price);
                          }else{
                            total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                            total_row_price = currency_format_display(total_row_price);


                          }
                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <input type="text" id="edit_inv_paid_price_`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_`+i+`" class="form-control text-center text-success text-black" placeholder="`+Translation('الدفعة الجديدة')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_`+i+`" name="edit_pay_note_`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حفظ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حذف الدفعة')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <input type="text" id="edit_inv_paid_price_other`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_other`+i+`" class="form-control text-center text-success text-black" placeholder="`+Translation('الدفعة الجديدة')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_other`+i+`" name="edit_pay_note_other`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_other`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حفظ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_other`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حذف الدفعة')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>

                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                     

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('التنزيلات')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("هذه الوصل لا يحتوي على اي دفوعات"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#edit_payments_fields").html(HTML_VIEW_PAY);
                        $("#edit_pay_inv_id").val(itm);

                        $('#edit_payments_modal').modal('toggle');
                      }
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    function update_payments (id){

        var row_num1        = id.split('_');
        var row_num         = row_num1[3];

        var inv_id          = $("#edit_pay_inv_id").val();
        var notes           = $("#edit_pay_note_"+row_num).val();
        var paid            = $("#edit_inv_paid_price_"+row_num).val();
        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

        if (paid.indexOf('$') > -1)
          {
            
             paid = paid.replace('$','');
            
          }

        if (paid.indexOf(',') > -1)
          {
            
             paid = paid.replace(/,/g,'');
            
          }

          paid = parseFloat(paid);


        var check1          = true;

        if(paid == '' || paid <= 0 || paid == null || paid == undefined || isNaN(paid)){
            noty({
                    width: 200,
                    text: Translation('الرجاء قم بادخال مبلغ دفعه'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 2000,
                    layout: 'topRight',
              });
            check1 = false;
        }



        if(check1){
            $("#save_payment_"+row_num).attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice_curt.php",
                type:"POST",
                dataType: "JSON",
                data : {inv_id              :inv_id,
                        paid                :paid,
                        sell_ids            :sell_id_fk,
                        payment_id          :payment_id,
                        notes               :notes,
                        type                :'update_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $('#edit_payments_modal').modal('toggle');
                    
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                
                $("#save_payment_"+row_num).attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                
                $("#save_payment_"+row_num).attr('disabled',false);

            })
            .always(function() {
                console.log("complete");
            });
          }else{
              noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

        
    }


    function remove_payments (id){

          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText:  Translation("موافق: امسح!"),
              cancelButtonText:   Translation("الغاء الامر"),
              closeOnConfirm: true,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {

                        var row_num1        = id.split('_');
                        var row_num         = row_num1[3];

                        var inv_id          = $("#edit_pay_inv_id").val();
                        var notes           = $("#edit_pay_note_"+row_num).val();
                        var paid            = $("#edit_inv_paid_price_"+row_num).val();
                        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
                        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

                        if (paid.indexOf('$') > -1)
                          {
                            
                            var paid = parseFloat(paid.replace('$',''));
                            
                          }

                        var check1          = true;

                        



                        if(check1){
                            $("#remove_payment_btn_"+row_num).attr('disabled',true);
                            $.ajax({
                                url: "models/crul_invoice_curt.php",
                                type:"POST",
                                dataType: "JSON",
                                data : {inv_id              :inv_id,
                                        paid                :paid,
                                        sell_ids            :sell_id_fk,
                                        payment_id          :payment_id,
                                        notes               :notes,
                                        type                :'delete_payments'}
                            })
                            .done(function(res) {
                               
                                  if(res.is_success == true){

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

                                   

                                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                                    $('#edit_payments_modal').modal('toggle');
                                    
                                    noty({
                                                    width: 200,
                                                    text: Translation(res.data),
                                                    type: 'success',
                                                    dismissQueue: true,
                                                    timeout: 2000,
                                                    layout: 'topRight',
                                                    callback: {
                                                              onShow: function() {},
                                                              afterShow: function() {},
                                                              onClose: function() {},
                                                              afterClose: function() {},
                                                              onCloseClick: function() {},
                                                            },
                                              });

                                    // i will reload the page to reset all fields
                                    
                               
                                }else{
                                    swal({
                                        title: Translation("خطأ"),
                                        text: Translation(res.data),
                                        confirmButtonColor: "#66BB6A",
                                        type: "warning"
                                    });
                                    //$("#add-form-cont").collapse('hide');
                                }

                                
                                $("#remove_payment_btn_"+row_num).attr('disabled',false);
                            })
                            .fail(function(err) {
                                 swal({
                                    title: Translation("خطأ"),
                                    text: Translation(err),
                                    confirmButtonColor: "#66BB6A",
                                    type: "error"
                                });
                                
                                $("#remove_payment_btn_"+row_num).attr('disabled',false);

                            })
                            .always(function() {
                                console.log("complete");
                            });
                        }else{
                            noty({
                                  width: 200,
                                  text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                            });
                        }
               
              }
          }); // /confirm



        
    }


    $('#print_pay').click(function(e) {
      e.preventDefault();
         print_invoice('Print','pay');
    });

    $('#pdf_pay').click(function(e) {
      e.preventDefault();
         print_invoice('PDF','pay');
    });


    function compute_remain_price(val, id){

      var row_num1 = id.split('_');
      var row_num = row_num1[3];
      if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
        val = val;
      }else{
        val = 0;
      }
        var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price'); 
        var old_paid   = $("#inv_total_paid_"+row_num).attr('data-old-paid-price');
        
          // alert("old_paid="+old_paid)

        if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_paid   == null || old_paid   == undefined || isNaN(old_paid)){old_paid=0; }
       
        var new_remaind = real_price - (+old_paid + +val);

       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي للمادة"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          // $("#inv_row_remaind_price_"+row_num).val('');
          $("#"+id).val('');
          // we should return the old remaind too
          $("#inv_row_remaind_price_"+row_num).val(currency_format_display( real_price - old_paid));

        }else{
          $("#inv_row_remaind_price_"+row_num).val(currency_format_display( new_remaind));

        }

        // compute total invoice paid and total remained
          var sum = 0;        

          $('input[id^="inv_paid_price_"]').each(function() 
          { 
            if(!isNaN(this.value) && this.value.length!=0) 
            {
              sum += parseFloat(this.value);            
            }         
          });

          var old_papid   = $("#total_inv_paid").attr('data-total-inv-paid');
          if(old_papid   == null || old_papid   == undefined || isNaN(old_papid)){old_papid=0; }

          var new_pay = +old_papid + +sum;
          $("#total_inv_paid").html(currency_format_display(new_pay));

          var old_actual_price   = $("#total_inv_actual").attr('data-total-inv-actual');
          if(old_actual_price   == null || old_actual_price   == undefined || isNaN(old_actual_price)){old_actual_price=0; }

          var all_invoice_remaind = old_actual_price - new_pay;
          $("#total_inv_remain").html(currency_format_display(all_invoice_remaind));

    }
    

    function print_invoice(typ,payment=null){
      if(typ=='Print'){
        window.open().document.write(HTML_VIEW_PAY+print_page);
      }else if(typ=='PDF'){
        var nn = $("#inv_numb").val();
        pdf_generator(HTML_VIEW_PAY,nn,'pay')
      }else{
        window.open().document.write(HTML_VIEW_PAY);
      }
    }

    function pdf_generator(HTML,INV_NO,payment){

                $.ajax({
                      url : 'models/crul_invoice.php',

                      type : 'POST',
                      data : {type:'PDF',html:HTML,inv_no:INV_NO,pay:payment},
                      dataType : 'json',
                      success : function(response) {
                            console.log(response)
                            if(response.is_success == true) {

                                    noty({
                                        width: 200,
                                        text: Translation('تم توليد ملف الـ PDF بنجاح'),
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'top',
                                    });
                                    var LINKS = '<a class="btn btn-labeled btn-labeled-left heading-btn btn-info" href="'+response.data+'" target="_blank" style="float: right;"> '+Translation('تحميل')+' <b><i class="icon-file-download"></i></b> </a>';
                                    if(payment !=null){
                                      $("#link_pdf_pay").append(LINKS);
                                    }else{
                                      $("#link_pdf").append(LINKS);
                                    }

                                  
                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            } else {

                               noty({
                                     width: 200,
                                     text: Translation(response.message),
                                     type: 'error',
                                     dismissQueue: true,
                                     timeout: 3000,
                                     layout: 'top',
                               });

                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            }
                      },
                      complete: function() {
                            //   me.data('requestRunning', false);
                      }

                }); // submit ajax
    }

    function get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('تحديد المخزن')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =Translation("خزن");
                          if(response[i][2]==1){tp =Translation("انتاج");}
                          attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                        }
                        $("#stock_id_fk").html(attach);
                        $("#edit_category_id").html(attach);
                        $('#stock_id_fk').selectpicker('refresh');
                        $("#edit_category_id").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

    function get_Profile_price(){

            $.ajax({
                  url : 'models/crul_profile_price.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('تحديد ملف السعر')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp ="";
                          attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                        }
                        $("#price_profile_id").html(attach);
                        $("#edit_price_profile_id").html(attach);
                        $('#price_profile_id').selectpicker('refresh');
                        $("#edit_price_profile_id").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }



    function get_Customer(){

            var cust_typ  = getQueryVariable("typ");

            $.ajax({
                  url : 'models/crul_customer.php',
                  type : 'POST',
                  data : {type:'get_Customer',cust_typ:cust_typ},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('تحديد الزبون')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp  = response[i][2];
                          var tp1 = response[i][3];
                          attach = attach + '<option data-subtext="'+Translation('هاتف')+': '+tp+' || E-Mail: '+tp1+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                        }
                        $("#customer_id_fk").html(attach);
                        $("#edit_customer_id_fk").html(attach);
                        $('#customer_id_fk').selectpicker('refresh');
                        $("#edit_customer_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

    var products_array_values =[] ;

  

    function get_Others(){

        $.ajax({
                  url : 'models/crul_invoice.php',
                  type : 'POST',
                  data : {type:'get_others'},
                  dataType : 'json',
                  success : function(response) {
                    console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('مواد اخرى')+'</option>';
                    
                        for(var i=response.length-1 ; i >= 0;i--){
                         
                          attach = attach + '<option data-subtext="  '+response[i][2]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                        }
                        $("#other_id_fk").html(attach);
                        $('#other_id_fk').selectpicker('refresh');
                        //$("#edit_product_id").html(edit_attach);

                  },
                  complete: function() {

                  }

            }); // submit ajax

        }


    function load_prices(row_num){
      // load price for this product

          var PP_ID = $("#price_profile_id").val();
          var P_ID  = $("#product_id_fk_"+row_num).val();
          

          if(PP_ID=='' || PP_ID ==null){
              noty({
                      width: 200,
                      text: Translation("الرجاء اختيار ملف سعر لتحميل الاسعار منه"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',

                    });
          }

          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get',PP_ID:PP_ID,p_val:P_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#buy_price_per_meter_"+row_num).val('');
                          // $("#last_sell_price_"+row_num).val('');
                          
                          noty({
                            width: 200,
                            text: Translation("لا يوجد سعر بيع لهذه المادة"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#buy_price_per_meter_"+row_num).val(response[0][1]);
                          // $("#last_sell_price_"+row_num).val(response[0][2]); 
                          
                        }
                  },
                  complete: function() {
                    load_last_prices(row_num);
                  }

            }); // submit ajax
      // end loading price
    }

    function load_last_prices(row_num){
      // load price for this product

          
          var P_ID  = $("#product_id_fk_"+row_num).val();
          // to load the last sell price for this customer
          var Cus_ID  = $("#customer_id_fk").val();

          if(Cus_ID=='' || Cus_ID ==null){
              noty({
                      width: 200,
                      text: Translation("الرجاء قم بتحديد اسم الزبون لتحميل اخر سعر بيع له"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',
                    });
          }


          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get_last_sell_price',p_val:P_ID,Cus_ID:Cus_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#last_sell_price_"+row_num).val('');
                          $("#last_sell_price_decor_"+row_num).val('');

                          
                          noty({
                            width: 200,
                            text: Translation("لا يوجد اخر سعر بيع لهذا الزبون"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#last_sell_price_"+row_num).val(response[0][0]); 
                          $("#last_sell_price_decor_"+row_num).val(response[0][1]); 
                          
                        }
                  },
                  complete: function() {

                  }

            }); // submit ajax
      // end loading price
    }

    function load_products1(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[2];
        if(val !=""){

          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_one_product_sell',p_val:val},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response.length==0){
                          $("#product_id_fk_"+row_num).val('');
                          $("#forign_id_"+row_num).html('');
                          noty({
                            width: 200,
                            text: Translation("لا توجد هكذا مادة الرجاء التاكد من الكود"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{

                          $("#product_id_fk_"+row_num).val(response[0][0]);
                          $("#item_type_id_"+row_num).val(response[0][3]);
                          $("#forign_id_"+row_num).html(response[0][2]);

                          load_prices(row_num);
                          
                        }

                        // to reset the selected product when change product
                        $("#products_"+row_num).html('');
                        $("#total_length_"+row_num).val('');
                  },
                  complete: function() {

                  }

            }); // submit ajax

        }

         
    }


    function load_products(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[3];
        
        var forgin_code = $("#product_id_fk_"+row_num+" option:selected").attr('data-forgin-code');
        var item_type_   = $("#product_id_fk_"+row_num+" option:selected").attr('data-item_type_id');

        $("#forign_id_"+row_num).html(forgin_code);
        $("#item_type_id_"+row_num).val(item_type_);

        // we should show modal for input rolls length 
        var qty = $("#purchase_quantity_"+row_num).val();

        load_prices(row_num);

        // to reset the selected product when change product
        $("#products_height_"+row_num).html('');
        $("#products_height_"+row_num).html('<input type="text" id="curtain_height_'+row_num+'" name="curtain_height_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('الارتفاع')+'"  onchange="compute_area(this.value,this.id,'+row_num+');">');

        $("#products_width_"+row_num).html('');
        $("#products_width_"+row_num).html('<input type="text" id="curtain_width_'+row_num+'" name="curtain_width_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('العرض')+'"  onchange="compute_area(this.value,this.id,'+row_num+');">');


        $("#total_length_"+row_num).val('');
        
        add_qty_input_fields(qty,"purchase_quantity_"+row_num);

    }

    // make products as searchable list

    function get_products(row_num){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_product_sell'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('اختيار المادة')+'</option>';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          var tp =response[i][2];
                          attach = attach + '<option  data-subtext="'+Translation('الرمز الاجنبي : ')+tp+'" value="'+response[i][0]+'" data-forgin-code="'+response[i][2]+'" data-item_type_id="'+response[i][3]+'">'+response[i][1]+'</option>';
                        }
                        $("#product_id_fk_"+row_num).html(attach);
                        $('#product_id_fk_'+row_num).selectpicker('refresh');

                        $("#edit_product_id_fk_"+row_num).html(attach);
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }


    // this function just to show how many he select roll in the top of modal
    function total_sel_length(){

      var total=$('input[id^="checked_roll_"]:checked').length;
      $("#total_selected").html(total);

      var sum = 0;        
      $('input[id^="part_roll_length_"]').each(function() 
      { 
        if(!isNaN(this.value) && this.value.length!=0) 
        {
          sum += parseFloat(this.value);            
        }         
      });

      $("#total_sel_roll_length").html(sum);
    }

    function part_sell(cnt){
      

      var chk = $("#checked_roll_"+cnt).is(':checked');

      if(chk){
        var roll_length = $("#checked_roll_"+cnt).attr('data-remained-length');
        $("#part_roll_length_"+cnt).val(roll_length);
      }else{
        $("#part_roll_length_"+cnt).val('');
      }
      total_sel_length();
      
    }

    function part_sell2(cnt){
      

      // if he enter value in textbox we should check automatically the checkbox
      var roll_val = $("#part_roll_length_"+cnt).val();
      var roll_length = $("#checked_roll_"+cnt).attr('data-remained-length');
      if(roll_val !=''){
        // check val not 0 or greater than roll length?
        
        if(parseFloat(roll_val) > parseFloat(roll_length) || parseFloat(roll_val) <= 0 || isNaN(parseFloat(roll_val)) ){
          $("#part_roll_length_"+cnt).val(roll_length);
        }
        $("#checked_roll_"+cnt).prop('checked', true);
      }else{
        $("#checked_roll_"+cnt).prop('checked', false);
      }
      total_sel_length();
    }

    function add_qty_input_fields(qty,id){
      // console.log(qty);
       // alert(qty);
      var row_num1 = id.split('_');
      var row_num  = row_num1[2];

      

      if(qty >0 && qty !=""){

          // we should check if this product have purchase or not

          var p_id = $("#product_id_fk_"+row_num).val();
          if(p_id == null || p_id == '' || p_id == undefined || p_id < 1){

            noty({
                    width: 200,
                    text: Translation('الرجاء قم باختيار المادة اولا'),
                    type: 'information',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
                });

          }else{
            $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'check_item_type',p_id:p_id},
                  dataType : 'json',
                  success : function(response) {
                    if(response[0][6]==0){ // is have curtain 0: havnt we should show him to select product from purchase; 1: have curtain and we wont show him any thing because he will write the height and width of curtain
                     if(response[0][4]==0){ // have purchase
                        // we should show modal to select the products
                        $("#fields_count_purchase").val(qty);
                        $("#rows_count_purchase").val(row_num);
                        

                        $.ajax({
                                url : 'models/crul_invoice.php',
                                type : 'POST',
                                data : {type:'get_purchase_product',p_id:p_id},
                                dataType : 'json',
                                success : function(res) {
                                  $("#rolls_count_purchase").val(res.data.length);
                                  // get number of store stock for sorting & Grouping
                                  
                                  var attach_input =`<style> .tab-content{display: -webkit-box;} .nav-tabs.nav-justified > li > a {display: block; }
                                                    .nav.nav-lg > li > a {height: 60px;} </style>`;
                                  for (var j = 0; j < res.stocks.length; j++) {
                                    
                                    var panel_header ='white';                    

                                    if(res.stocks[j][2]==1){
                                      panel_header ='success';
                                    }
                                   attach_input = attach_input + `
                                                                  <!-- Heading badge -->
                                                                  <div class="panel panel-`+panel_header+`">
                                                                    <div class="panel-heading">
                                                                      <h6 class="panel-title">`+res.stocks[j][1]+`</h6>
                                                                      <div class="heading-elements">
                                                                        <span class="badge bg-indigo-400 heading-text">`+res.stocks[j][3]+`</span>
                                                                      </div>
                                                                    </div>
                                                                    
                                                                    <div class="panel-body">
                                                                        <!-- Tabs widget -->
                                                                        <div class="tab-content-bordered content-group">
                                                                          <ul class="nav nav-tabs nav-tabs-highlight nav-lg nav-justified">
                                                                            <li class="active"><a href="#complete_roll`+j+`" data-toggle="tab">`+Translation('مواد كاملة')+`</a></li>
                                                                            <li><a href="#just_damage`+j+`" data-toggle="tab">`+Translation('مواد جزء منها تالف')+`</a></li>
                                                                            <li><a href="#partiall_sold`+j+`" data-toggle="tab">`+Translation('مواد بيعت بالتجزئة')+`</a></li>
                                                                            <li><a href="#partiall_sold_used`+j+`" data-toggle="tab">`+Translation('مواد بيعت بالتجزئة واستخدمت بالانتاج')+`</a></li>
                                                                            <li><a href="#used_in_production`+j+`" data-toggle="tab">`+Translation('مواد استخدمت فقط في الانتاج')+`</a></li>
                                                                          </ul>

                                                                          <div class="tab-content">
                                                                  `;
                                    var tab_complete_roll       =`<div class="tab-pane has-padding active" id="complete_roll`+j+`">`;
                                    var tab_just_damage         =`<div class="tab-pane has-padding " id="just_damage`+j+`">`;
                                    var tab_partiall_sold       =`<div class="tab-pane has-padding " id="partiall_sold`+j+`">`;
                                    var tab_partiall_sold_used  =`<div class="tab-pane has-padding " id="partiall_sold_used`+j+`">`;
                                    var tab_used_in_production  =`<div class="tab-pane has-padding " id="used_in_production`+j+`">`;
                                    
                                    for (var i = 0; i < res.data.length; i++) {
                                      var item_input = '';
                                      if(res.stocks[j][0] == res.data[i][3]){
                                        // now we should check item_status and group it according to item status
                                        item_input =  `
                                                        <div class="form-group col-sm-3">
                                                            <div class="input-group">
                                                              <span class="input-group-addon">
                                                                <input type="checkbox" class="styled" data-item-status="`+res.data[i][4]+`" data-remained-length="`+res.data[i][5]+`" data-roll-length="`+res.data[i][1]+`" data-roll-id-fk="`+res.data[i][0]+`" id="checked_roll_`+i+`" name="checked_roll_`+i+`" onclick="part_sell(`+i+`);"  >
                                                              </span>
                                                              <span class="input-group-addon">`+res.data[i][5]+` </span> <!-- remainded length -->
                                                              <input type="number" id="part_roll_length_`+i+`" name="part_roll_length_`+i+`" class="form-control" placeholder="`+Translation('بيع بالتجزئة')+`" onchange="part_sell2(`+i+`);">
                                                              
                                                            </div>
                                                        </div>

                                                        `;

                                        switch (res.data[i][4])
                                        {
                                          case "0":
                                          case "2":
                                                tab_complete_roll = tab_complete_roll + item_input;
                                                break;
                                          case "8":
                                          case "11":
                                                tab_just_damage = tab_just_damage + item_input;
                                                break;
                                          case "5":
                                                tab_partiall_sold = tab_partiall_sold + item_input;
                                                break;
                                          case "9":
                                                tab_partiall_sold_used = tab_partiall_sold_used + item_input;
                                                break;
                                          case "3":
                                                tab_used_in_production = tab_used_in_production + item_input;
                                                break;
                                        }
                                        
                                      } // if stock
                                      
                                    } // for i
                                    
                                    tab_complete_roll       = tab_complete_roll + `</div>`;
                                    tab_just_damage         = tab_just_damage + `</div>`;
                                    tab_partiall_sold       = tab_partiall_sold + `</div>`;
                                    tab_partiall_sold_used  = tab_partiall_sold_used + `</div>`;
                                    tab_used_in_production  = tab_used_in_production + `</div>`;
                                    
                                    attach_input = attach_input + tab_complete_roll + tab_just_damage + tab_partiall_sold + tab_partiall_sold_used + tab_used_in_production;

                                   attach_input = attach_input + `    
                                                                        </div>
                                                                      </div>
                                                                      <!-- /tabs widget -->
                                                                    </div>
                                                                  </div>
                                                                  <!-- /heading badge -->
                                                                  `;
                                  } // for j

                                  

                                  $("#input_box_array_purchase").html(attach_input);
                                }
                              });

                        $('#add_new_product_from_purchase').modal('toggle');


                     }else{ // havn't purchase

                        // Modal for input rolls lengths
                        $("#fields_count").val(qty);
                        $("#rows_count").val(row_num);
                        var attach_input ="";
                        for (var i = 1; i <= qty; i++) {
                          attach_input = attach_input + `
                                                          <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                                            <label class="control-label">`+Translation('الطول')+`</label>
                                                            <input type="text" id="roll_length_`+i+`" name="roll_length_`+i+`" class="form-control" placeholder="`+Translation('الطول')+`" required="required">
                                                            <div class="form-control-feedback">
                                                              <i class="icon-pencil-ruler text-muted"></i>
                                                            </div>
                                                          </div>`;
                        }

                        $("#input_box_array").html(attach_input);
                        $('#add_new_product').modal('toggle');

                     }
                    }else{ // is have curtain
                      calc_total_item_cost(id,row_num);
                    }    
                  },
                  complete: function() {
                    
                  }

            }); // submit ajax
          }
            // end checking for purchasing or not


            

      }
      

    }


    function calc_total_length(row_no,qty){
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            total_roll_length = +total_roll_length + +$("#row_"+row_no+"_roll_"+i).val();
          }
          $("#total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
    }


    function calc_total_item_cost(id,row_no){
          var row_num1 = id.split('_');
          var row_num = row_no ; // row_num1[4];
          var actual_disc = 0;
          
          var total_item_cost = $("#total_length_"+row_num).val() * $("#buy_price_per_meter_"+row_num).val();
          
          // check if this product have curtain so we should include the decor cost also
          var sell_decor_price  = $("#buy_price_per_meter_decor_"+row_num).val();
          var height            = $("#curtain_height_"+row_num).val();
          var width             = $("#curtain_width_"+row_num).val();
          var qanty             = $("#purchase_quantity_"+row_num).val();

          
          
          if(!isNaN(height) && !isNaN(width) && height !='' && height !=null && height !=undefined && height >0 && width !='' && width !=null && width !=undefined && width >0){ // that mean its curtain because it have height and width, also we should mutliple it with qanity
            // alert('height='+height + ' width='+width)
            if(!isNaN(sell_decor_price) ){
              total_item_cost = (total_item_cost  + (sell_decor_price * width)) * qanty;
            }
          }

          // discount and checking for % or absolute val
          var discount = $("#sell_discount_"+row_no).val();
          if (discount.indexOf('%') > -1)
          {
            $("#sell_discount_"+row_no).attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);
              total_item_cost = total_item_cost - actual_disc;
              

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#sell_discount_"+row_no).attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;

          }

          $("#sell_discount_"+row_no).attr('data-discount-actual',actual_disc); // absolute discount

          $("#total_item_cost_"+row_num).val(currency_format_display(total_item_cost));  
          
          calc_total_purchase_price();
    }

    function calc_other_cost(){

          var total_item_cost = $("#other_quantity_1").val() * $("#buy_price_per_meter_other").val();
          var actual_disc = 0;
          // discount and checking for % or absolute val
          var discount = $("#sell_discount_other").val();
          if (discount.indexOf('%') > -1)
          {
            $("#sell_discount_other").attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);

              total_item_cost = total_item_cost - actual_disc;

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#sell_discount_other").attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;
          }

          $("#sell_discount_other").attr('data-discount-actual',actual_disc); // absolute discount

          $("#total_item_cost_other").val(currency_format_display(total_item_cost));  
          

          calc_total_purchase_price();

    }

    function calc_payments(row_num=null) {

          // check if current payment greater than row total price
          if(row_num !=null){

            if(row_num == 'other'){
              var cur_pay   = $("#other_pay").val();
              var prod_cost = $("#total_item_cost_other").val();

            }else{
              var cur_pay   = $("#product_pay_"+row_num).val();
              var prod_cost = $("#total_item_cost_"+row_num).val();

            }

            if (prod_cost.indexOf('$') > -1)
            {
              
               prod_cost = prod_cost.replace('$','');
              
            }

            if (prod_cost.indexOf(',') > -1)
            {
              
               prod_cost = prod_cost.replace(/,/g,'');
              
            }

            prod_cost = parseFloat(prod_cost);

            if(cur_pay > prod_cost){
              noty({
                        width: 200,
                        text: Translation("قيمة المبلغ المدفوع اكبر من المجموع الكلي لهذه المادة .. الرجاء ادخال القيمة الصحيحة"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });
              
              if(row_num == 'other'){
                $("#other_pay").val('');
              }else{
                $("#product_pay_"+row_num).val('');
              }
            }


          }
          
         // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#total_rows").val();
          for (var i = 1; i <= curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#product_pay_"+i).length > 0){
              var td_cost = $("#product_pay_"+i).val();
            
              
              if(isNaN(td_cost) || td_cost == ""){
                td_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(td_cost).toFixed(2);
            }
            
          }
          
          var other_price = $("#other_pay").val();
          if(isNaN(other_price)){
                other_price =0;
              }
          
          purchase_total = +purchase_total + +other_price;
          $("#total_paid").val(currency_format_display(purchase_total));

    }


    function calc_total_purchase_price(){
          // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#total_rows").val();
          for (var i = 1; i <= curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#total_item_cost_"+i).length > 0){
              var td_cost = $("#total_item_cost_"+i).val();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost ==""){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }
          // console.log(purchase_total +" TT");
          // calculate other

          var other_price = $("#total_item_cost_other").val();
          other_price = other_price.replace('$','');
          var other_val = parseFloat(other_price.replace(/,/g,''));
          purchase_total = +purchase_total + +other_val;
          $("#purchase_total").val(currency_format_display(purchase_total));


    }

    function compute_area(val, id, row_num){

      var height = $("#curtain_height_"+row_num).val();
      var width  = $("#curtain_width_"+row_num).val();

      if(isNaN(height) ){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل الارتفاع '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#curtain_height_"+row_num).val('');
      }

      if( isNaN(width)){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل  العرض'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#curtain_width_"+row_num).val('');
      }

      var area = height * width;
      if( isNaN(area)){
        area = '';
      }
      $("#total_length_"+row_num).val(area);

      calc_total_item_cost(id,row_num);

    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return 'not';
    }


$(document).ready(function() {
  
    get_products(1);
    get_Profile_price();
    get_Customer();
    // escape_notes();
    get_Others();
    

    // to prevent default show modal on page load

    $('#product_id_fk_1').change(function(e) {
      e.preventDefault();
         load_products(this.value,this.id);
    });

    $('#purchase_quantity_1').change(function(e) {
      e.preventDefault();
         add_qty_input_fields(this.value,this.id);
    });

    // add new row to purchase menu
    $("#purchase_item_body").on('click','.btn_add_item',function(e){
      e.preventDefault();
      var curnt_row_num = $("#total_rows").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`
                          <tr  id="item_row_`+CNT+`" >
                            <td width="3%" id="num_`+CNT+`">`+CNT+`</td>
                            <td width="8%">
                              <select class="form-control multi_lang" name="product_id_fk_`+CNT+`" id="product_id_fk_`+CNT+`" data-width="100%" placeholder="رمز المادة" onchange="load_products(this.value,this.id);" data-live-search="true">

                              </select>
                              <input id="item_type_id_`+CNT+`" name="item_type_id_`+CNT+`" type="hidden" placeholder="`+Translation('رمز المادة')+`">
                              
                            </td>
                            <td width="8%" id="forign_id_`+CNT+`"></td>

                            <td width="6%">
                              <input type="number" value="1" id="purchase_quantity_`+CNT+`" name="purchase_quantity_`+CNT+`"  class="form-control text-center" placeholder="`+Translation('الكمية')+`"  onchange="add_qty_input_fields(this.value,this.id);">
                            </td>

                            
                            <td width="6%" id="products_height_`+CNT+`">
                              <input type="text" id="curtain_height_`+CNT+`" name="curtain_height_`+CNT+`"  class="form-control text-center" placeholder="`+Translation('الارتفاع')+`"  onchange="compute_area(this.value,this.id,`+CNT+`);">

                            </td>
                            <td width="6%" id="products_width_`+CNT+`">
                              <input type="text" id="curtain_width_`+CNT+`" name="curtain_width_`+CNT+`"  class="form-control text-center" placeholder="`+Translation('العرض')+`"  onchange="compute_area(this.value,this.id,`+CNT+`);">

                            </td>

                            <td width="7%" >
                              <input id="total_length_`+CNT+`" name="total_length_`+CNT+`" type="text" class="form-control text-center" readonly >
                            </td>

                            <td width="6%">
                              <input id="last_sell_price_`+CNT+`" name="last_sell_price_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td>

                            <td width="7%">
                              <input id="buy_price_per_meter_`+CNT+`" name="buy_price_per_meter_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع المتر')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                            <td width="6%">
                              <input id="last_sell_price_decor_`+CNT+`" name="last_sell_price_decor_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع ديكور')+`" readonly >
                            </td>

                            <td width="7%">
                              <input id="buy_price_per_meter_decor_`+CNT+`" name="buy_price_per_meter_decor_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع متر الديكور')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                            <td width="7%">
                              <input id="sell_discount_`+CNT+`" name="sell_discount_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control text-center" placeholder="`+Translation('تنزيلات')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>
                            <td width="9%" > 
                            
                              <input id="total_item_cost_`+CNT+`" name="total_item_cost_`+CNT+`" type="text" value="0 $" class="form-control text-center" readonly >
                            </td>
                            <td width="9%">
                              <textarea type="text" id="purchase_item_note_`+CNT+`" name="purchase_item_note_`+CNT+`" class="form-control " placeholder="`+Translation('ملاحظات')+`" > </textarea>
                            </td>
                            <td width="9%" >
                              <input id="sell_item_delivery_name_`+CNT+`" name="sell_item_delivery_name_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('المستلم')+`">
                            </td>
                            <td width="7%" >
                              <input id="product_pay_`+CNT+`" name="product_pay_`+CNT+`" type="text"  class="form-control text-center" placeholder="`+Translation('المبلغ المدفوع')+`" onchange="calc_payments(`+CNT+`);" >
                            
                            </td>
                            <td width="6%">
                              <button class="btn btn-link btn-xs btn_add_item" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button class="btn btn-link btn-xs btn_remove_item" id="row_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#purchase_item_body").append(attach_new_row);
            $("#total_rows").val(CNT);
            get_products(CNT);


    });

    // remove current row 
    $("#purchase_item_body").on('click','.btn_remove_item',function(e){
          e.preventDefault();
          console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[1];
          $("#item_row_"+row_num).remove();
          calc_total_purchase_price();
          calc_payments();
    });

    $("#default_val_btn").on('click',function(){
        var qty   =$("#fields_count").val();
        var deflt = $("#default_val").val();
        for (var i = 1; i <= qty; i++) {
          $("#roll_length_"+i).val(deflt);
        }
     })


    $('#add_new_product_form').on('submit', function(e){

          e.preventDefault();

          var qty = $("#fields_count").val();
          var row_no = $("#rows_count").val();
          var attach_input ="";
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            
            total_roll_length = +total_roll_length + +$("#roll_length_"+i).val();

            attach_input = attach_input + `<input data-roll-id-fk="0" types="text" id="row_`+row_no+`_roll_`+i+`" class="badge badge-primary col-sm-6" value="`+$("#roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          $("#products_height_"+row_no).html(attach_input);
          $("#products_width_"+row_no).remove();
          $("#products_height_"+row_no).attr('colspan','2');
          $("#buy_price_per_meter_decor_"+row_no).attr('readonly','readonly');


          $("#total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
          $('#add_new_product').modal('toggle');

    });


    $('#add_payments_form').on('submit', function(e){

          e.preventDefault();

          var inv_id = $("#inv_numb_pay").val();
          // inv_product_other
          var sell_id_array                    =[];
          var pay_price_array                  =[];
          var pay_notes_array                  =[];
          var check_price_array                =[];
          var check_sell_id_array              =[];

          var k =0 ;
          $('input[id^="inv_paid_price_"]').each(function() 
          { 
            if(!isNaN(this.value) && this.value.length!=0) 
            {
              pay_price_array[k]      = parseFloat(this.value);

              var row_num1            = this.id.split('_');
              var row_num             = row_num1[3]; 
              var sell_id_fk          = $("#inv_product_"+row_num).attr('data-sell-id-fk');   
              var notes               = $("#pay_note_"+row_num).val();   

              sell_id_array[k]        = sell_id_fk;
              pay_notes_array[k]      = notes;

              check_price_array[k]    = Checks('inv_paid_price_'+row_num,'No',0.0001,null);
              
              if(sell_id_fk > 0){
                check_sell_id_array[k]  = true;
              }else{
                check_sell_id_array[k]  = false;
              }

              k =k+1;   

            }         
          });
          

          var check_paid  = false;
          var check_ids   = true;

          for(m=0;m<check_price_array.length;m++){

            if(check_sell_id_array[m]==false){
              check_ids = false;
            }
            if(check_price_array[m]==true){
              check_paid = true;   // because it accept at least one payment
            }

          }

          if(check_paid && check_ids){
            $("#submit_add_pay_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice_curt.php",
                type:"POST",
                dataType: "JSON",
                data : {inv_id              :inv_id,
                        row_payments        :pay_price_array,
                        sell_ids            :sell_id_array,
                        notes               :pay_notes_array,
                        type                :'add_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $('#add_payments_modal').modal('toggle');
                    
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#submit_add_pay_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_pay_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
          }else{
              noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

          

    });


    $('#add_new_product_form_from_purchase').on('submit', function(e){

          e.preventDefault();

          var qty               = $("#fields_count_purchase").val();
          var row_no            = $("#rows_count_purchase").val();
          var qty_all_rolls     = $("#rolls_count_purchase").val();
          var attach_input      = "";
          var total_roll_length = 0;
          var k =1;
          for (var i = 0; i <  qty_all_rolls; i++) {
            
            
            if($("#part_roll_length_"+i).val() !='' && $("#part_roll_length_"+i).val() != undefined){
              total_roll_length = +total_roll_length + +$("#part_roll_length_"+i).val();
              
              // we should store id-fk for selected rolls
              var original_roll_length  = $("#checked_roll_"+i).attr('data-roll-length');
              var roll_id_fk            = $("#checked_roll_"+i).attr('data-roll-id-fk');
              var roll_status           = $("#checked_roll_"+i).attr('data-item-status');
              var remained_length       = $("#checked_roll_"+i).attr('data-remained-length');
              attach_input = attach_input + `<input data-item-status="`+roll_status+`" data-remained-length="`+remained_length+`"  data-roll-id-fk="`+roll_id_fk+`" data-roll-length="`+original_roll_length+`" types="text" id="row_`+row_no+`_roll_`+k+`" class="badge bg-orange-400 col-sm-6" value="`+$("#part_roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);" readonly>`;
              k = k +1;
            }
          }
          
          $("#products_height_"+row_no).html(attach_input);
          $("#products_width_"+row_no).remove();
          $("#products_height_"+row_no).attr('colspan','2');
          $("#buy_price_per_meter_decor_"+row_no).attr('readonly','readonly');

          $("#total_length_"+row_no).val(total_roll_length);
          // update the quantity field to fit with selected product
          $("#purchase_quantity_"+row_no).val(k-1);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();

          
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
          $('#add_new_product_from_purchase').modal('toggle');

    });




    $('#add_form').submit(function(event) {
          event.preventDefault();
              // block

          block = $(this).parent();
              // \block

          var cnt                                 = $("#total_rows").val();
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var roll_length_array                   =[];
          var roll_total_array                    =[];
          var unit_price_array                    =[];
          var discount_val_array                  =[];
          var discount_type_array                 =[];
          var discount_actual_array               =[];
          var roll_id_fk_array                    =[];
          var roll_id_fk_total_array              =[];
          var roll_origianl_length_array          =[];
          var roll_original_length_total_array    =[];
          var row_total_price_array               =[];
          var notes_array                         =[];
          var deliver_array                       =[];
          var payments_array                      =[];
          var item_type_array                     =[];
          var height_array                        =[];
          var width_array                         =[];
          var decor_price_array                   =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          var check_rolls                         =[];
          var check_rolls_all                     =[];
          var check_height                        =[];
          var check_width                         =[];
          var check_decor_price                   =[];
          var k=1;

          for(var i =1; i <= cnt; i++){

              var productID       = $("#product_id_fk_"+i).val();
              var itemTypeID      = $("#item_type_id_"+i).val();
              var quantityField   = $("#purchase_quantity_"+i).val();
              var unit_price      = $("#buy_price_per_meter_"+i).val();
              var notes           = $("#purchase_item_note_"+i).val();
              var row_total_price = $("#total_item_cost_"+i).val();
              var product_pay     = $("#product_pay_"+i).val();
              var discount        = $("#sell_discount_"+i).val();
              var discount_type   = $("#sell_discount_"+i).attr('data-discount-type');
              var discount_actual = $("#sell_discount_"+i).attr('data-discount-actual');
              var height_curt     = $("#curtain_height_"+i).val();
              var width_curt      = $("#curtain_width_"+i).val();
              var decor_price     = $("#buy_price_per_meter_decor_"+i).val();
              var deliver_name    = $("#sell_item_delivery_name_"+i).val();

              row_total_price     = row_total_price.replace('$','');
              row_total_price     = row_total_price.replace(/,/g,'');
              row_total_price     = parseFloat(row_total_price);

              if(productID != undefined && productID != null ){
                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No',1);
                check_price[k]            = Checks('buy_price_per_meter_'+i,'No',0.000001);
                
                
                // check if height and width elments are exists
                if($('#curtain_height_'+i).length >0 && $('#curtain_width_'+i).length >0){
                
                  check_height[k]           = Checks('curtain_height_'+i,'No',1);
                  check_width[k]            = Checks('curtain_width_'+i,'No',1);
                  // check_decor_price[k]      = Checks('buy_price_per_meter_decor_'+i,'No',0.000001);

                }
                //console.log(check_quantity)
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                deliver_array[k]          = deliver_name;
                unit_price_array[k]       = unit_price;
                discount_val_array[k]     = discount;
                discount_type_array[k]    = discount_type;
                discount_actual_array[k]  = discount_actual;
                row_total_price_array[k]  = row_total_price;
                payments_array[k]         = product_pay;
                item_type_array[k]        = itemTypeID;

                height_array[k]           = height_curt;
                width_array[k]            = width_curt;
                decor_price_array[k]      = decor_price;


                // now i should check for rolls number and it should equal to quantity
                roll_length_array          =[];
                check_rolls                =[];
                roll_id_fk_array           =[];
                roll_origianl_length_array =[];

                if($('#curtain_height_'+i).length ==0 && $('#curtain_width_'+i).length ==0){
                
                  // alert(height_curt)
                  for(var j=1; j<=quantityField; j++){
                    check_rolls[j]           = Checks('row_'+k+'_roll_'+j,'No',1,null,'badge');
                    var rolls                = $('#row_'+k+'_roll_'+j).val();
                    var roll_id_fk           = $('#row_'+k+'_roll_'+j).attr('data-roll-id-fk');
                    var roll_original_length = $('#row_'+k+'_roll_'+j).attr('data-roll-length');
                    
                    
                    roll_id_fk_array[j]            = roll_id_fk;

                    roll_origianl_length_array[j]  = roll_original_length;
            
                    
                    console.log(rolls);
                    console.log('#row_'+k+'_roll_'+j);

                    roll_length_array[j]    = rolls;
                  }

                }else{
                  for(var j=1; j<=quantityField; j++){
                    roll_length_array[j]      = height_curt + ";" + width_curt ;
                    
                    roll_id_fk_array[j]       = 'c';  // 0 havn't purchase; >0 have purchase item; c its curtain
                    
                  }

                }
                

                roll_id_fk_total_array[k]           = roll_id_fk_array;
                roll_original_length_total_array[k] = roll_origianl_length_array;
                roll_total_array[k]                 = roll_length_array;
                check_rolls_all[k]                  = check_rolls;
                // end checking rolls number
                console.log(roll_length_array);
                console.log(roll_total_array);
                console.log(roll_id_fk_array);
                console.log(roll_id_fk_total_array);
                k++;
              }
          }
          
          var invoice_type                = $("#invoice_type").val();  //0 raw ; 1 curtain
          var invoice_type_singular       = $("#invoice_type_singular").val();  //0 plural ; 1 single
          var customer_id_fk              = $("#customer_id_fk").val();
          var pay_term                    = $("#pay_term").val();
          var invoice_date                = $("#invoice_date").val();
          var price_profile_id            = $("#price_profile_id").val();
          // var sell_discount_type          = $("#sell_discount_type").val();
          var invoice_note                = $("#invoice_note").val();
          var total_invoice               = $("#purchase_total").val();
          var total_paid                  = $("#total_paid").val();
          total_invoice                   = total_invoice.replace('$','');
          total_invoice                   = total_invoice.replace(/,/g,'');
          total_invoice                   = parseFloat( total_invoice);
          
          total_paid                      = total_paid.replace('$','');
          total_paid                      = total_paid.replace(/,/g,'');
          total_paid                      = parseFloat( total_paid);

          // other products
          var other_id_fk                 = $("#other_id_fk").val();
          var other_quantity_1            = $("#other_quantity_1").val();
          var buy_price_per_meter_other   = $("#buy_price_per_meter_other").val();
          var sell_discount_other         = $("#sell_discount_other").val();
          var sell_discount_other_type    = $("#sell_discount_other").attr('data-discount-type');
          var sell_discount_other_actual  = $("#sell_discount_other").attr('data-discount-actual');
          var purchase_item_note_other    = $("#purchase_item_note_other").val();
          var row_other_total_price       = $("#total_item_cost_other").val();
          var other_pay                   = $("#other_pay").val();

          row_other_total_price = row_other_total_price.replace('$','');
          row_other_total_price = row_other_total_price.replace(/,/g,'');
          row_other_total_price = parseFloat( row_other_total_price);
            
          // check if other in not null we should make quantiy and price required
          // alert(other_id_fk)
            var Check3    = true;
            var Check4    = true;
          if(other_id_fk != '' && other_id_fk != undefined){
             Check3    = Checks('other_quantity_1','No',1);
             Check4    = Checks('buy_price_per_meter_other','No',0.00000001);
          }

          

          var Check1      = Checks('customer_id_fk');
          var Check2      = Checks('price_profile_id');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkrolls  = true;
          var checkprice  = true;
          var checkheight = true;
          var checkwidth  = true;
          var checkdecor  = true;

          for(m=1;m<=check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

            if(check_height[m]==false){
              checkheight = false;
            }

            if(check_width[m]==false){
              checkwidth = false;
            }

            // if(check_decor_price[m]==false){
            //   checkdecor = false;
            // }

            if(check_price[m]==false){
              checkprice = false;
            }

            for(var n=1;n<=roll_total_array[m];n++){
              if(check_rolls_all[m][n]==false){
                checkrolls = false;
              }
            }

          }




        if(Check1 && Check2 && Check3 && Check4 && CheckPro && checkQty && checkrolls && checkprice && checkheight && checkwidth && checkdecor ){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice_curt.php",
                type:"POST",
                dataType: "JSON",
                data : {invoice_type              :invoice_type,
                        is_single                 :invoice_type_singular,
                        customer_id_fk            :customer_id_fk,
                        pay_term                  :pay_term,
                        invoice_date              :invoice_date,
                        price_profile_id          :price_profile_id,
                        invoice_note              :invoice_note,
                        other_id_fk               :other_id_fk,
                        other_quantity_1          :other_quantity_1,
                        other_sell_price          :buy_price_per_meter_other,
                        other_discount            :sell_discount_other,
                        other_discount_type       :sell_discount_other_type,
                        other_discount_actual     :sell_discount_other_actual,
                        other_note                :purchase_item_note_other,
                        other_row_price           :row_other_total_price,
                        other_pay                 :other_pay,
                        total_invoice             :total_invoice,
                        total_paid                :total_paid,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        item_length               :roll_total_array,
                        sell_price                :unit_price_array,
                        discount                  :discount_val_array,
                        discount_type             :discount_type_array,
                        discount_actual           :discount_actual_array,
                        roll_id_fk                :roll_id_fk_total_array,
                        sell_item_note            :notes_array,
                        sell_item_deivery         :deliver_array,
                        row_price                 :row_total_price_array,
                        row_payments              :payments_array,
                        item_type                 :item_type_array,
                        original_length           :roll_original_length_total_array,
                        decor_price               :decor_price_array,
                        type                      :'create'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    // remove table rows
                    $('tr[id^="item_row_"]').each(function(){ 
                        if( this.id !='item_row_1' && this.id !='item_row_other') 
                        {
                          $(this).remove();          
                        }         
                    });

                    // empty td rows
                    $('td[id^="products_"]').each(function(){ 
                        
                          $(this).html('');                  
                    });

                    $('td[id^="forign_id_"]').each(function(){ 
                        
                          $(this).html('');                  
                    });

                    $("#price_profile_id").val('0').selectpicker('refresh');
                    $("#customer_id_fk").val('0').selectpicker('refresh');
                    $("#other_id_fk").val('0').selectpicker('refresh');
                    $("#total_rows").val('1');


                    // $("#product_name").val('');
                    // $("#erbil_code").val('');
                    // $("#turkish_code").val('');
                    // $("#barcode").val('');
                    // $("#product_note").val('');
                    // $(".fileinput-remove-button").trigger('click');

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $("#add-form-cont").collapse('hide');
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {location.reload();},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#submit_add_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }else{
          noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة وايضا التحقق من ان الاطوال المحددة مساوية للعدد'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }

    });




    $('#edit_form').submit(function(event) {
            event.preventDefault();
            // block
            block = $(this).parent();
            // \block

            var catId                  = $("#edit_objid").val();

            var product_id             = $("#edit_product_id").val();
            var quantity               = $("#edit_quantity").val();
            var buy_price              = $("#edit_buy_price").val();
            var created_at             = $("#edit_created_at").val();
            var sell_price             = $("#edit_sell_price").val();
            var sell_price_percentage  = $("#edit_sell_price_percentage").val();
            var average_price          = $("#edit_average_price").val();
            var note                   = $("#edit_note").val();

            var Check1 = true;
            var Check2 = true;
            var Check3 = true;
            var Check4 = true;
            var Check5 = true;
            var Check6 = true;


            Check1 = Checks('edit_product_id');
            Check2 = Checks('edit_quantity');
            Check3 = Checks('edit_buy_price');
            Check4 = Checks('edit_sell_price');
            Check5 = Checks('edit_sell_price_percentage');

            if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                //alert("ssss")
                $.ajax({
                    url: "models/crul_purchase1.php",
                    type:"POST",
                       data : {obj_id:catId,product_id:product_id,quantity:quantity,buy_price:buy_price,created_at:created_at,
                        sell_price:sell_price,sell_price_percentage:sell_price_percentage,average_price:average_price,note:note,type:'update'},
                    complete:function(){
                      //hideLoader();
                    },
                    beforeSend:function(){
                      //showLoader("Updating Purchase");
              },
                    success: function(res) {
                      if(res == 0){
                        $("#edit-form-cont").collapse('hide');
                        $("#edit_form")[0].reset();
                        swal({
                            title:"Not Success",
                            text: "Detail:"+res,
                            confirmButtonColor: "#66BB6A",
                            type: "warning"
                        });
                      }else if(res == 1){
                        $("#edit_form")[0].reset();
                        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        //$("#edit-form-cont").collapse('hide');
                        get_Products();
                        $('#edit_form_cont').modal('toggle');
                        noty({
                                        width: 200,
                                        text: 'Purchase Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                  });
                      }else{
                              swal({
                                  title: "Error",
                                  text: "Detail:"+res,
                                  confirmButtonColor: "#66BB6A",
                                  type: "error"
                              });
                          }
                    }
                });
              }
    });



   
    $("#add_others_btn").on('click',function(e){
        e.preventDefault();
        $("#add_other_modal").modal('toggle');
    });

    $('#add_other_form').submit(function(event) {
        event.preventDefault();
        
        var other_name                = $("#other_name").val();
        var other_description         = $("#other_description").val();
        var other_buy_price_per_unit  = $("#other_buy_price_per_unit").val();

        var check1 = true;
        var check2 = true;
        var check3 = true;

        var Check1    = Checks('other_name');
        var Check2    = Checks('other_buy_price_per_unit');

        if(Check1 && Check2){
            $("#submit_add_other_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {other_name:other_name,other_description:other_description,other_buy_price_per_unit:other_buy_price_per_unit
                        ,type:'add_other'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    $("#add_other_modal").modal('toggle');
                    get_Others();
                    noty({
                              width: 200,
                              text: Translation(res.data),
                              type: 'success',
                              dismissQueue: true,
                              timeout: 3000,
                              layout: 'topRight',
                        });
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#submit_add_other_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_other_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });

        }else{
          noty({
                  width: 200,
                  text: Translation("الرجاء ادخال الحقول المطلوبة"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'topRight',
            });
        }



    });


});







$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    
  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 10000000,
        step: 1,
        buttondown_class: "btn btn-xs",
        buttonup_class: "btn btn-xs"
    });

  $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });

  // Mini
    $('.select-size-xs').select2({
        containerCssClass: 'select-xs'
    });


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 5 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    

   var query_ip   = getQueryVariable("ip");
   var query_typ  = getQueryVariable("typ");


    function invoce_filter_btn_label(){

       if(query_ip =='not' ){
         $("#inv_filter").html(Translation('فلترة الوصولات'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-teal-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==2){
         $("#inv_filter").html(Translation('واصل'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-success-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==3){
         $("#inv_filter").html(Translation('مسترجع'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-purple-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==4){
         $("#inv_filter").html(Translation('عرض'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-violet-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==1 ){
         $("#inv_filter").html(Translation('واصل جزئيا'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-orange-400 btn-labeled dropdown-toggle');

       }
       

       if(query_ip ==0 ){
         $("#inv_filter").html(Translation('غير واصل'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-danger-400 btn-labeled dropdown-toggle');

       }

     }


   var table = $('.datatable-column-search-inputs').DataTable({
        
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_invoice_curt.php",
        "data": function(d){
          d.type = "load";
          if(query_ip !='not'){
            d.ip =query_ip ;
          }
          if(query_typ !='not'){
            d.typ =query_typ ;
          }
          
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          {
              "targets": 10,
              "data": null,
              "render": function (data,type,row) {

                            return  `<ul class='icons-list pull-right'>
                                      

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-success-400' onclick="show_invoice(`+row[0]+`,null,'Details')" data-popup='tooltip' data-original-title='`+Translation('عرض وصل البيع مع التفاصيل')+`'>
                                                <i class='icon-stack-text'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-info-400' onclick="show_invoice(`+row[0]+`,'Print','Details')" data-popup='tooltip' data-original-title='`+Translation('طباعة الوصل مع التفاصيل')+`'>
                                                <i class='icon-printer2'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-orange-400' onclick="show_invoice(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('عرض وصل البيع بدون التفاصيل')+`'>
                                                <i class='icon-calculator'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-pink-400' onclick="show_invoice(`+row[0]+`,'Print')" data-popup='tooltip' data-original-title='`+Translation('طباعة الوصل بدون التفاصيل')+`'>
                                                <i class='icon-printer4'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-purple-400' onclick="show_sticker(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('عرض ملصقات الوصل')+`'>
                                                <i class='icon-qrcode'></i>
                                            </a>
                                        </li>

                                        <!--
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a href='#' class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash'></i>
                                            </a>
                                        </li>
                                        -->
                                        <li class="dropdown">
                                          <a href="#" class="dropdown-toggle" data-toggle="dropdown"  data-original-title='`+Translation('تفاصيل دفوعات الوصل')+`'>
                                            <i class="icon-menu9"></i>
                                          </a>

                                          <ul class="dropdown-menu dropdown-menu-right">
                                            <li>
                                              <a href='#' onclick="show_payments(`+row[0]+`)"  data-original-title='Show Invoice Payments'>
                                                <i class='icon-coins text-info-400'></i> `+Translation('عرض الدفوعات')+`
                                              </a>
                                            </li>
                                            <li>
                                              <a href='#' onclick="add_payments(`+row[0]+`)"  data-original-title='Add New Payments to this Invoice'>
                                                <i class='icon-cash text-primary-600'></i> `+Translation('اضافة دفعه')+`
                                              </a>
                                            </li>
                                            <li>
                                              <a href='#' onclick="edit_payments(`+row[0]+`)"  data-original-title='Edit or Remove Invoice Payments'>
                                                <i class='icon-pencil5 text-teal-600'></i>`+Translation('تحرير الدفوعات')+`
                                              </a>
                                            </li>

                                          </ul>
                                        </li>

                                    </ul>`;
                        }
          },


            {
               "render": function(data, type, row){


                        // return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='Show Invoice Details'>`+data+`</a>`;
                        return  `<a onclick="load_account_statment('',`+row[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض جميع كشوفات الحساب لهذا الوصل')+`'>`+data+`</a>`;
                        

               },
               "targets": 1
            },

            {
               "render": function(data, type, row){


                        return  `<a onclick="load_account_statment(`+row[11]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض جميع كشوفات الحساب لهذا الزبون')+`'>`+data+`</a>`;


               },
               "targets": 3
            },
            {
                "render": function(data, type, row){

                    return currency_format_display(data);
                },
                "targets": 4
            },

            {
                "render": function(data, type, row){

                    return currency_format_display(data);
                },
                "targets": 5
            },

            {
                "render": function(data, type, row){

                    return currency_format_display(data);
                },
                "targets": 6
            },

            {
                "render": function(data, type, row){

                    return currency_format_display(data);
                },
                "targets": 7
            },
            

            {
                "render": function(data, type, row){
                   if(row[8] ==2 ){
                     status=  `<span class="label label-success btn-block ">`+Translation('واصل')+`</span>`;
                   }else if(row[8] ==3){
                     status = '<span class="label bg-purple  btn-block "> '+Translation('مرجع')+' </span>';
                   }else if(row[8] ==4){
                     status = '<span class="label bg-violet  btn-block "> '+Translation('عرض')+' </span>';
                   }else{

                        // datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'

                        //Set the two dates
                        var y2k  = new Date(row[2]);
                        var today= new Date();
                        var days = Date.dateDiff('d', y2k, today); //displays 625
                        //alert(days)
                         if(days >= row[10]){
                             var afterTermDays = days - row[10];
                             if(row[8]==1){
                               status = '<span class="label bg-orange  btn-block btn-xs"> '+Translation('واصل جزئيا')+' ('+afterTermDays+' DAYS OUT)</span>';
                             }else{
                               status = '<span class="label label-danger btn-block btn-xs"> '+Translation('غير واصل')+' ('+afterTermDays+' DAYS OUT)</span>';
                             }

                         }else{
                             var remainedDays = row[10]-days;
                             if(row[8]==1){
                               status = '<span class="label label-info  btn-block btn-xs"> '+Translation('واصل جزئيا')+' ('+remainedDays+' DAYS REM)</span>';
                             }else{
                               status = '<span class="label label-primary btn-block btn-xs"> '+Translation('غير واصل')+' ('+remainedDays+' DAYS REM)</span>';
                             }

                         }
                   }
                   return  status;
                },
                "targets": 8
            }
            

           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[5] == 1 ){ // outcome type
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('alpha-info');
                });
            }
        },
        "order": [[0,'desc']],
        "displayLength": 25,
      
        initComplete: function () {
         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-primary"
                                      id="add_Item_Btn">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+Translation(CURRENT_BTN)+`
                                    </a>`); 

          $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                          <button id="inv_filter_btn" type="button"
                          class="btn bg-teal-400 btn-labeled dropdown-toggle"
                          data-toggle="dropdown"><b><i class="icon-filter4">
                          </i></b> <span id="inv_filter">`+Translation('فلترة الوصولات')+`</span> <span class="caret"></span></button>
                          <ul class="dropdown-menu dropdown-menu-right">
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`"><i class="icon-close2 text-teal"></i> `+Translation('ازالة الفلتر')+` </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`&ip=2"><i class="icon-coins text-success"></i> `+Translation('الواصل')+`</a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`&ip=1"><i class="icon-bell-check text-info"></i> `+Translation('واصل جزئيا')+`</a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`&ip=0"><i class="icon-alarm-check text-danger"></i> `+Translation('غير واصل')+`</a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`&ip=4"><i class=" icon-task text-violet"></i> `+Translation('عروض')+` </a></li>
                          <li><a href="index.php?p=invoice_curt&typ=`+query_typ+`&ip=3"><i class="icon-loop text-purple"></i> `+Translation('مسترجع')+` </a></li>

                        </ul>
                      </div>`);
 
            invoce_filter_btn_label();

            this.api().columns().every( function() {
                var column = this;
                

            });
            escape_notes();
        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



