@extends('layouts.masterHome2')

@section('content')

    <br/>

   
 
     <div id="all">
     <div class="box-body">
     <div class="card-body">
    <div class="form-group col-md-3" style="text-align:right">
      <label> أسم العميل  </label>
      <select class="form-control select2 select2-hidden-accessible"   style="width: 100%;text-align:right" name="client_id" id="client_id" required>
        @foreach( $clients as $client ) 
        <option value="{{ $client->id }}"  >{{$client->name}} </option>
        @endforeach
      </select>
    </div>
    </div>
    </div>



    <a href="#" onclick="addInvoiceRow()"  class="btn" style="background-color:#2C4E71;color:#FFF;margin-right:30px;float:right">أضافة <i class="fa fa-plus" aria-hidden="true"></i>
 </a><br/><br/>
     

 
    <div class="card" style="margin:10px">
               
              <!-- /.card-header -->
              <div class="card-body">
                <table id="example" class="table table-bordered table-striped">
                  <thead>
                  
                 <tr >
                 <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px; width:120px"> اخر بيع    </th>
                 <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px;width:120px"> أجمالي الصنف    </th>
                  <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px; width:120px"> الكمية    </th>
                  <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px; width:120px"> السعر    </th>
                  <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px; width:120px"> المتاح    </th>
                  <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px;width:500px"> أسم المنتج    </th>

                 </tr>

                 </thead>
              <tbody>
                           
                 

                  
               
                </tbody>
                </table>
              </div>
              <!-- /.card-body -->           
    </div>  
 
            
    <div class="row" style="margin:10px">
            
            <div class="col-md-3" style="margin-top:0px;">
            
                <div class="card" style="height: 110px">
                  <div class="card-body">
                  
                    <div class="row">
                        <div class="col-md-4">
                          <div class="form-group">
                              <input type="number" value="0" min="0" style="width: 80px;" id="discount" name="discount" class="form-control"  placeholder="الخصم"  onchange="get_total_price()" required>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div class="form-group">
                              <select class="form-control"  id="discount_type"  style="width: 80px;" name="discount_type"  onchange="get_total_price()"  required>
                                <option value="num"  >num</option>
                                <option value="percent"  >%</option>                    
                              </select>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div class="form-group" style="text-align: end;">
                              <label for="exampleInputPassword1" >الخصم  </label>
                          </div>
                        </div>
                    </div> <!-- row -->
                    

                    
                    <div class="row">
                      <div class="col-md-8"> 
                        <div class="form-group" style="text-align:end">
                                <label for="exampleInputPassword1" id="total_table">0</label>
                        </div>
                      </div>
                      <div class="col-md-4" >
                        <div class="form-group" style="text-align:end">
                            <label for="exampleInputPassword1" >الأجمالي  </label>
                        </div>
                      </div>
                    </div>

                  </div>
                </div>
            </div>


            
          </div>
          


<!-- payment method -->

<div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title" style="float:right"> 
              
                  <a href="#" onclick="addPaymentMethod()"  class="btn" style="background-color:#2C4E71;color:#FFF;margin-right:30px;float:right">طريقة الدفع <i class="fa fa-plus" aria-hidden="true"></i>
                  </a>  
                </h3>
              </div>
              <!-- /.card-header -->
            <div class="card-body text-center"> 


              <table id="payment" class="table table-bordered table-striped">
                  <thead>
                      <tr>
                        <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px;width:70%"> اخري     </th>
                        <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px;width:100px"> المبلغ    </th>
                        <th style="text-align:center;vertical-align: middle;background-color:#2C4E71;color:#FFF;border-color:#0000003c;border-width: 2px;width:300px""> طريقة الدفع    </th>
                      </tr>
                  </thead>
                  <tbody></tbody>
              </table>



            </div>
            </div>


            <div class="card-footer">
                  <button onclick="submit()" class="btn btn-info" id="submit">Save</button>
            </div>  

            
