var table 
    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;
                          } 
                          
                          .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;
                          }
                          
                          .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 table_invoice     =`
                            <html>

                              <head>
                                  <meta http-equiv=Content-Type content="text/html; charset=unicode">
                                  <meta name=Generator content="Microsoft Word 15 (filtered)">
                                  <style>
                                      <!--
                                      /* Font Definitions */
                                      
                                      @font-face {
                                          font-family: "Cambria Math";
                                          panose-1: 2 4 5 3 5 4 6 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: Calibri;
                                          panose-1: 2 15 5 2 2 2 4 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Calibri Light";
                                          panose-1: 2 15 3 2 2 2 4 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Century Gothic";
                                          panose-1: 2 11 5 2 2 2 2 2 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Sakkal Majalla";
                                          panose-1: 2 0 0 0 0 0 0 0 0 0;
                                      }
                                      /* Style Definitions */
                                      
                                      p.MsoNormal,
                                      li.MsoNormal,
                                      div.MsoNormal {
                                          margin-top: 0in;
                                          margin-right: 0in;
                                          margin-bottom: 8.0pt;
                                          margin-left: 0in;
                                          line-height: 105%;
                                          font-size: 11.0pt;
                                          font-family: "Calibri", sans-serif;
                                      }
                                      
                                      h2 {
                                          mso-style-link: "Heading 2 Char";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          page-break-after: avoid;
                                          font-size: 8.0pt;
                                          font-family: "Calibri Light", sans-serif;
                                          color: #262626;
                                          font-weight: normal;
                                      }
                                      
                                      p.MsoHeader,
                                      li.MsoHeader,
                                      div.MsoHeader {
                                          mso-style-link: "Header Char";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          font-size: 8.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      a:link,
                                      span.MsoHyperlink {
                                          color: blue;
                                          text-decoration: underline;
                                      }
                                      
                                      a:visited,
                                      span.MsoHyperlinkFollowed {
                                          color: purple;
                                          text-decoration: underline;
                                      }
                                      
                                      span.Heading2Char {
                                          mso-style-name: "Heading 2 Char";
                                          mso-style-link: "Heading 2";
                                          font-family: "Calibri Light", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      p.msonormal0,
                                      li.msonormal0,
                                      div.msonormal0 {
                                          mso-style-name: msonormal;
                                          margin-right: 0in;
                                          margin-left: 0in;
                                          font-size: 12.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      span.HeaderChar {
                                          mso-style-name: "Header Char";
                                          mso-style-link: Header;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      p.msopapdefault,
                                      li.msopapdefault,
                                      div.msopapdefault {
                                          mso-style-name: msopapdefault;
                                          margin-right: 0in;
                                          margin-bottom: 8.0pt;
                                          margin-left: 0in;
                                          line-height: 105%;
                                          font-size: 12.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      p.msochpdefault,
                                      li.msochpdefault,
                                      div.msochpdefault {
                                          mso-style-name: msochpdefault;
                                          margin-right: 0in;
                                          margin-left: 0in;
                                          font-size: 10.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      p.Slogan,
                                      li.Slogan,
                                      div.Slogan {
                                          mso-style-name: Slogan;
                                          margin-top: 0in;
                                          margin-right: 0in;
                                          margin-bottom: 3.0pt;
                                          margin-left: 0in;
                                          font-size: 7.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #A6A6A6;
                                          letter-spacing: .2pt;
                                          font-style: italic;
                                      }
                                      
                                      p.ContactInfo,
                                      li.ContactInfo,
                                      div.ContactInfo {
                                          mso-style-name: "Contact Info";
                                          margin-top: 26.0pt;
                                          margin-right: 0in;
                                          margin-bottom: 0in;
                                          margin-left: 0in;
                                          margin-bottom: .0001pt;
                                          text-align: center;
                                          font-size: 8.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #A6A6A6;
                                      }
                                      
                                      p.ThankYou,
                                      li.ThankYou,
                                      div.ThankYou {
                                          mso-style-name: "Thank You";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          text-align: center;
                                          font-size: 9.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                          font-weight: bold;
                                          font-style: italic;
                                      }
                                      
                                      span.companyphones {
                                          mso-style-name: company_phones;
                                      }
                                      
                                      span.companyemail {
                                          mso-style-name: company_email;
                                      }
                                      
                                      span.invoiceno {
                                          mso-style-name: invoice_no;
                                      }
                                      
                                      span.invoicedate {
                                          mso-style-name: invoice_date;
                                      }
                                      
                                      span.deliverystatus {
                                          mso-style-name: delivery_status;
                                      }
                                      
                                      span.destination {
                                          mso-style-name: destination;
                                      }
                                      
                                      .MsoChpDefault {
                                          font-size: 10.0pt;
                                      }
                                      
                                      @page WordSection1 {
                                          size: 841.9pt 595.3pt;
                                          margin: .5in .5in .5in .5in;
                                      }
                                      
                                      div.WordSection1 {
                                          page: WordSection1;
                                      }
                                      
                                      -->
                                  </style>

                              </head>

                              <body lang=EN-US link=blue vlink=purple>

                                  <div class=WordSection1>

                                      <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 delete_items(itemid) {
        
          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: امسح!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_offer.php",
                  type:"POST",
                  dataType:"JSON",
                  data: {"type":"delete","obj_id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                    
                  },
                  success: function(res) {
                    if(res.is_success == true){
                      // get_Products();
                      swal({
                                  title: "Deleted!",
                                  text: Translation(res.data),
                                  confirmButtonColor: "#66BB6A",
                                  type: "success"
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: "Cancelled",
                                  text: Translation(res.data),
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              }
          }); // /confirm
    }

   
    
    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_offer.php',
                type : 'POST',
                data : {type:'show_invoice', id : itm},
                dataType : 'json',
                success : function(response) {
                    // console.log(response)
                    
                        headers =`
                                  <table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0 width="92%" style='width:92.0%;border-collapse:collapse'>
                                      <tr style='height:.25in'>
                                          <td width="33%" nowrap colspan=3 style='width:33.44%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 5.4pt 0in 5.4pt;height:.25in'>
                                              <p class=Slogan style='line-height:105%'><span style='font-family:"Century Gothic",sans-serif'>
                                              <img   width=86 height=77 src="image/sys/image004.gif"></span></p>
                                              <p class=Slogan style='line-height:105%'>
                                                <b><span style='font-size:9.0pt;  line-height:105%;font-family:"Century Gothic",sans-serif;color:#FFC000'>
                                                `+Translation('Health Services')+` 
                                                </span>
                                              </b></p>
                                              <p class=Slogan style='line-height:105%'>
                                                <b><span style='font-size:9.0pt; line-height:105%;font-family:"Century Gothic",sans-serif;color:#FFC000'>
                                              `+Translation('Medical Equipment and Supplies')+` </span>
                                            </b></p>
                                          </td>
                                          <td width="59%" colspan=14 style='width:59.32%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:.25in'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                                <span style='font-size:36.0pt;  font-family:"Century Gothic",sans-serif;color:#A6A6A6'>        
                                                </span>
                                                <span style='font-size:36.0pt;font-family:"Century Gothic",sans-serif;color:#A8D08D'> </span>
                                                <span style='font-size:36.0pt;font-family:"Century Gothic",sans-serif;color:#FFC000'>
                                                `+Translation('QUOTE')+`
                                                </span></p>
                                          </td>
                                          <td width="7%" nowrap style='width:7.24%;border:none;border-bottom:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:.25in'>
                                              <p class=MsoNormal dir=RTL style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:right;direction:rtl;unicode-bidi:embed'>
                                                <span dir=LTR><img width=31 height=62 src="image/sys/image005.gif"></span></p>
                                          </td>
                                      </tr>
                                      <tr style='height:25.15pt' align="center">
                                          <td width="23%" nowrap colspan=2 style='width:23.78%;border:solid windowtext 1.0pt;   border-top:none;padding:0in 5.4pt 0in 5.4pt;height:25.15pt'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;   text-align:center'>
                                                <b><span style='font-size:12.0pt;line-height:105%'>
                                                `+Translation('Quote #')+`
                                                </span> 
                                              </b>
                                              <b><span lang=AR-SA dir=RTL style='font-size:12.0pt;line-height:105%'>
                                              `+Translation('رقم العرض')+`
                                              </span></b></p>
                                          </td>
                                          <td width="9%" style='width:9.66%;border-top:none;border-left:none;  border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 0in 0in 0in;height:25.15pt'>
                                              <h2 align=center style='text-align:center;line-height:105%'>
                                                <b><span  style='font-size:12.0pt;line-height:105%;font-family:"Calibri",sans-serif'>
                                                `+Translation('Date')+` 
                                                </span></b><span dir=RTL></span>
                                                <span lang=AR-SA dir=RTL style='font-size: 12.0pt;line-height:105%;font-family:"Calibri",sans-serif'>
                                                  <span dir=RTL></span>&nbsp;
                                                  `+Translation('التاريخ')+`
                                                  </span><span dir=LTR></span><span lang=AR-SA><span dir=LTR></span> </span>
                                              </h2>
                                          </td>
                                          <td width="11%" colspan=4 style='width:11.66%;border-top:none;border-left:   none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;   padding:0in 0in 0in 0in;height:25.15pt'>
                                              <h2 align=center style='text-align:center;line-height:105%'>
                                                <b><span  style='font-size:12.0pt;line-height:105%;font-family:"Calibri",sans-serif'>
                                                `+Translation('RFQ No. رقم طلب العرض')+`
                                                </span>
                                                </b><b> </b>
                                              </h2>
                                          </td>
                                          <td width="12%" colspan=4 style='width:12.06%;border-top:none;border-left:   none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;   padding:0in 0in 0in 0in;height:25.15pt'>
                                              <h2 align=center style='text-align:center;line-height:105%'>
                                                <b><span  style='font-size:12.0pt;line-height:105%;font-family:"Calibri",sans-serif'>
                                                `+Translation('Delivery Date')+`
                                                </span>
                                                </b>
                                              </h2>
                                          </td>
                                          <td width="20%" colspan=4 style='width:20.9%;border-top:none;border-left:   none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 0in 0in 0in;height:25.15pt'>
                                              <h2 align=center style='text-align:center;line-height:105%'><b>
                                                <span   style='font-size:12.0pt;line-height:105%;font-family:"Calibri",sans-serif'>
                                                `+Translation('Expiry Date')+`
                                                </span>
                                              </b></h2>
                                          </td>
                                          <td width="21%" nowrap colspan=3 style='width:21.94%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;   padding:0in 5.4pt 0in 5.4pt;height:25.15pt'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;   text-align:center;line-height:normal'>
                                                <b><span style='font-size:12.0pt'>
                                                `+Translation('Payment Terms')+`
                                                </span> </b>
                                              </p>
                                          </td>
                                      </tr>
                                      <tr style='height:26.95pt' align="center">
                                          <td width="23%" nowrap colspan=2 style='width:23.78%;border:solid windowtext 1.0pt;   border-top:none;padding:0in 5.4pt 0in 5.4pt;height:26.95pt'>
                                           `+response.invoice[0].offer_number+`
                                          </td>
                                          <td width="9%" style='width:9.66%;border:none;border-bottom:solid windowtext 1.0pt;   padding:0in 0in 0in 0in;height:26.95pt'>
                                               `+response.invoice[0].offer_date+`
                                          </td>
                                          <td width="11%" colspan=4 style='width:11.66%;border-top:none;border-left:   solid windowtext 1.0pt;border-bottom:solid windowtext 1.0pt;border-right:  none;padding:0in 0in 0in 0in;height:26.95pt'>
                                              `+response.invoice[0].request_for_quta_number+`
                                          </td>
                                          <td width="12%" colspan=4 style='width:12.06%;border-top:none;border-left:   solid windowtext 1.0pt;border-bottom:solid windowtext 1.0pt;border-right:   none;padding:0in 0in 0in 0in;height:26.95pt'>
                                              `+response.invoice[0].delivery_time+`
                                          </td>
                                          <td width="20%" colspan=4 style='width:20.9%;border:solid windowtext 1.0pt;   border-top:none;padding:0in 0in 0in 0in;height:26.95pt'>
                                              `+response.invoice[0].validity+`
                                          </td>
                                          <td width="21%" nowrap colspan=3 style='width:21.94%;border-top:none;   border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:26.95pt'>
                                              `+response.invoice[0].pay_terms+`
                                          </td>
                                      </tr>`;
                        
                        

                      customer_details = `



                                          <tr style='height:19.25pt' >
                                              <td width="23%" nowrap colspan=2 rowspan=4 style='width:23.78%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:19.25pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                    <b>`+Translation('Client Details')+`</b> </p>
                                              </td>
                                              <td width="9%" valign=top style='width:9.66%;padding:0in 5.4pt 0in 5.4pt; height:19.25pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                    
                                                    `+Translation('Name :')+` </p>
                                              </td>
                                              <td width="44%" colspan=12 valign=top style='width:44.62%;border:none;   border-right:solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:19.25pt'>
                                                  `+response.invoice[0].customer_full_name+`
                                              </td>
                                              <td width="21%" colspan=3 rowspan=4 style='width:21.94%;border-top:none;   border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 0in 0in 0in;height:19.25pt'>
                                                  <p class=MsoNormal dir=RTL style='margin-bottom:0in;margin-bottom:.0001pt;   text-align:right;line-height:normal;direction:rtl;unicode-bidi:embed'>
                                                    <b><span lang=AR-IQ style='color:black'>
                                                          `+Translation('تفاصيل الزبون')+`
                                                       </span>
                                                    </b></p>
                                              </td>
                                          </tr>
                                          <tr style='height:17.0pt'>
                                              <td width="9%" valign=top style='width:9.66%;padding:0in 5.4pt 0in 5.4pt;   height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+Translation('Address:')+`</p>
                                              </td>
                                              <td width="44%" colspan=12 valign=top style='width:44.62%;border:none; border-right:solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+response.invoice[0].customer_address+` </p>
                                              </td>
                                          </tr>
                                          <tr style='height:17.0pt'>
                                              <td width="9%" valign=top style='width:9.66%;padding:0in 5.4pt 0in 5.4pt; height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+Translation('Email:')+`</p>
                                              </td>
                                              <td width="44%" colspan=12 valign=top style='width:44.62%;border:none;   border-right:solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+response.invoice[0].customer_email+`</p>
                                              </td>
                                          </tr>
                                          <tr style='height:17.0pt'>
                                              <td width="9%" valign=top style='width:9.66%;padding:0in 5.4pt 0in 5.4pt;  height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+Translation('Phone No.:')+`</p>
                                              </td>
                                              <td width="44%" colspan=12 valign=top style='width:44.62%;border:none;  border-right:solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:17.0pt'>
                                                  <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt'>
                                                  `+response.invoice[0].customer_phone+`</p>
                                              </td>
                                          </tr>
                                            `;

                      attach =  `

                                    <tr style='height:26.0pt'>
                                        <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt; border-top:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Item No.')+`</span>
                                              </b>
                                            </p>
                                        </td>
                                        <td width="37%" nowrap colspan=5 style='width:37.14%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Item Description')+`</span> </b></p>
                                        </td>
                                        <td width="7%" nowrap colspan=3 style='width:7.52%;border:solid windowtext 1.0pt;  border-left:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Origin')+`</span></b>
                                            </p>
                                        </td>
                                        <td width="9%" nowrap colspan=4 style='width:9.24%;border:solid windowtext 1.0pt;  border-left:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Delivery')+`</span></b>
                                            </p>
                                        </td>
                                        <td width="6%" style='width:6.32%;border:solid windowtext 1.0pt;border-left: none;padding:0in 0in 0in 0in;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b>`+Translation('Qty')+`</b>
                                            </p>
                                        </td>
                                        <td width="10%" style='width:10.56%;border:solid windowtext 1.0pt;border-left:  none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Unit Price')+`</span></b>
                                            </p>
                                        </td>
                                        <td width="12%" nowrap style='width:12.38%;border-top:none;border-left:none;   border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Total Price')+`</span> </b>
                                            </p>
                                        </td>
                                        <td width="9%" nowrap colspan=2 style='width:9.56%;border:solid windowtext 1.0pt;  border-left:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('Notes')+`</span></b>
                                            </p>
                                        </td>
                                    </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){                        


                          attach = attach + ` 

                                              <tr style='height:15.0pt' align="center">
                                                  <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                        `+(i+1)+`
                                                      </p>
                                                  </td>
                                                  <td width="37%" align="left" nowrap colspan=5 style='width:37.14%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal style='font-weight:bold; margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                        <span style='font-size:10.0pt;font-family:"Times New Roman",serif'>
                                                        `+response.invoice[i].product_name+`
                                                        </span>
                                                      </p>
                                                      <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                        <span style='font-size:10.0pt;font-family:"Times New Roman",serif'>
                                                        `+response.invoice[i].description_en+`
                                                        </span>
                                                      </p>
                                                  </td>
                                                  <td width="7%" colspan=3 style='width:7.52%;border-top:none;border-left:solid windowtext 1.0pt; border-bottom:solid windowtext 1.0pt;border-right:solid black 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                                        <b>
                                                        <span style='color:black'>
                                                        `+response.invoice[i].made_in+`
                                                        </span></b>
                                                      </p>
                                                  </td>
                                                  <td width="9%" nowrap colspan=4 style='width:9.24%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid gray 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      
                                                        `+response.invoice[i].offer_sell_item_delivery_name+`
                                                      
                                                  </td>
                                                  <td width="6%" style='width:6.32%;border-top:none;border-left:none;  border-bottom:solid windowtext 1.0pt;border-right:solid gray 1.0pt;  padding:0in 0in 0in 0in;height:15.0pt'>
                                                      `+response.invoice[i].offer_sell_item_quantity+`
                                                  </td>
                                                  <td width="10%" style='width:10.56%;border-top:none;border-left:none;  border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      `+currency_format_display(response.invoice[i].offer_item_sell_price_per_unit)+`
                                                  </td>
                                                  <td width="12%" nowrap style='width:12.38%;border-top:none;border-left:none;  border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      `+currency_format_display(response.invoice[i].row_price)+`
                                                  </td>
                                                  <td width="9%" nowrap colspan=2 style='width:9.56%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      `+response.invoice[i].offer_sell_item_notes+`
                                                  </td>
                                              </tr>`;
                        
                        
                       
                      } // for i

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

                      footers =`



                                <tr style='height:17.1pt'>
                                    <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                    <td width="70%" colspan=14 valign=top style='width:70.78%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal align=right style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:right;line-height:normal'>
                                          <b><span style='color:black'>`+Translation('Grand Total (USD)')+`</span> </b>
                                        </p>
                                    </td>
                                    <td width="12%" align=center valign=top style='width:12.38%;border-top:none;border-left:  none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                        `+currency_format_display(response.invoice[0].total_price)+` 
                                        </p>
                                    </td>
                                    <td width="9%" nowrap colspan=2 style='width:9.56%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                </tr>
                                <tr style='height:17.1pt'>
                                    <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                    <td width="70%" colspan=14 valign=top style='width:70.78%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal align=right style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:right;line-height:normal'>
                                          <b><span style='color:red'>`+Translation('Discount (USD)')+`</span> </b>
                                        </p>
                                    </td>
                                    <td width="12%" align=center valign=top style='width:12.38%;border-top:none;border-left:  none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                          <span style='font-size:12.0pt;font-family:"Times New Roman",serif'>
                                          `+currency_format_display(response.invoice[0].actual_discount)+`
                                          </span></p>
                                    </td>
                                    <td width="9%" nowrap colspan=2 style='width:9.56%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                </tr>
                                <tr style='height:17.1pt'>
                                    <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                    <td width="70%" colspan=14 valign=top style='width:70.78%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal align=right style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:right;line-height:normal'>
                                          <b><span style='color:#862D03'>`+Translation('Balance (Not Paid)')+`</span> </b>
                                        </p>
                                    </td>
                                    <td width="12%" align=center style='width:12.38%;border-top:none;border-left:none;  border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                        <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                          <span style='font-size:12.0pt;font-family:"Times New Roman",serif'>
                                          `+currency_format_display(response.invoice[0].total_remained)+`
                                          </span></p>
                                    </td>
                                    <td width="9%" nowrap colspan=2 style='width:9.56%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:17.1pt'>
                                      
                                    </td>
                                </tr>
                                <tr style='height:26.0pt'>
                                    <td width="7%" valign=bottom style='width:7.28%;padding:0in 5.4pt 0in 5.4pt; height:26.0pt'>
                                        <p class=ContactInfo align=left style='margin-top:0in;text-align:left; line-height:105%'>
                                        <b><span style='font-size:9.0pt;line-height:105%'>
                                        `+Translation('Note:')+`
                                        </span></b>
                                        </p>
                                    </td>
                                    <td width="92%" colspan=17 valign=bottom style='width:92.72%;padding:0in 0in 0in 0in;  height:26.0pt'>
                                        <p class=ContactInfo align=left style='margin-top:0in;text-align:left; line-height:105%'>
                                        <b><span style='font-size:9.0pt;line-height:105%'>
                                        `+response.invoice[0].offer_note+` 
                                        </span></b>
                                        </p>
                                    </td>
                                </tr>
                                <tr style='height:30.5pt'>
                                    <td width="7%" valign=top style='width:7.28%;padding:0in 5.4pt 0in 5.4pt;  height:30.5pt'>
                                        <p class=ContactInfo align=left style='text-align:left;line-height:105%'>
                                          <b><span  style='font-size:9.0pt;line-height:105%'>
                                          `+Translation('Signed By:')+`
                                          </span></b> </p>
                                    </td>
                                    <td width="92%" colspan=17 valign=top style='width:92.72%;padding:0in 0in 0in 0in;  height:30.5pt'>

                                    </td>
                                </tr>
                                <tr style='height:6.0pt'>
                                    <td width="100%" colspan=18 valign=top style='width:100.0%;padding:0in 5.4pt 0in 5.4pt;  height:6.0pt'>
                                        <p class=ContactInfo style='margin-top:0in;line-height:105%'>
                                          <span style='font-size:9.0pt;line-height:105%;color:#7F7F7F'>
                                          `+Translation('Make all checks payable to DFAD Company')+`
                                          </span> 
                                        </p>
                                    </td>
                                </tr>
                                <tr style='height:6.0pt'>
                                    <td width="100%" colspan=18 valign=top style='width:100.0%;padding:0in 5.4pt 0in 5.4pt;  height:6.0pt'>
                                        <p class=ThankYou style='line-height:105%'>
                                        `+Translation('Thank you for your business!')+`
                                        </p>
                                    </td>
                                </tr>
                                <tr style='height:6.0pt'>
                                    <td width="100%" colspan=18 valign=top style='width:100.0%;padding:0in 5.4pt 0in 5.4pt;  height:6.0pt'>
                                        <p class=ContactInfo style='margin-top:12.0pt;line-height:105%'>
                                        <span lang=AR-KW dir=RTL style='font-size:10.0pt;line-height:105%;font-family:"Sakkal Majalla";  color:#7F7F7F'>
                                        `+Translation('شارع ١٠٠م محلة نازناز, مقابل مطار أربيل الدولي, أربيل, عراق')+`
                                        </span><span dir=LTR></span><span lang=AR-KW><span dir=LTR></span> </span>
                                        </p>
                                    </td>
                                </tr>
                                <tr style='height:.25in'>
                                    <td width="42%" nowrap colspan=5 style='width:42.02%;padding:0in 5.4pt 0in 5.4pt;  height:.25in'>
                                        <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center'>
                                        `+COMPANY_PHONE+`
                                        </p>
                                    </td>
                                    <td width="16%" nowrap colspan=7 style='width:16.1%;padding:0in 5.4pt 0in 5.4pt;  height:.25in'>
                                        <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center'>
                                        <span style='color:black'>`+Translation('www.dfad.co')+`</span> </p>
                                    </td>
                                    <td width="41%" nowrap colspan=6 style='width:41.86%;padding:0in 5.4pt 0in 5.4pt;  height:.25in'>
                                        <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center'>
                                        <span style='color:black'>`+COMPANY_EMAIL+`</span></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td width="7%" style='width:7.28%;padding:0in 0in 0in 0in'></td>
                                    <td width="16%" style='width:16.5%;padding:0in 0in 0in 0in'></td>
                                    <td width="9%" style='width:9.66%;padding:0in 0in 0in 0in'></td>
                                    <td width="3%" style='width:3.26%;padding:0in 0in 0in 0in'></td>
                                    <td width="9%" colspan=4 style='width:9.22%;padding:0in 0in 0in 0in'></td>
                                    <td width="6%" style='width:6.02%;padding:0in 0in 0in 0in'></td>
                                    <td width="3%" style='width:3.56%;padding:0in 0in 0in 0in'></td>
                                    <td width="5%" colspan=3 style='width:5.68%;padding:0in 0in 0in 0in'></td>
                                    <td width="6%" style='width:6.32%;padding:0in 0in 0in 0in'></td>
                                    <td width="10%" style='width:10.56%;padding:0in 0in 0in 0in'></td>
                                    <td width="12%" style='width:12.38%;padding:0in 0in 0in 0in'></td>
                                    <td width="2%" style='width:2.32%;padding:0in 0in 0in 0in'></td>
                                    <td width="7%" style='width:7.24%;padding:0in 0in 0in 0in'></td>
                                </tr>
                                <tr>
                                    <td width="7%" style='width:7.28%;padding:0in 0in 0in 0in'></td>
                                    <td width="16%" style='width:16.5%;padding:0in 0in 0in 0in'></td>
                                    <td width="9%" style='width:9.66%;padding:0in 0in 0in 0in'></td>
                                    <td width="3%" style='width:3.26%;padding:0in 0in 0in 0in'></td>
                                    <td width="8%" colspan=3 style='width:8.4%;padding:0in 0in 0in 0in'></td>
                                    <td width="0%" style='width:.82%;padding:0in 0in 0in 0in'></td>
                                    <td width="6%" style='width:6.02%;padding:0in 0in 0in 0in'></td>
                                    <td width="3%" style='width:3.56%;padding:0in 0in 0in 0in'></td>
                                    <td width="1%" style='width:1.66%;padding:0in 0in 0in 0in'></td>
                                    <td width="4%" colspan=2 style='width:4.02%;padding:0in 0in 0in 0in'></td>
                                    <td width="6%" style='width:6.32%;padding:0in 0in 0in 0in'></td>
                                    <td width="10%" style='width:10.56%;padding:0in 0in 0in 0in'></td>
                                    <td width="12%" style='width:12.38%;padding:0in 0in 0in 0in'></td>
                                    <td width="2%" style='width:2.32%;padding:0in 0in 0in 0in'></td>
                                    <td width="7%" style='width:7.24%;padding:0in 0in 0in 0in'></td>
                                </tr>
                                <tr height=0>
                                    <td width=76 style='border:none'></td>
                                    <td width=105 style='border:none'></td>
                                    <td width=69 style='border:none'></td>
                                    <td width=23 style='border:none'></td>
                                    <td width=38 style='border:none'></td>
                                    <td width=17 style='border:none'></td>
                                    <td width=5 style='border:none'></td>
                                    <td width=6 style='border:none'></td>
                                    <td width=41 style='border:none'></td>
                                    <td width=27 style='border:none'></td>
                                    <td width=13 style='border:none'></td>
                                    <td width=7 style='border:none'></td>
                                    <td width=23 style='border:none'></td>
                                    <td width=25 style='border:none'></td>
                                    <td width=91 style='border:none'></td>
                                    <td width=128 style='border:none'></td>
                                    <td width=12 style='border:none'></td>
                                    <td width=45 style='border:none'></td>
                                </tr>
                            </table>

                        </div>

                    </div>

                </body>



                  
                     `+print_attach+`
                    </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                       HTML_VIEW = table_invoice + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                        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.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].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=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++){

                        
                       
  
                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i+1)+` </span>
                                                    </td>

                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product_`+i+`" > `+currency_format_display(response.invoice[i].total_invoices_price)+` </span>
                                                    </td>

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

                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <input type="text" id="product_row_total_`+i+`"   class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_payment_discount)+`"  readonly >
                                                    </td>

                                                    <td width=74 style='width:55.5pt;' >
                                                      <input type="text" id="inv_total_paid_`+i+`" data-total-remain-price="`+response.invoice[i].total_remained+`" name="inv_total_paid_`+i+`" class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_remained)+`" placeholder="المبلغ المدفوع لهذه المادة" 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="الدفعة الجديدة" 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(response.invoice[i].total_remained)+`"  placeholder="الباقي" 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="ملاحظات" ></textarea> 
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        
                       
                      } // for i

                      

                      // total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                </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);
                        $("#customer_id_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.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>
                                       `+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=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{
                          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;' class="last_td">
                                                      <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;'>
                                                      <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.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{
                          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" 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 change_delivery_status (id, delivery_status){


      swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("هل انت متأكد من تحويل حالة العرض الحالي الى الحالة الجديدة؟! لانه سيترتب على هذه العملية نقل بين الجداول خصوصا عند تحويله الى وصل بيع.. الرجاء التأكد قبل استكمال العملية"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: استمر!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: true,
              closeOnCancel: true
          },
          function(isConfirm){
            if (isConfirm) {
       
                $.ajax({
                    url: "models/crul_offer.php",
                    type:"POST",
                    dataType: "JSON",
                    data : {inv_id              :id,
                            delivery_status     :delivery_status,
                            type                :'change_delivery_status'}
                })
                .done(function(res) {
                   
                    if(res.is_success == true){

                       
                       

                        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                       
                        
                        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');
                    }

                    
                   
                })
                .fail(function(err) {
                     swal({
                        title: Translation("خطأ"),
                        text: Translation(err),
                        confirmButtonColor: "#66BB6A",
                        type: "error"
                    });
                    
                    

                })
                .always(function() {
                    console.log("complete");
                });
            }
          }); // /confirm
  

        
    }


    function free_stock (id){


      swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("هل انت متأكد من الغاء الحجز المخزني وتحرير المواد التابعة لهذا العرض؟! لانه بمجرد الغاء الحجز سوف لن تستطيع التراجع عن العملية "),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: استمر!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: true,
              closeOnCancel: true
          },
          function(isConfirm){
            if (isConfirm) {
       
                $.ajax({
                    url: "models/crul_offer.php",
                    type:"POST",
                    dataType: "JSON",
                    data : {inv_id              :id,
                            type                :'free_stock'}
                })
                .done(function(res) {
                   
                    if(res.is_success == true){

                       
                       

                        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                       
                        
                        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');
                    }

                    
                   
                })
                .fail(function(err) {
                     swal({
                        title: Translation("خطأ"),
                        text: Translation(err),
                        confirmButtonColor: "#66BB6A",
                        type: "error"
                    });
                    
                    

                })
                .always(function() {
                    console.log("complete");
                });
            }
          }); // /confirm
  

        
    }

    function update_payments (id){

        var row_num1        = id.split('_');
        var row_num         = row_num1[3];
        // alert(row_num)
        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.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: 'error',
                    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.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_remain   = $("#inv_total_paid_"+row_num).attr('data-total-remain-price');
        
          // alert("old_paid="+old_paid)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - 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('');
          $("#inv_row_remaind_price_"+row_num).val(currency_format_display( old_remain));
        }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('Download')+' <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 =response[i][2];
                          
                          attach = attach + '<option data-subtext=" '+tp+' " value="'+response[i][0]+'">'+response[i][1]+'</option>';
                       
                        }
                        $("#stock_id_fk").html(attach);
                        $('#stock_id_fk').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(){

            $.ajax({
                  url : 'models/crul_customer.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  = 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 =[] ;

    // make products as searchable list

    function get_products(row_num){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_product_with_last_buy_price'},
                  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-last-buy-price="'+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

          

         

    }



   


    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 last_buy_price = $("#product_id_fk_"+row_num+" option:selected").attr('data-last-buy-price');

        $("#forign_id_"+row_num).html(forgin_code);
        $("#buy_price_"+row_num).val(last_buy_price); // reset price
        $("#buy_price_per_meter_"+row_num).val(''); // reset price
        $("#purchase_quantity_"+row_num).val(1); // reset quantity
        
        load_prices(row_num);
        load_Serails(row_num);
        load_on_hand(row_num);
        calc_total_item_cost(val,row_num);
        
    }

    function load_on_hand(row_num){
         
          var product_id  = $("#product_id_fk_"+row_num).val();
          var stock_id    = $("#stock_id_fk").val();

          if(stock_id ==null || stock_id =='' || stock_id == undefined){
            noty({
                      width: 200,
                      text: Translation("الرجاء قم بتحديد اسم المخزن لعرض الكمية المتوفرة من هذه المادة"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',
                    });
            return false;
          }
          
          $.ajax({
                  url : 'models/crul_stock_detail.php',
                  type : 'POST',
                  data : {type:'get_on_hand',product_id:product_id,stock_id:stock_id},
                  dataType : 'json',
                  success : function(response) {
                    console.log(response)
                      if(response.data[0].on_hand_quantity <= 0){
                        $("#on_hand_alert_"+row_num).removeClass('bg-success');
                        $("#on_hand_alert_"+row_num).addClass('bg-warning');
                      }else{
                        $("#on_hand_alert_"+row_num).removeClass('bg-warning');
                        $("#on_hand_alert_"+row_num).addClass('bg-success');
                      }
                        $("#on_hand_alert_"+row_num).text(response.data[0].on_hand_quantity);   
                      
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax


       
      // end loading price
    }
   

    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_Serails(row_num){
         
          var P_ID  = $("#product_id_fk_"+row_num).val();
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_serail',id:P_ID},
                  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   value="'+response[i][0]+'">'+response[i][1]+'</option>';
                        }
                        $("#product_serial_id_"+row_num).html(attach);
                        $('#product_serial_id_'+row_num).selectpicker('refresh');

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

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

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

                  }

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

    

    // 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 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 = $("#purchase_quantity_"+row_num).val() * $("#buy_price_per_meter_"+row_num).val();
          
          

          $("#total_item_cost_"+row_num).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
            

            var cur_pay   = $("#payment_total").val();
            var prod_cost = $("#purchase_total").val();


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

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


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

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

            prod_cost = parseFloat(prod_cost);
            cur_pay   = parseFloat(cur_pay);

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

    }


    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);
            }
            
          }


          

          // before discount
          $("#purchase_total_no_disc").val(currency_format_display(purchase_total));

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

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

          }

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

          // price after discount
          purchase_total = purchase_total - actual_disc;
          $("#purchase_total").val(currency_format_display(purchase_total));


    }

    


$(document).ready(function() {
  
    get_products(1);
    get_Profile_price();
    get_Customer();
    
    get_Stock();
    

    // 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();
         calc_total_item_cost(this.value,1);
    });

    // 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  id="num_`+CNT+`">`+CNT+`</td>
                            <td >
                              
                              <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" required="required">

                              </select>
                              <input type="hidden" id="buy_price_`+CNT+`" name="buy_price_`+CNT+`" >
                              
                            </td>
                            <td  id="forign_id_`+CNT+`"></td>
                            <td >
                    

                              <select class="form-control multi_lang" name="product_serial_id_`+CNT+`" id="product_serial_id_`+CNT+`" data-width="100%" placeholder="S.N"  data-live-search="true" >

                              </select>

                            </td>

                            <td >
                      
                                <span class="label btn-block bg-success text-semibold multi_lang" id="on_hand_alert_`+CNT+`"></span>

                            </td>
                            <td >
                              <input type="number" value="1" id="purchase_quantity_`+CNT+`" name="purchase_quantity_`+CNT+`"  class="form-control text-center" placeholder="`+Translation('العدد')+`"  onchange="calc_total_item_cost(this.value,`+CNT+`);" required="required">
                            </td>
                            
                            <td >
                              <input id="last_sell_price_`+CNT+`" name="last_sell_price_`+CNT+`" type="text" class="form-control" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td>
                            <td >
                              <input id="buy_price_per_meter_`+CNT+`" name="buy_price_per_meter_`+CNT+`" type="text" class="form-control" placeholder="`+Translation('سعر بيع الوحدة')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" required="required" >
                            </td>
                            
                            <td  > 
                            
                              <input id="total_item_cost_`+CNT+`" name="total_item_cost_`+CNT+`" type="text" value="0 $" class="form-control text-center" readonly >
                            </td>
                            <td >
                              <textarea type="text" id="purchase_item_note_`+CNT+`" name="purchase_item_note_`+CNT+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" > </textarea>
                            </td>

                            <td > 
                            
                              <input id="offer_sell_item_delivery_name_`+CNT+`" name="offer_sell_item_delivery_name_`+CNT+`" type="text"  class="form-control text-center" placeholder="مدة التسليم" >
                            </td>
                            
                            <td >
                              <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();
    });

   


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

          e.preventDefault();

          var cust_id = $("#customer_id_pay").val();
          // inv_product_other
          
          var pay_price_array                  =[];
          var pay_notes_array                  =[];
          var check_price_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 notes               = $("#pay_note_"+row_num).val();   

              pay_notes_array[k]      = notes;

              check_price_array[k]    = Checks('inv_paid_price_'+row_num,'No',0.0001,null);

              k =k+1;   

            }         
          });
          

          var check_paid  = false;
          var check_ids   = true;

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

            
            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.php",
                type:"POST",
                dataType: "JSON",
                data : {cust_id             :cust_id,
                        row_payments        :pay_price_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() {
                
                $("#submit_add_pay_btn").attr('disabled',false);

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

          

    });


   




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

          var cnt                                 = $("#total_rows").val();
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var serials_array                       =[];
          var unit_price_array                    =[];
          var buy_price_array                     =[];
          var delivery_array                      =[];
          // var discount_type_array                 =[];
          // var discount_actual_array               =[];
          
          var row_total_price_array               =[];
          var notes_array                         =[];
          
          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
         
          var k=1;

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

              var productID       = $("#product_id_fk_"+i).val();
              var serailID        = $("#product_serial_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 last_buy_price  = $("#buy_price_"+i).val();
              var delivery        = $("#offer_sell_item_delivery_name_"+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');

              

              if(productID != undefined && productID != null && productID != ''){

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

                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.00000001);
                
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                
                row_total_price_array[k]  = row_total_price;
                
                serials_array[k]          = serailID;
                buy_price_array[k]        = last_buy_price;
                delivery_array[k]         = delivery;
                // discount_type_array[k]    = discount_type;
                // discount_actual_array[k]  = discount_actual;

                k++;
              }
          }
          
          var customer_id_fk              = $("#customer_id_fk").val();  
          var validity                    = $("#validity").val();
          var invoice_date                = $("#invoice_date").val();
          var price_profile_id            = $("#price_profile_id").val();
          var delivery_time               = $("#delivery_time").val();
          var offer_status                = $("#offer_status").val();
          var invoice_note                = $("#invoice_note").val();
          var stock_id_fk                 = $("#stock_id_fk").val();
          var pay_terms                   = $("#pay_terms").val();

          var total_invoice_no_disc       = $("#purchase_total_no_disc").val();
          var total_invoice               = $("#purchase_total").val();
          var request_for_quta_number     = $("#request_for_quta_number").val();

          var discount                    = $("#discount_total").val();
          var discount_type               = $("#discount_total").attr('data-discount-type');
          var discount_actual             = $("#discount_total").attr('data-discount-actual');


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

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

          // if(isNaN(total_paid) || total_paid =="" || total_paid==null || total_paid==undefined){
          //   total_paid ="";
          // }
         

          

          var Check1      = Checks('customer_id_fk');
          var Check2      = Checks('invoice_date');
          var Check3      = Checks('offer_status');
          var Check4      = Checks('stock_id_fk');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkprice  = 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_price[m]==false){
              checkprice = false;
            }

            
          }




        if(Check1 && Check2 && Check3 && Check4 && CheckPro && checkQty  && checkprice){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_offer.php",
                type:"POST",
                dataType: "JSON",
                data : {customer_id_fk            :customer_id_fk,
                        validity                  :validity,
                        invoice_date              :invoice_date,
                        delivery_time             :delivery_time,
                        offer_status              :offer_status,
                        invoice_note              :invoice_note,
                        stock_id_fk               :stock_id_fk,
                        request_for_quta_number   :request_for_quta_number,
                        pay_terms                 :pay_terms,

                        discount                  :discount,
                        discount_type             :discount_type,
                        discount_actual           :discount_actual,
                        

                        total_invoice_no_disc     :total_invoice_no_disc,
                        total_invoice             :total_invoice,
                        
                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_price                :unit_price_array,
                        sell_item_note            :notes_array,
                        row_price                 :row_total_price_array,
                        serials_id                :serials_array,
                        last_buy_price            :buy_price_array,
                        delivery_item             :delivery_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');
                    $("#total_rows").val('1');

                    $(".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: 'error',
                    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_purchase.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"
                              });
                          }
                    }
                });
              }
    });



   
    


});







