var table ;

var profile_id = '';

    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                            setTimeout(function() {
                              window.print()
                            }, 2000)
                        </script>
                        `;
  
    var table_invoice     =`
                            <html>
                              <head>
                              <title>Invoice</title>
                              <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                              </head>
                              <style>
                              #Table_01 {
                              text-align: center;
                              font-weight:600;
                              }
                              .footer11 {
                                  position:fixed;
                                  
                                  bottom:0;
                                  
                              }
                              </style>
                              <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
                                <center>

                              `;

    



    function edit_items(itemid){
          
          $("#edit_objid").val(itemid);
          $("#update_type").val('update');
          
          get_Zone();

          var headers           = '';
          var attach            = "";
          var attach_d          = "";
          var attach_other      = "";
          var footers           = "";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          var total_rows        = 0;
          var doctor_total_rows        = 0;
          var resp;
          $.ajax({
                url : 'models/crul_plan.php',
                type : 'POST',
                data : {type:'get_edit_plan', id : itemid},
                dataType : 'json',
                success : function(response) {
                  
                  resp = response;

                 
                  
                 
                 
                  $("#edit_plan_title").val(response.plan[0].plan_title);
                  $("#edit_plan_description").val(response.plan[0].plan_description);
                  $("#edit_plan_start_date").val(response.plan[0].plan_start_date);
                  $("#edit_plan_end_date").val(response.plan[0].plan_end_date);
                  $("#edit_city_id_fk").val(response.plan[0].city_id_fk).selectpicker('refresh');
                  $("#edit_zone_id_fk").val(response.plan[0].zone_id_fk).selectpicker('refresh');
                  $("#edit_plan_note").val(response.plan[0].plan_note);
                  

                  
                  var ids =['','','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','',''];

               
                for(var i=0; i<response.saleman.length; i++){
                  ids[i] =  response.saleman[i].team_leader_id_fk;
                }

               
                $("#edit_team_leader_id_fk").selectpicker('val',[ids[0],
                                                            ids[1],
                                                            ids[2],
                                                            ids[3],
                                                            ids[4],
                                                            ids[5],
                                                            ids[6],
                                                            ids[7],
                                                            ids[8],
                                                            ids[9],
                                                            ids[10],
                                                            ids[11],
                                                            ids[12],
                                                            ids[13],
                                                            ids[14],
                                                            ids[15],
                                                            ids[16],
                                                            ids[17],
                                                            ids[18],
                                                            ids[19],
                                                            ids[20],
                                                            ids[21],
                                                            ids[22],
                                                            ids[23],
                                                            ids[24],
                                                            ids[25],
                                                            ids[26],
                                                            ids[27],
                                                            ids[28],
                                                            ids[29],
                                                            ids[30],
                                                            ids[31],
                                                            ids[32],
                                                            ids[33],
                                                            ids[34],
                                                            ids[35],
                                                            ids[36],
                                                            ids[37],
                                                            ids[38],
                                                            ids[39],
                                                            ids[40],
                                                            ids[41],
                                                            ids[42],
                                                            ids[43],
                                                            ids[44],
                                                            ids[45],
                                                            ids[46],
                                                            ids[47],
                                                            ids[48],
                                                            ids[49],
                                                            ids[50],

                                                            ]);

                  total_rows = response.product.length;                     
                  doctor_total_rows = response.plan.length;                     
                  
                  $("#edit_total_rows").val(total_rows);
                  $("#edit_total_rows_doctor").val(doctor_total_rows);
                  
                  attach_d =  `<div class="form-group">
                              <div class="table-responsive1">
                                <table  class="table col-sm-12 table-bordered .table-sm">
                                  <thead>
                                    <tr class="bg-blue ">
                                      <th>#</th>
                                      <th class="multi_lang">`+Translation('الطبيب')+`</th>
                                      <th class="multi_lang">`+Translation('عدد الزيارات الموصى بها')+`</th>
                                     
                                      <th class="multi_lang">`+Translation('ملاحظة')+`</th>
                                      <th></th>
                                    </tr>
                                  </thead>
                                  <tbody id="edit_doctor_item_body" >
                                
                                  `;

                  var last_i    = 0;
                  var clss_last = '';
                  var area_all  = 0;

                  for(var i=0 ; i < doctor_total_rows;i++){

                      if( i == (doctor_total_rows -1)){
                        clss_last = 'tab_last';
                      }    
                     

                      attach_d = attach_d + `     
                                        <tr  id="edit_doctor_item_row_`+i+`" >
                                          <td  id="edit_doctor_num_`+i+`">`+(+i + +1)+`</td>
                                          
                                          <td >
                                           
                                            <select class="form-control multi_lang stop_enter" name="edit_doctor_id_fk_${i}" id="edit_doctor_id_fk_${i}" data-width="100%"  data-live-search="true"  required="required" tabindex="">

                                            </select>

                                          </td>

                                          <td >
                                            <input type="number" value="`+parseInt(response.plan[i].number_of_visit)+`" id="edit_number_of_visit_${i}" name="edit_number_of_visit_${i}"  class="form-control text-center multi_lang stop_enter" placeholder="عدد الزيارات" value="1" tabindex="">
                                          </td>

                                          <td >
                                            <input value="`+(response.plan[i].plan_doctor_notes)+`" id="edit_plan_doctor_notes_${i}" name="edit_plan_doctor_notes_${i}" type="text" class="form-control multi_lang stop_enter" placeholder="ملاحظة" >
                                          </td>

                                         
                                          <td >
                                            <button class="btn btn-link btn-xs edit_btn_add_item_doctor `+clss_last+`" onclick="Add_Rows_Doctor()">
                                              <i  class="icon-add text-blue"></i>
                                            </button>
                                            <button tabindex="-1" class="btn btn-link btn-xs edit_btn_remove_item_doctor" id="edit_row_`+i+`" onclick="remove_rows_doctor(`+i+`)">
                                              <i  class="icon-subtract text-danger-600"></i>
                                            </button>
                                            
                                          </td>
                                        </tr>
                                              
                                              `;
                        
                        
                       
                  } // for i



                  attach =  `<div class="form-group">
                              <div class="table-responsive1">
                                <table  class="table col-sm-12 table-bordered .table-sm">
                                  <thead>
                                    <tr class="bg-blue ">
                                      <th>#</th>
                                      <th width="20%" class="multi_lang">`+Translation('المادة')+`</th>
                                      <th class="multi_lang">`+Translation('الكمية')+`</th>
                                      <th class="multi_lang">`+Translation('سعر الوحدة')+`</th>
                                      <th class="multi_lang">`+Translation('العرض')+`</th> 
                                      <th width="12%" class="multi_lang">`+Translation('ملاحظة')+`</th>
                                      <th></th>
                                    </tr>
                                  </thead>
                                  <tbody id="edit_purchase_item_body" >
                                
                                  `;
                     
                  // show sell item details  

                  var last_i    = 0;
                  var clss_last = '';
                  var area_all  = 0;
                  for(var i=0 ; i < total_rows;i++){

                      if( i == (total_rows -1)){
                        clss_last = 'tab_last';
                      }    
                      

                      attach = attach + `     
                                        <tr  id="edit_item_row_`+i+`" >
                                          <td  id="edit_num_`+i+`">`+(+i + +1)+`</td>
                                          
                                          <td >
                                           
                                            <select class="form-control multi_lang" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`"   data-live-search="true" required="required">

                                            </select>

                                          </td>

                                          <td >
                                            <input type="number" value="`+parseInt(response.product[i].quantity)+`" id="edit_purchase_quantity_`+i+`" name="edit_purchase_quantity_`+i+`"  class="form-control text-center " placeholder="`+Translation('الكمية')+`"   required="required">

                                          </td>

                                          <td >
                                            <input  value="`+((response.product[i].plan_sell_price))+`" id="edit_sell_price_`+i+`" name="edit_sell_price_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع الوحدة')+`"  required="required" >

                                          </td>


                                          <td >
                                            <input  value="`+(response.product[i].plan_product_offer)+`" id="edit_discount_`+i+`" name="edit_discount_`+i+`" type="text" class="form-control text-center"  placeholder="`+Translation('العرض')+`"  >
                                          </td>

                                         

                                       

                                          <td >
                                            <input value="`+response.product[i].plan_product_notes+`" id="edit_sell_item_note_`+i+`" name="edit_sell_item_note_`+i+`" type="text" class="form-control multi_lang " placeholder="`+Translation('ملاحظة')+`" >
                                          </td>                                      


                                          <td >
                                            <button class="btn btn-link btn-xs edit_btn_add_item `+clss_last+`" onclick="Add_Rows()">
                                              <i  class="icon-add text-blue"></i>
                                            </button>
                                            <button tabindex="-1" class="btn btn-link btn-xs btn_remove_item" id="edit_row_`+i+`" onclick="remove_rows(`+i+`)">
                                              <i  class="icon-subtract text-danger-600"></i>
                                            </button>
                                            
                                          </td>
                                        </tr>
                                              
                                              `;
                        
                        
                       
                  } // for i



                  footers =`  
                                  </tbody>
                                  <tfoot>
                
                                   
                                  </tfoot>
                                </table>
                              </div>

                            </div>`;

                      

                     
                },
                complete: function() {

                      HTML_VIEW_PAY =  headers + attach_d + footers + attach  + footers;
                     
                      $("#edited_purchase_contain").html(HTML_VIEW_PAY);
                      // $("#inv_numb").val(itm);


                      

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

                     
                      for(var i=0 ; i < total_rows;i++){ // to load product in select
                       
                        edit_get_products(i,resp.product[i].product_id_fk,'edit_product_id_fk_');
                      }

                      for(var i=0 ; i < doctor_total_rows;i++){ // to load product in select
                       
                        edit_get_Doctor(i,resp.plan[i].doctor_id_fk,'edit_doctor_id_fk_');
                      }

                     
                     
                }

          }); // submit ajax



    }   



    

    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_plan.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_plan.php',
                type : 'POST',
                data : {type:'show_plan', id : itm},
                dataType : 'json',
                success : function(response) {
                    // console.log(response)
                    
                      headers =`

                                  <table id="Table_01" width="795" height="796" border="1" cellpadding="0" cellspacing="0">
                                    <tr>
                                      <td colspan="10">
                                        ${response.plan[0].plan_title}
                                      </td>
                                      
                                    </tr>
                                    <tr>
                                      <td >
                                        Plan Number
                                      </td>

                                      <td >
                                        ${response.plan[0].plan_number}
                                      </td>

                                      <td >
                                        City
                                      </td>

                                      <td >
                                        ${response.plan[0].city_name}
                                      </td>

                                      <td >
                                        Zone
                                      </td>

                                      <td >
                                        ${response.plan[0].zone_name}
                                      </td>

                                      <td >
                                        Start Date
                                      </td>

                                      <td >
                                        ${response.plan[0].plan_start_date}
                                      </td>

                                      <td >
                                        Expire Date
                                      </td>

                                      <td >
                                        ${response.plan[0].plan_end_date}
                                      </td>
                                    </tr>

                                    <tr>
                                        <td colspan="10">
                                         Description
                                        </td>
                                    </tr>

                                    <tr>
                                        <td colspan="10">
                                          ${response.plan[0].plan_description}
                                        </td>
                                    </tr>

                                    <tr>
                                        <td colspan="10">
                                          Note
                                        </td>
                                    </tr>

                                    <tr>
                                        <td colspan="10">
                                          ${response.plan[0].plan_note}
                                        </td>
                                    </tr>

                                    `;
                        
                        

                      attach = `<tr style="">
                                  <td colspan="2">
                                   No
                                  </td>
                                  <td colspan="8" style="text-align:left;">
                                     Teamleader Name
                                  </td>
                                  
                                </tr>`;

                      for(var i=0 ; i < response.saleman.length;i++){    

                          attach = attach + `
                                              <tr style="">
                                                <td colspan="2">
                                                  `+(i+1)+`
                                                </td>
                                                <td colspan="8" style="text-align:left;">
                                                   ${response.saleman[i].full_name}
                                                </td>
                                                
                                              </tr> `;
                       
                      } // for i

                      attach = attach+  `<tr style="">
                                    <td >
                                      No
                                    </td>
                                    <td colspan="3" style="text-align:left;">
                                       Doctor Name
                                    </td>
                                    <td >
                                      Number of Visit
                                    </td>
                                    <td colspan="3">
                                      Note
                                    </td>
                                    <td >
                                      Doctor Speciality
                                    </td>
                                    <td >
                                      Doctor Address
                                    </td>
                                    
                                  </tr> `;
                     
                      

                      for(var i=0 ; i < response.plan.length;i++){    

                          attach = attach + `
                                              <tr style="">
                                                <td >
                                                  `+(i+1)+`
                                                </td>
                                                <td colspan="3" style="text-align:left;">
                                                   ${response.plan[i].doctor_name}
                                                </td>
                                                <td >
                                                  ${response.plan[i].number_of_visit}
                                                </td>
                                                <td colspan="3">
                                                 ${response.plan[i].plan_doctor_notes}
                                                </td>
                                                <td >
                                                  ${response.plan[i].doctor_specialty}
                                                </td>

                                                <td >
                                                  ${response.plan[i].doctor_address}
                                                </td>
                                                
                                              </tr> `;
                        
                        
                       
                      } // for i


                      attach = attach+  `<tr style="">
                                    <td >
                                      No
                                    </td>
                                    <td colspan="2"  style="text-align:left;">
                                       Product Name
                                    </td>
                                    <td >
                                      Product Code
                                    </td>
                                    <td >
                                      Badge No.
                                    </td>
                                    <td >
                                      Quantity
                                    </td>
                                    <td >
                                      Sell Price
                                    </td>

                                    <td >
                                      Offer
                                    </td>

                                    <td colspan="2">
                                      Note
                                    </td>
                                    
                                  </tr> `;
                     
                      

                      for(var i=0 ; i < response.product.length;i++){    

                          attach = attach + `
                                              <tr style="">
                                                <td >
                                                  `+(i+1)+`
                                                </td>
                                                <td colspan="2" style="text-align:left;">
                                                   ${response.product[i].product_name}
                                                </td>
                                                <td >
                                                  ${response.product[i].product_code}
                                                </td>
                                                <td >
                                                 ${response.product[i].badge_no}
                                                </td>
                                                <td >
                                                  ${response.product[i].quantity}
                                                </td>

                                                <td >
                                                  ${response.product[i].plan_sell_price}
                                                </td>

                                                <td >
                                                  ${response.product[i].plan_product_offer}
                                                </td>

                                                <td colspan="2">
                                                  ${response.product[i].plan_product_notes}
                                                </td>
                                                
                                              </tr> `;
                        
                        
                       
                      } // for i


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

                      footers =`
                                
                                
                              </table>
                              <!-- End Save for Web Slices -->
                              </body>
                            </center>
                         

                  
                     `+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


    }
    
    


    


    



  


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

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


  
   

    




    function get_City(){

      $.ajax({
                      url : 'models/crul_city.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select City')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

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

                }); // submit ajax

    }

    function get_Zone(id=0){

      $.ajax({
                      url : 'models/crul_zone.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_id'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select Zone')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

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

                }); // submit ajax

    }

    

    function get_Team_leader(){

      $.ajax({
                url : 'models/crul_teamleader.php',
                type : 'POST',
                data : {type:'get_team_leader'},
                dataType : 'json',
                success : function(response) {
                    var attach ='';
                    
                    for(var i=response.length-1 ; i >= 0;i--){
                        
                        attach = attach + '<option value="'+response[i].staff_id+'">'+response[i].full_name+'</option>';
                       

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

            }); // submit ajax

    }
   
    


    



   

    function load_prices(row_num){
        
          
          
          var sell_price    = $("#product_id_fk_"+row_num+" option:selected").attr('data-sell-price');
         

          

          if(sell_price=='' || sell_price ==null){
              noty({
                      width: 200,
                      text: Translation("لم يتم تحديد سعر بيع لهذه المادة"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',

                    });
              return false;
          }

          $("#sell_price_"+row_num).val(sell_price);


         
      // end loading price
    }


    function edit_load_prices(row_num){
        
          var sell_price    = $("#edit_product_id_fk_"+row_num+" option:selected").attr('data-sell-price');
         

          

          if(sell_price=='' || sell_price ==null){
              noty({
                      width: 200,
                      text: Translation("لم يتم تحديد سعر بيع لهذه المادة"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',

                    });
              return false;
          }

          $("#edit_sell_price_"+row_num).val(sell_price);

    }

   


    


    function Add_Rows(){

      var curnt_row_num = $("#edit_total_rows").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`

                          <tr  id="edit_item_row_`+CNT+`" >
                            <td  id="edit_num_`+CNT+`">`+(+CNT + +1)+`</td>


                            <td >
                                           
                              <select class="form-control multi_lang" name="edit_product_id_fk_`+CNT+`" id="edit_product_id_fk_`+CNT+`"   onchange="edit_load_prices(`+CNT+`);" data-live-search="true" required="required">

                              </select>

                            </td>

                            <td >
                              <input type="number" value="1" id="edit_purchase_quantity_`+CNT+`" name="edit_purchase_quantity_`+CNT+`"  class="form-control text-center " placeholder="`+Translation('الكمية')+`"   required="required">

                            </td>

                            <td >
                              <input  value="" id="edit_sell_price_`+CNT+`" name="edit_sell_price_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع الوحدة')+`"  required="required" >

                            </td>


                            <td >
                              <input  value="" id="edit_discount_`+CNT+`" name="edit_discount_`+CNT+`" type="text" class="form-control text-center" data-discount-type="" data-discount-actual="" placeholder="`+Translation('التخفيضات')+`"  >
                            </td>

                           

                           

                            <td >
                              <input value="" id="edit_sell_item_note_`+CNT+`" name="edit_sell_item_note_`+CNT+`" type="text" class="form-control multi_lang " placeholder="`+Translation('ملاحظة')+`" >
                            </td>
                             


                            <td >
                              <button class="btn btn-link btn-xs edit_btn_add_item tab_last" onclick="Add_Rows()">
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button tabindex="-1" class="btn btn-link btn-xs btn_remove_item" id="edit_row_`+CNT+`" onclick="remove_rows(`+CNT+`)">
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#edit_purchase_item_body").append(attach_new_row);
            $("#edit_total_rows").val(CNT);
            get_products(CNT);
           

    }


    function remove_rows(row_num){
    
          
          $("#edit_item_row_"+row_num).remove();
         
    
    }

    function Add_Rows_Doctor(){

      var curnt_row_num = $("#edit_total_rows_doctor").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`

                          <tr  id="edit_doctor_item_row_`+CNT+`" >
                            <td  id="edit_doctor_num_`+CNT+`">`+(+CNT + +1)+`</td>


                            <td >
                                           
                              <select class="form-control multi_lang" name="edit_doctor_id_fk_`+CNT+`" id="edit_doctor_id_fk_`+CNT+`"   data-live-search="true" required="required">

                              </select>

                            </td>

                            <td >
                              <input type="number" value="1" id="edit_number_of_visit_`+CNT+`" name="edit_number_of_visit_`+CNT+`"  class="form-control text-center " placeholder="`+Translation('عدد الزيارات الموصى بها')+`"   required="required">

                            </td>

                            

                            <td >
                              <input value="" id="edit_plan_doctor_notes_`+CNT+`" name="edit_plan_doctor_notes_`+CNT+`" type="text" class="form-control multi_lang " placeholder="`+Translation('ملاحظة')+`" >
                            </td>
                             


                            <td >
                              <button class="btn btn-link btn-xs edit_btn_add_item_doctor tab_last" onclick="Add_Rows_Doctor()">
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button tabindex="-1" class="btn btn-link btn-xs edit_btn_remove_item_doctor" id="edit_row_`+CNT+`" onclick="remove_rows_doctor(`+CNT+`)">
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#edit_doctor_item_body").append(attach_new_row);
            $("#edit_total_rows_doctor").val(CNT);
            get_Doctor(CNT);
           

    }

    function remove_rows_doctor(row_num){
    
          
          $("#edit_doctor_item_row_"+row_num).remove();
         
    
    }

    
    function auto_number(){

        var curnt_row_num = $("#total_rows").val();
        var CNT = +curnt_row_num + +1;
        var k =1;
        for (var i = 1; i <= CNT; i++) {
          if($("#num_"+i).length > 0){
            $("#num_"+i).text(k);
            k++;
          }
          
        }

    }

    function auto_number_doctor(){

        var curnt_row_num = $("#total_rows_doctor").val();
        var CNT = +curnt_row_num + +1;
        var k =1;
        for (var i = 1; i <= CNT; i++) {
          if($("#doctor_num_"+i).length > 0){
            $("#doctor_num_"+i).text(k);
            k++;
          }
          
        }

    }


    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--){
                          
                         
                        attach = attach + '<option  data-subtext="" value="'+response[i].product_id+'" data-sell-price="'+response[i].sell_price+'"  >'+response[i].product_name+'</option>';

                          
                      }
                       
                        
                        $("#product_id_fk_"+row_num).html(attach);
                        $('#product_id_fk_'+row_num).selectpicker('refresh');

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

            }); // submit ajax

          

         

    }

    function edit_get_products(row_num,id=null,typ=null){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_product_with_last_buy_price'},
                  dataType : 'json',
                  success : function(response) {
                        var attach ='<option value="" selected="selected">'+Translation('اختيار المادة')+'</option>';
                        
                        for(var i=response.length-1 ; i >= 0;i--){   
                           
                          attach = attach + '<option  data-subtext="" value="'+response[i].product_id+'" data-sell-price="'+response[i].sell_price+'"  >'+response[i].product_name+'</option>';
                            
                        }  
                      
                        
                        if(typ == 'edit_product_id_fk_'){
                          $("#"+typ+row_num).html(attach);
                          $("#"+typ+row_num).selectpicker('refresh');
                        }
                        
                        


                        if(id !=null && id !=''){
                          $('#'+typ+row_num).val(id).selectpicker('refresh');
                        }
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }

    function get_Doctor(row_num,typo){

      if (typo =='city') {
        var id    = $("#city_id_fk").val();
      }else if (typo =='zone') {
        var id    = $("#zone_id_fk").val();
      }else if (typo =='sub-zone') {
        var id    = $("#sub_zone_id_fk").val();
      }else if (typo =='quarter') {
        var id    = $("#quarter_id_fk").val();
      }else if (typo =='street') {
        var id    = $("#street_id_fk").val();
      }



      $.ajax({
                url : 'models/crul_doctor.php',
                type : 'POST',
                data : {
                          id:id,
                          typo:typo,
                          type:'get_with_id_type'},
                dataType : 'json',
                success : function(response) {
                    var attach ='<option value="" selected="selected">Select Doctor</option>';
                    
                    for(var i=response.length-1 ; i >= 0;i--){
                        
                        attach = attach + '<option value="'+response[i].doctor_id+'">'+response[i].doctor_name+'</option>';
                       

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

            }); // submit ajax

    }

    function edit_get_Doctor(row_num,id=null,typ=null){
          
          $.ajax({
                  url : 'models/crul_doctor.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                      
                      var attach ='<option value="" selected="selected">Select Doctor</option>';
                    
                      for(var i=response.length-1 ; i >= 0;i--){
                          
                          attach = attach + '<option value="'+response[i].doctor_id+'">'+response[i].doctor_name+'</option>';
                         

                      }
                      
                        
                        if(typ == 'edit_doctor_id_fk_'){
                          $("#"+typ+row_num).html(attach);
                          $("#"+typ+row_num).selectpicker('refresh');
                        }
                        
                        


                        if(id !=null && id !=''){
                          $('#'+typ+row_num).val(id).selectpicker('refresh');
                        }
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }

    function get_Sub_Zone(id=0){

      $.ajax({
                      url : 'models/crul_sub_zone.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_id'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select Sub Zone')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#sub_zone_id_fk").html(attach);
                            $("#edit_sub_zone_id_fk").html(attach);
                            $('#sub_zone_id_fk').selectpicker('refresh');
                            $("#edit_sub_zone_id_fk").selectpicker('refresh');

                            $("#excel_sub_zone_id_fk").html(attach);
                            $("#excel_sub_zone_id_fk").selectpicker('refresh');

                            $("#delete_sub_zone_id_fk").html(attach);
                            $("#delete_sub_zone_id_fk").selectpicker('refresh');

                            $("#print_sub_zone_id_fk").html(attach);
                            $("#print_sub_zone_id_fk").selectpicker('refresh');

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

                }); // submit ajax

    }

    function get_Quarter(id=0){

      $.ajax({
                      url : 'models/crul_quarter.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_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--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#quarter_id_fk").html(attach);
                            $("#edit_quarter_id_fk").html(attach);
                            $('#quarter_id_fk').selectpicker('refresh');
                            $("#edit_quarter_id_fk").selectpicker('refresh');

                            $("#excel_quarter_id_fk").html(attach);
                            $("#excel_quarter_id_fk").selectpicker('refresh');
                            $("#delete_quarter_id_fk").html(attach);
                            $("#delete_quarter_id_fk").selectpicker('refresh');

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

                }); // submit ajax

    }

    function get_Street(id=0){

      $.ajax({
                      url : 'models/crul_street.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_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--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#street_id_fk").html(attach);
                            $("#edit_street_id_fk").html(attach);
                            $('#street_id_fk').selectpicker('refresh');
                            $("#edit_street_id_fk").selectpicker('refresh');

                            $("#excel_street_id_fk").html(attach);
                            $("#excel_street_id_fk").selectpicker('refresh');

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

                }); // submit ajax

    }
  

   

$(document).ready(function() {
  
    get_products(1);
    get_City();
    
    get_Team_leader();

    $("#city_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Zone(ID);
      get_Doctor(1,'city');

    });

    $("#zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Sub_Zone(ID);
      get_Doctor(1,'zone');
    });

    $("#sub_zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Quarter(ID);
      get_Doctor(1,'sub-zone');

    });

    $("#quarter_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Street(ID);
      get_Doctor(1,'quarter');

    });

    $("#street_id_fk").on('change',function(e){    
      var ID   = $(this).val();
     
      get_Doctor(1,'street');

    });
   

    
    $("#add_form").on('change', '[id^="product_id_fk_"]',function(e){
          
       var ID   = $(this).attr('id');
       var num  = ID.split('_');
       load_prices(num[3]);

      
    });
    
    



   

    // to prevent default show modal on page load

   

    // 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 stop_enter" name="product_id_fk_`+CNT+`" id="product_id_fk_`+CNT+`" data-width="100%"    data-live-search="true" required="required">

                              </select>
                            </td>
                            
                            <td >
                              <input type="number" value="1" id="purchase_quantity_`+CNT+`" name="purchase_quantity_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('QNTY')+`"   required="required">
                            </td>

                            <td  >
                              <input type="text" id="sell_price_`+CNT+`" name="sell_price_`+CNT+`"  class="form-control text-center multi_lang stop_enter" placeholder="`+Translation('سعر الوحدة')+`" required="required" >
                            </td>
                            <td >
                              <input id="discount_`+CNT+`" name="discount_`+CNT+`" type="text" value="" class="form-control text-center text-black text-size-large stop_enter" data-discount-type="" data-discount-actual=""  >
                             
                            </td>


                        
                           
                        
                            <td >
                              <input type="text" id="sell_item_note_`+CNT+`" name="sell_item_note_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ملاحظة')+`" >
                            </td>
                            
                            <td >
                              <button class="btn btn-link btn-xs btn_add_item" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button tabindex="-1" 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);
            auto_number();


    });


     // add new row to purchase menu
    $("#doctor_item_body").on('click','.btn_add_item_doctor',function(e){
      e.preventDefault();
      var curnt_row_num = $("#total_rows_doctor").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`
                          <tr  id="doctor_item_row_`+CNT+`" >
                            <td  id="num_`+CNT+`">`+CNT+`</td>
                            
                            
                            <td >
                              <select class="form-control multi_lang stop_enter" name="doctor_id_fk_`+CNT+`" id="doctor_id_fk_`+CNT+`" data-width="100%"    data-live-search="true" required="required">

                              </select>
                            </td>
                            
                            <td >
                              <input type="number" value="1" id="number_of_visit_`+CNT+`" name="number_of_visit_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('عدد الزيارات')+`"   required="required">
                            </td>

                                   
                        
                            <td >
                              <input type="text" id="plan_doctor_notes_`+CNT+`" name="plan_doctor_notes_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ملاحظة')+`" >
                            </td>
                            
                            <td >
                              <button class="btn btn-link btn-xs btn_add_item_doctor" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button tabindex="-1" class="btn btn-link btn-xs btn_remove_item_doctor" id="row_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#doctor_item_body").append(attach_new_row);
            $("#total_rows_doctor").val(CNT);
            get_Doctor(CNT);
            auto_number_doctor();


    });

     // remove current row 
    $("#doctor_item_body").on('click','.btn_remove_item_doctor',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[1];
          $("#doctor_item_row_"+row_num).remove();
          
          auto_number_doctor();
    });

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

     // to prevent submitting form
    $("#edited_purchase_contain").on('click','.edit_btn_add_item',function(e){
        e.preventDefault();

    });


    $("#edited_purchase_contain").on('click','.edit_btn_add_item_doctor',function(e){
        e.preventDefault();

    });

    

   



   




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

          var cnt                                 = $("#total_rows").val();
          var cnt_doc                             = $("#total_rows_doctor").val();

          var doctor_id_array                     =[];
          var visit_array                         =[];
          var doctor_note_array                   =[];
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var unit_price_array                    =[];
          var discount_array                      =[];
         
          var buy_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 quantityField   = $("#purchase_quantity_"+i).val();
              var unit_price      = $("#sell_price_"+i).val();
              var notes           = $("#sell_item_note_"+i).val();
              var discount        = $("#discount_"+i).val();
             
              

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

               
                

                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No');
                check_price[k]            = Checks('sell_price_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
               

                discount_array[k]         = discount;
               
                k++;
              }
          }

          var kk=1;

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

              var doctorID        = $("#doctor_id_fk_"+i).val();
              var visit           = $("#number_of_visit_"+i).val();
              var doctor_notes    = $("#plan_doctor_notes_"+i).val();
             
              

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

                doctor_id_array[kk]       = doctorID;
                visit_array[kk]           = visit;
                doctor_note_array[kk]     = doctor_notes;
               
                kk++;
              }
          }
          
          var plan_title                  = $("#plan_title").val();  
          var author                      = "";
          var plan_description            = $("#plan_description").val();
          var plan_start_date             = $("#plan_start_date").val();
          
          var plan_end_date               = $("#plan_end_date").val();
          var doctor_id_fk                = $("#doctor_id_fk").val();
          var team_leader_id_fk           = $("#team_leader_id_fk").val();

          var plan_note                   = $("#plan_note").val();
          var city_id_fk                  = $("#city_id_fk").val();
          var zone_id_fk                  = $("#zone_id_fk").val();
          


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

         
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkprice  = true;
          var checkheight  = true;
          var checkwidth  = true;
          var checkcolor  = 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 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_plan.php",
                type:"POST",
                dataType: "JSON",
                

                data : {plan_title                :plan_title,
                        author                    :author,
                        plan_description          :plan_description,
                        plan_start_date           :plan_start_date,
                        plan_end_date             :plan_end_date,
                        doctor_id_fk              :doctor_id_fk,
                        team_leader_id_fk         :team_leader_id_fk,
                        plan_note                 :plan_note,
                        zone_id_fk                :zone_id_fk,
                        city_id_fk                :city_id_fk,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_price                :unit_price_array,
                        sell_item_note            :notes_array,
                        discount_array            :discount_array,
                        
                        doctor_id                 :doctor_id_array,
                        visit                     :visit_array,
                        doctor_note               :doctor_note_array,
                        
                        type                      :'create'}
            
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    noty({
                              width: 200,
                              text: Translation(res.data),
                              type: 'success',
                              dismissQueue: true,
                              timeout: 2000,
                              layout: 'topRight',
                              callback: {
                                        onShow: function() {

                                        },
                                        afterShow: function() {
                                           show_invoice(res.id,'Print');
                                        },
                                        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) {
                $("#submit_add_btn").attr('disabled',false);

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

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

    });




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

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

          var cnt                                 = $("#edit_total_rows").val();
          var cnt_doc                             = $("#edit_total_rows_doctor").val();


  
          
          var doctor_id_array                     =[];
          var visit_array                         =[];
          var doctor_note_array                   =[];
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var unit_price_array                    =[];
          var discount_array                      =[];
         
          var buy_price_array                     =[];
          var notes_array                         =[];
          
          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];



          var k=1;

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

              var productID       = $("#edit_product_id_fk_"+i).val();
              var quantityField   = $("#edit_purchase_quantity_"+i).val();
              var unit_price      = $("#edit_sell_price_"+i).val();
              var notes           = $("#edit_sell_item_note_"+i).val();
              var discount        = $("#edit_discount_"+i).val();
             
              

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

               
                

                check_products[k]         = Checks('edit_product_id_fk_'+i);
                check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No');
                check_price[k]            = Checks('edit_sell_price_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
               

                discount_array[k]         = discount;
               
                k++;
              }
          }


          var kk=1;

          for(var i =0; i <= cnt_doc; i++){

              var doctorID        = $("#edit_doctor_id_fk_"+i).val();
              var visit           = $("#edit_number_of_visit_"+i).val();
              var doctor_notes    = $("#edit_plan_doctor_notes_"+i).val();
             
              

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

                doctor_id_array[kk]       = doctorID;
                visit_array[kk]           = visit;
                doctor_note_array[kk]     = doctor_notes;
               
                kk++;
              }
          }
          
          var plan_title                  = $("#edit_plan_title").val();  
          var author                      = "";
          var plan_description            = $("#edit_plan_description").val();
          var plan_start_date             = $("#edit_plan_start_date").val();
          
          var plan_end_date               = $("#edit_plan_end_date").val();
          var doctor_id_fk                = $("#edit_doctor_id_fk").val();
          var team_leader_id_fk           = $("#edit_team_leader_id_fk").val();

          var plan_note                   = $("#edit_plan_note").val();
          var city_id_fk                  = $("#edit_city_id_fk").val();
          var zone_id_fk                  = $("#edit_zone_id_fk").val();
          
         

          

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

         
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkprice  = true;
          var checkheight  = true;
          var checkwidth  = true;
          var checkcolor  = 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 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_edit_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_plan.php",
                type:"POST",
                dataType: "JSON",
                data : {plan_title                :plan_title,
                        author                    :author,
                        plan_description          :plan_description,
                        plan_start_date           :plan_start_date,
                        plan_end_date             :plan_end_date,
                        doctor_id_fk              :doctor_id_fk,
                        team_leader_id_fk         :team_leader_id_fk,
                        plan_note                 :plan_note,
                        zone_id_fk                :zone_id_fk,
                        city_id_fk                :city_id_fk,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_price                :unit_price_array,
                        sell_item_note            :notes_array,
                        discount_array            :discount_array,
                        
                        doctor_id                 :doctor_id_array,
                        visit                     :visit_array,
                        doctor_note               :doctor_note_array,
                        id                        :catId,
                        type                      :'update'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $("#edit_form_cont").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_edit_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_edit_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }else{
          noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }

         
    });


   
    


});