</div>
<script>

var banks=[];
function submit (){

  document.getElementById("submit").disabled = true;
  var table1 = document.getElementById("example");
  var rows_num = table1.rows.length;
  let array = []; // initialize an empty array products
  
  let discount = document.getElementById('discount').value;
  let discount_type = document.getElementById('discount_type').value;
  let client_id = document.getElementById('client_id').value;
  let total_table = document.getElementById('total_table').innerHTML;
  let client = {
    "discount":discount,
    "discount_type":discount_type,
    "client_id":client_id,
    "total_price":total_table
  };
 
  
  var client_string = JSON.stringify(client);

  for (let i = 1; i < rows_num; i++) {
    var product = JSON.parse (document.getElementById('select'+i).value);
    let myObject = {};
    myObject.sell_store_id=product.id;
    var price = JSON.parse (document.getElementById('{"price":'+i+'}').value);
    myObject.price=price;
    var quantity = JSON.parse (document.getElementById('{"quantity":'+i+'}').value);
    myObject.quantity=quantity;
    array.push(myObject); 

    var store_aviliable = JSON.parse (document.getElementById("store_aviliable"+i).innerHTML);
    if(store_aviliable < quantity ) {
      alert ( " NO Enough Quanity in Store");
      return 0;
    }
    
  }

  if (array.length == 0) {
        alert("Empty List Of Products!");
        return 0;
    }

  
  var list = JSON.stringify(array);
 
  var paytable = document.getElementById("payment");
  var pay_rows_num = paytable.rows.length;
  let payarray = []; // initialize an empty array

  for (let i = 1; i < pay_rows_num; i++) {
    
    let myObject = {};

    var  select_ = document.getElementById('payselect'+i).value; // 
    var payselect_row  = JSON.parse(select_);

    myObject.safe_account_id= payselect_row.id  ;
    myObject.payment_method_id = payselect_row.payment_method.id;
    myObject.payment_method_name = payselect_row.payment_method.name;

    var payamount = document.getElementById('payamount'+i).value;
    myObject.payamount=payamount;

    var cheqserial_ = document.getElementById('cheqserial_'+i);
    if (JSON.stringify(cheqserial_) != "null") {
      if (cheqserial_.value != "") {
        myObject.cheqserial_=cheqserial_.value;
      }else{
        myObject.cheqserial_="111";
      }
    } else {
      myObject.cheqserial_="";
    }

    var cheqdate_ = document.getElementById('cheqdate_'+i);
    if (JSON.stringify(cheqdate_) != "null") {
      myObject.cheqdate_=cheqdate_.value;
    } else {
      myObject.cheqdate_="";
    }


    var cheqbank_ = document.getElementById('cheqbank_'+i);
    if (JSON.stringify(cheqbank_) != "null") {
      myObject.cheqbank_=cheqbank_.value;
    } else {
      myObject.cheqbank_="";
    }


    payarray.push(myObject); 
  }


  if (payarray.length == 0) {
        alert("Empty List Of Payment Methods!");
        //return 0;
    }

  console.log(payarray);
  var pay_list = JSON.stringify(payarray);

  
  $.ajax({
  type : 'GET',
  url : 'index/create/'+ list +'/'+pay_list+'/'+client_string,
  /*data : {
    '_token' : $('meta[name="csrf-token"]').attr('content')
  },
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },*/

  success : function(data) {
    
   //console.log("Work fine")
   //console.log(data.list);
   //console.log(data.pay_list);
   //console.log(data.client);

   if( data.state == 200){
    alert("New Invoice Created Successfully ");
    var all= document.getElementById('all');
    all.style.display = 'none';           // Hide
    
    var invoice_id=data.invoice_id;
    var url = '{{ url("/invoice/details", "id") }}';
        url = url.replace('id', invoice_id);
    window.location.replace(url );


   }
      
  },
  error : function(request, status, error) {
    console.log(error);
  }
});

}