$(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': '&'+Left_Arraw+'arr;', 'previous': '&'+Right_Arraw+'arr;' }
            
        },
        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");


    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({
        
        keys: {
            className: 'focus focus-success'
        },
        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_offer.php",
        "data": function(d){
          d.type = "load";
          if(query_ip !='not'){
            d.ip =query_ip ;
          }
        }
        },
        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) {


                          var menus = ``;
                          var menus1 = ``;
                            
                          if(row[8] !=1){

                           
                            menus = `
                                      <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="change_delivery_status(`+row[0]+`,'0')"  data-original-title='Show Invoice Payments'>
                                                <i class='icon-history text-primary-400'></i> `+Translation('تغيير الحالة الى عرض')+`
                                              </a>
                                            </li>
                                            <li>
                                              <a href='#' onclick="change_delivery_status(`+row[0]+`,'1')"  data-original-title='Add New Payments to this Invoice'>
                                                <i class='icon-cart-add text-success-600'></i>`+Translation('تحويله الى وصل بيع')+` 
                                              </a>
                                            </li>
                                            <li>
                                              <a href='#' onclick="change_delivery_status(`+row[0]+`,'2')"  data-original-title='Edit or Remove Invoice Payments'>
                                                <i class='icon-warning22 text-danger-600'></i>`+Translation('تم رفض العرض')+` 
                                              </a>
                                            </li>

                                          </ul>
                                        </li>
                                        `;

                            }


                            if(row[7] ==1){

                           
                            menus1 = `
                                      <li class='text-primary-600'>
                                            <a href='#' class='text-purple-400' onclick="free_stock(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('الغاء الحجز المخزني')+`'>
                                                <i class='icon-spinner11'></i>
                                            </a>
                                        </li>
                                        `;

                            }



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

                                        
                                        <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="add_payments(`+row[12]+`)" data-popup='tooltip' data-original-title='`+Translation('اضافة دفعه على حساب الزبون')+`'>
                                                <i class='icon-cash'></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>
                                        
                                        `+menus+menus1+`

                                    </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[12]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض جميع كشوفات الحساب لهذا الزبون')+`'>`+data+`</a>`;


               },
               "targets": 3
            },

            
           

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

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

            
            {
                "render": function(data, type, row){
                   if(data ==1 ){
                     status=  `<span class="label bg-orange btn-block ">`+Translation('Booking From Stock')+`</span>`;
                   }else if(data ==0){
                     status = '<span class="label bg-pink  btn-block ">'+Translation('Not Booking')+'  </span>';
                   }
                   return  status;
                },
                "targets": 7
            },
            
            
            

            {
                "render": function(data, type, row){
                   if(data ==1 ){
                     status=  `<span class="label label-success btn-block ">`+Translation('Converted to Invoice')+`</span>`;
                   }else if(data ==2){
                     status = '<span class="label bg-danger-400  btn-block ">'+Translation('Rejected')+'  </span>';
                   }else if(data ==0){
                     status = '<span class="label bg-primary  btn-block ">'+Translation('Offer')+'  </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"><i class="icon-close2 text-teal"></i>`+Translation('ازالة الفلتر')+`  </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=2"><i class="icon-coins text-success"></i>`+Translation('الواصل')+` </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=1"><i class="icon-bell-check text-info"></i>`+Translation('واصل جزئيا')+`  </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=0"><i class="icon-alarm-check text-danger"></i>`+Translation('غير واصل')+` </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=4"><i class=" icon-task text-violet"></i>`+Translation('عروض')+`  </a></li>
          //                 <li><a href="index.php?p=invoice&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();
        });
    });


    // high light row and column
    var lastIdx = null;
     
    $('.datatable-highlight tbody').on('mouseover', 'td', function() {
        var chk_inx =table.cell(this).index();
        if(chk_inx != undefined && chk_inx !=null && chk_inx !='' ){ // because child row
          var colIdx = table.cell(this).index().column;

          if (colIdx !== lastIdx) {
              $(table.cells().nodes()).removeClass('active');
              $(table.column(colIdx).nodes()).addClass('active');
          }
        }
        
    }).on('mouseleave', function() {
        $(table.cells().nodes()).removeClass('active');
    });

    // end highlight row and column

    // 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'
    });


});