$(function() {

 
    
  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 10000000,
        step: 1,
        buttondown_class: "btn btn-xs",
        buttonup_class: "btn btn-xs"
    });

  var start_date = moment().add(5, 'days');

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

  $("#delivery_time").daterangepicker({ 
        singleDatePicker: true,
        startDate: start_date,
        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");


   


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

          if(PROFILE_TYPE < 3){
            d.city_id =CITY_ID ;
          }
        }
        },
        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": 11,
              "data": null,
              "render": function (data,type,row) {

                      var today = new Date();
                      var dd = today.getDate();
                      var mm = today.getMonth()+1; //January is 0!
                      var yyyy = today.getFullYear();

                      if(dd.toString().length <2){
                        dd = "0" + dd;
                      }


                      if(mm.toString().length <2){
                        mm = "0" + mm;
                      }

                      today =  yyyy + '-' + mm + '-' + dd;

                      var btns = '';

                      if(IS_VIEW==0){


                          if(PROFILE_TYPE == 2){

                          
                            if(row[2]==today){ // fully editing
                              btns = `<li class='text-primary-600'>
                                          <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                              <i class='icon-pencil7'></i>`+Translation('تعديل')+`
                                          </a>
                                      </li>

                                      `;

                            }else{ // deliveried to customer so they can't change anything
                              btns = ``;
                            }
                          }else if(PROFILE_TYPE > 2){

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

                                      <li class='text-danger-600'>
                                          <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                              <i class='icon-trash'></i>`+Translation('حذف')+`
                                          </a>
                                      </li>`;

                          }

                         

                      }

                     

                      return  `<ul class='icons-list '>
                                         
                                        <li class="dropdown">
                                          <a  class="dropdown-toggle" data-toggle="dropdown"  data-original-title='`+Translation('تفاصيل دفوعات الوصل')+` '>
                                            <i class="icon-menu9"></i>
                                          </a>

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

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

                                           
                                            `+btns+`
                                            

                                          </ul>
                                        </li>
                                        
                                    </ul>`;
                        }
          },


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


                        // return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='Show Invoice Details'>`+data+`</a>`;
                        return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض الوصل')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

            

            
           

            


           
            
            

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


                   if(data ==0 ){
                     status=  `<span class="label bg-green-600 btn-block ">`+Translation('Active')+`</span>`;
                   }else {
                     status=  `<span class="label bg-violet btn-block ">`+Translation('Expired')+`</span>`;
                   }

                   
                   return  status ;
                },
                "targets": 9
            }
            

           
        ],
        "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>`);   
         

          if(IS_VIEW==0){

            if(PROFILE_TYPE >= 2){

                $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      
                                      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>`);
            } 
          }else{
              $("#add-form-cont").addClass('collapse');

          }

             

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


});