function get_price(select) {
  const sell_store = JSON.parse(select.value);
  document.getElementById('{"price":'+sell_store.rowIndex+'}').value=sell_store.unit_price;
  var quantity = document.getElementById('{"quantity":'+sell_store.rowIndex+'}').value;
  document.getElementById('{"quantity":'+sell_store.rowIndex+'}').max=sell_store.quantity;
  document.getElementById('{"totalrow":'+sell_store.rowIndex+'}').innerHTML=sell_store.unit_price*quantity;
 
  document.getElementById("store_aviliable"+sell_store.rowIndex).innerHTML=sell_store.quantity;
  document.getElementById("last_sell"+sell_store.rowIndex).innerHTML=sell_store.last_sell_price;


  

  get_total_price();
}

function quantity_change (quantity_text){
  var obj = JSON.parse(quantity_text.id);
  // {"quantity:1"}  // 1==> rowindex 
  var rowIndex = obj.quantity;
  var price = document.getElementById('{"price":'+rowIndex+'}').value;
  var quantity = document.getElementById('{"quantity":'+rowIndex+'}').value;
  document.getElementById('{"totalrow":'+rowIndex+'}').innerHTML=price*quantity;
 
  get_total_price();
}

function price_change (price_text){
  var obj = JSON.parse(price_text.id);
  // {"quantity:1"}  // 1==> rowindex 
  var rowIndex = obj.price;
  var price = document.getElementById('{"price":'+rowIndex+'}').value;
  var quantity = document.getElementById('{"quantity":'+rowIndex+'}').value;
  document.getElementById('{"totalrow":'+rowIndex+'}').innerHTML=price*quantity;
  
  get_total_price();
}

function get_total_price (){
  var table = document.getElementById("example");
  var rows_num = table.rows.length;
  var total_price = 0;
  for (let i = 1; i < rows_num; i++) {
    var total_row = document.getElementById('{"totalrow":'+i+'}').innerHTML;
    total_price = total_price + (total_row*1)   
  }
   
  var discount = document.getElementById('discount').value;
  var discount_type = document.getElementById('discount_type').value;

   if ( discount_type == "num" ){
    document.getElementById('total_table').innerHTML = total_price - (discount*1);
    total_price = total_price - (discount*1);
  }else if ( discount_type == "percent" ){
    document.getElementById('total_table').innerHTML = total_price - ( total_price*discount/100);
    total_price = total_price - ( total_price*discount/100);
  }

}


/*function delete_row (button){
  var row_index = button.id;
  document.getElementById("example").deleteRow(row_index);
  get_total_price();
}
*/
function addInvoiceRow() {
  var table = document.getElementById("example");
  var row = table.insertRow();
  /*var total_row = row.insertCell(0);
  var quantity = row.insertCell(1);
  var price = row.insertCell(2);
  var sell_store = row.insertCell(3);
  */

  var last_sell = row.insertCell(0);
  var total_row = row.insertCell(1);
  var quantity = row.insertCell(2);
  var price = row.insertCell(3);
  var store_aviliable = row.insertCell(4);
  var sell_store = row.insertCell(5);
 // var delete_ = row.insertCell(6);

  ////////////////////delete//////////////////////////////////////
 /* var delete_button = document.createElement('button');
  delete_button.textContent = 'X';
  delete_button.id = row.rowIndex;
  delete_button.style.backgroundColor="Tomato";
  delete_button.onclick = function(){ delete_row(this) } ;
  delete_.appendChild(delete_button);
  */

  ////////////////last_sell///////////////////////////////////
var last_sell_text = document.createElement("span");
last_sell_text.id = "last_sell"+row.rowIndex;
last_sell.style.fontSize="18px";
last_sell.style.fontWeight = 'bold';
last_sell.style.textAlign = "center";
last_sell.appendChild(last_sell_text);
////////////////store_aviliable/////////////////////////////////////////
var store_aviliable_text = document.createElement("span");
store_aviliable_text.id = "store_aviliable"+row.rowIndex;
store_aviliable.style.fontSize="18px";
store_aviliable.style.fontWeight = 'bold';
store_aviliable.style.textAlign = "center";
store_aviliable.appendChild(store_aviliable_text);

/////////// total row /////////////////////////////////////////////
   
var total_row_text = document.createElement("span");
total_row_text.id = '{"totalrow":'+row.rowIndex+'}';
total_row.style.fontSize="18px";
total_row.style.fontWeight = 'bold';
total_row.style.textAlign = "center";
total_row.appendChild(total_row_text);

/////////// select input //////////////////////////////
      var selectList = document.createElement("select");
      selectList.id = "select"+row.rowIndex;
      selectList.style.width = "100%";
      selectList.style.height = "45px";
      selectList.onchange= function(){ get_price(this) } ;
      selectList.classList.add('select2');
      sell_store.appendChild(selectList);

//////////// quantity input ///////////////////////////
  var quantity_text = document.createElement("INPUT");
  quantity_text.setAttribute("type", "number");
  quantity_text.style.textAlign = "center";
  quantity_text.style.width = "100px";
  quantity_text.style.height = "35px";
  quantity_text.id = '{"quantity":'+row.rowIndex+'}';
  quantity_text.value = 1;
  quantity_text.onchange= function(){ quantity_change(this) } ;
  quantity.appendChild(quantity_text);

//////////////////////////////////////////////////

//////////// price input ///////////////////////////
    var price_text = document.createElement("INPUT");
    price_text.setAttribute("type", "number");
    price_text.style.textAlign = "center";
    price_text.style.width = "100px";
    price_text.style.height = "35px";
    price_text.id = '{"price":'+row.rowIndex+'}';
    price_text.onchange= function(){ price_change(this) } ;
    price.appendChild(price_text);
//////////////////////////////////////////////////



$.ajax({
  type : 'GET',
  url : 'index/get_sell_stores',
  /*data : {
    '_token' : $('meta[name="csrf-token"]').attr('content')
  },
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },*/
  
  success : function(data) {
    
      // row.rowIndex ==> index of row 

			var sell_stores = data.sell_stores ;
			//console.log(sell_stores[0]);
      

      //Create and append the options
      for (var i = 0; i < sell_stores.length; i++) {
          var option = document.createElement("option");
          sell_stores[i].rowIndex=row.rowIndex;
          option.value = JSON.stringify(sell_stores[i]);
          option.text =  sell_stores[i]["store"]["sell_name"];
          selectList.appendChild(option);
      }

      get_price(selectList[0]);
      
  },
  error : function(request, status, error) {
    console.log(error);
  }
});


$('.select2').select2();

}

//-----------------------------Payment Method------------------------------------
//-------------------------------------------------------------------------------




function check_method(select){
 
  const method = JSON.parse(select.value);
  var method_name = method.payment_method.name;
  var rowindex = method.rowIndex;

  var id = '{"cell":0,"row":'+rowindex+'}';

  var another = document.getElementById(id);

if (method_name == "شيك" || method_name=="ايداع بنكي") {

  another.innerHTML="";

  var cheq_serial_text = document.createElement("INPUT");
  cheq_serial_text.setAttribute("type", "number");
  cheq_serial_text.style.textAlign = "center";
  cheq_serial_text.style.width = "200px";
  cheq_serial_text.style.height = "35px";
  cheq_serial_text.style.margin = "0px 10px 0px 10px";
  cheq_serial_text.min = "0";
  cheq_serial_text.id = "cheqserial_"+method.rowIndex;
  if ( method_name == "شيك"){cheq_serial_text.placeholder="رقم الشيك";}
  if ( method_name=="ايداع بنكي"){cheq_serial_text.placeholder="رقم الايداع";}


  var cheq_date_text = document.createElement("INPUT");
  cheq_date_text.setAttribute("type", "date");
  cheq_date_text.style.textAlign = "center";
  cheq_date_text.style.width = "200px";
  cheq_date_text.style.height = "35px";
  cheq_date_text.min = "0";
  cheq_date_text.style.margin = "0px 10px 0px 10px";
  cheq_date_text.id = "cheqdate_"+method.rowIndex;
  cheq_date_text.placeholder="تاريخ الصرف";



  
 
/*
  var cheq_bank_text = document.createElement("INPUT");
  cheq_bank_text.setAttribute("type", "text");
  cheq_bank_text.style.textAlign = "center";
  cheq_bank_text.style.width = "300px";
  cheq_bank_text.style.height = "35px";
  cheq_bank_text.min = "0";
  cheq_bank_text.style.margin = "0px 10px 0px 10px";
  cheq_bank_text.id = "cheqbank_"+method.rowIndex;
  cheq_bank_text.placeholder="مسحوب علي بنك";
*/

  var selectListbanks = document.createElement("select");
      selectListbanks.id = "cheqbank_"+method.rowIndex;
      selectListbanks.style.width = "300px";
      selectListbanks.style.height = "37px";
      

  for (var i = 0; i < banks.length; i++) {
          var o = document.createElement("option");
          o.value = JSON.stringify(banks[i]["id"]);
          o.text =  banks[i]["name"];
          selectListbanks.appendChild(o);
  }



 // another.appendChild(date_title);
  another.appendChild(cheq_date_text);
  
  


 //another.appendChild(bank_title);
 another.appendChild(selectListbanks);
 

  //another.appendChild(cheq_title);
 another.appendChild(cheq_serial_text);

  

  }else{
     another.innerHTML="";
  }

 
}


function addPaymentMethod() {
  var table = document.getElementById("payment");
  var row = table.insertRow();
  var another = row.insertCell(0);
  var amount = row.insertCell(1);
  var payment_method = row.insertCell(2);
  
 
/////////// another //////////////////////////////
  
      var another_text = document.createElement("span");
      another_text.id = '{"cell":0,"row":'+row.rowIndex+'}';
      another_text.style.fontSize="18px";
      another_text.style.fontWeight = 'bold';
      another_text.style.float = "right";
      another.appendChild(another_text);


/////////// select input //////////////////////////////
      var selectList = document.createElement("select");
      selectList.id = "payselect"+row.rowIndex;
      selectList.style.width = "100%";
      selectList.style.height = "45px";
      selectList.onchange= function(){ check_method(this) } ;
      payment_method.appendChild(selectList);

//////////// amount input ///////////////////////////////
  var amount_text = document.createElement("INPUT");
  amount_text.setAttribute("type", "number");
  amount_text.style.textAlign = "center";
  amount_text.style.width = "100px";
  amount_text.style.height = "35px";
  amount_text.min = "0";
  amount_text.id = "payamount"+row.rowIndex;
  amount_text.value = 0;
  //amount_text.onchange= function(){ quantity_change(this) } ;
  amount.appendChild(amount_text);
//////////////////////////////////////////////////////


$.ajax({
  type : 'GET',
  url : 'index/get_safe_accounts',
  /*data : {
    '_token' : $('meta[name="csrf-token"]').attr('content')
  },
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },*/
  
  success : function(data) {
    
      // row.rowIndex ==> index of row 

			var accounts = data.accounts ;
			//console.log(sell_stores[0]);
      
      banks=data.banks;

      //Create and append the options
      for (var i = 0; i < accounts.length; i++) {
          var option = document.createElement("option");
          accounts[i].rowIndex=row.rowIndex;
          option.value = JSON.stringify(accounts[i]);
          option.text =  accounts[i]["payment_method"]["name"];
          selectList.appendChild(option);
      }

       
      
  },
  error : function(request, status, error) {
    console.log(error);
  }
});
}

 
//-------------------------------------------------------------------------------




</script>
@endsection
