<?php
require_once __DIR__ . '/../magic/auth.php';

$auth = bdr_require_privilege(43, '../logout.php');
$user = $auth['user_id'];
$father = $auth['user_id'];
$branch = $auth['branch'];
$conn = $auth['conn'];
$db = $auth['conn'];

$mat_in_id = $_REQUEST['id'];
$element_id = 43;

$sitQuery = $db->prepare('SELECT material_supp.mat_name , material_in.invoice_no , material_in.mat_supp_id , material_in.mat_in_id , material_in.mat_invoice_date, material_in.store_id , material_in.net_cost , material_in.comm , material_in.date_in , material_in.vat , material_in.vat_out
			 							FROM material_in , material_supp WHERE material_in.mat_supp_id = material_supp.mat_supp_id
										AND material_in.mat_in_id = ? ');
			$sitQuery->bindParam(1,$mat_in_id);
			$sitQuery->execute();
		      if($sitQuery->rowCount()>0)
			{ $row = $sitQuery->fetch(PDO::FETCH_ASSOC);
						     $store_id   = $row["store_id"];  $vat   = $row["vat"];
					}
			 ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="robots" content="index,follow">
	<meta name="author" content="سامح دياب">
	<link rel="icon" href="../images/perfect.ico">
	<title>تحديث فاتورة</title>
	<link rel="stylesheet" href="../dist/css/bootstrap.css"/>
	<link rel="stylesheet" href="../css/font-awesome.min.css">
	<link rel="stylesheet" href="../hj2/humanity.calendars.picker.css">
	<link rel="stylesheet" href="../css/myCar.css"/>
	<script src="../js/jquery.js"></script>
	<script src="../js/jquery.autocomplete.js"></script>
	<script src="../dist/js/umd/popper.min.js"></script>
	<script src="../dist/js/bootstrap.js"></script>
	<script src="../hj2/jquery.plugin.js"></script>
	<script src="../hj2/jquery.calendars.js"></script>
	<script src="../hj2/jquery.calendars.plus.js"></script>
	<script src="../hj2/jquery.calendars.picker.js"></script>
	<script src="../hj2/jquery.calendars.ummalqura.js"></script>
</head>
    <body style="background-color:#3D3D3D;">
			<div class="container-fluid fixed-top" style="background-color:black;padding:10px;">
<h6 style="color:green; font-size:12pt;">شاشة تحديث فاتورة</h6>
</div>
<br /><br /> <br /><br />
<div class="container-fluid">
	<div id="msg"></div>
<form method="post" class="form-horizontal" id="new_mat_invoice" autocomplete="off">
    <div class="form-row">
        <input type="hidden" class="form-control" id="mat_in_idd" name="mat_in_idd" value="<?php echo $mat_in_id ; ?>" />
				<div class="col-1">
          <label for="invoice_no" class="control-label">رقم الفاتورة</label>
          <input type="text" class="form-control" id="invoice_no" name="invoice_no" value="<?php echo $row["invoice_no"] ; ?>"  placeholder="فاتورة البائع"/>
        </div>
				<div class="col-5"><label for="mat_supp_sr" class="control-label ">المورد</label>
          <input type="hidden" id="mat_supp_id" name="mat_supp_id" value="<?php echo $row["mat_supp_id"] ; ?>" />
            <input type="text" class="form-control" id="mat_supp_sr" name="mat_supp_sr" value="<?php echo $row["mat_name"] ; ?>" placeholder="بحث بالأسم"/>
      </div>
        <div class="col-1">
           <label for="mat_invoice_date" class="control-label">التاريخ</label>
          <input type="text" class="form-control" id="mat_invoice_date" name="mat_invoice_date" onchange="Gdate('mat_invoice_date')" value="<?php echo $row["mat_invoice_date"] ; ?>" placeholder="تاريخ الفاتورة"/>
          <script>
            $(function() {
              var calendar = $.calendars.instance('');
              $('#mat_invoice_date').calendarsPicker({calendar: calendar});
              });
          </script>
        </div>
        <div class="col-1">
        <label for="store_id" class="control-label ">المخزن</label>
         <select class="form-control" id="store_id" style="padding:3px;" name="store_id">
              <?php
              $sql2 =$db->prepare("SELECT store_id , store_name from store") ;
              $sql2->execute();
               if($sql2->rowCount()>0)
              {
                 while($ro = $sql2->fetch()){
                        $st_id   = $ro["store_id"];
                        $store_name = $ro["store_name"];
												if($st_id == $store_id){
													echo "<option selected value= $store_id >$store_name</option>";
												}else{
													echo "<option value= $store_id >$store_name</option>";
												}
                      }}
											?>
                    </select>
      </div>
  </div>
  <div class="form-row" style="margin-top:14px;">
      <div class="col-2">
        <label for="net_cost" class="control-label">اجمالي</label>
        <input type="text" class="form-control" id="net_cost" name="net_cost" value="<?php echo $row["net_cost"] ; ?>" placeholder="بعد الخصم"/>
      </div>
      <div class="col-1">
         <label for="vat_out" class="control-label ">الضريبة</label>
        <input type="number" onchange="vat_kind()" class="form-control" id="vat_out" name="vat_out" placeholder="VAT" value="<?php echo $row["vat_out"] ; ?>"/>
      </div>
      <div class="col-2">
      <label for="vat" class="control-label">نوع الضريبة</label>
      <select class="form-control" style="padding:3px;" id="vat" name="vat">
				<?php if($vat == 1)
					{echo '<option selected value="1" >ضريبية</option>
					<option value="2" >صفرية</option>
					<option value="3" >بدون ضريبة</option>';}
					else if($vat == 2){echo '<option value="1" >ضريبية</option>
					<option selected value="2" >صفرية</option>
					<option value="3" >بدون ضريبة</option>';}
					else{echo '<option value="1" >ضريبية</option>
					<option value="2" >صفرية</option>
					<option selected value="3" >بدون ضريبة</option>';}
				?>
      </select>
    </div>
    <div class="col-5">
       <label for="comm" class="control-label ">تعليق</label>
      <input type="text" class="form-control" id="comm" name="comm" placeholder="ملاحظات"value="<?php echo $row["comm"] ; ?>" />
    </div>
    <div class="col-2">
    <input style="float:right ;margin-top: 23px;" type="button" id="update_material_in" name="update_material_in" class="btn btn-info" value="تحديث بيانات "/>
  </div>
</div><!-- second row material invoice -->
</form>
<br />
    <form method="post" class="form-horizontal " id="new_invoice_line">
      <div class="form-row">
        <div class="col-10" id="line_msg">
      </div>
      </div>
			<div class="form-row">
				<input type="hidden" class="form-control" id="invoice_id" name="invoice_id" value="<?php echo $mat_in_id ; ?>"/>
				<div class="col-1">
					<label class="control-label">تحرير</label>
				</div>
					<div class="col-1">
						<label for="tot_price" class="control-label">إجمالي</label>
					</div>
					<div class="col-4">
						<label for="item_search" class="control-label">اسم القطعة</label>
					</div>
					<div class="col-1">
						<label for="qty" class="control-label">الكمية</label>
					</div>
					<div class="col-1">
						<label for="unit" class="control-label">الوحدة</label>
					</div>
					<div class="col-1">
						<label for="location" class="control-label">مكان التخزين</label>
					</div>
					<div class="col-3">
						<label for="comm" class="control-label">التعليق</label>
					</div>
			</div>
			<?php
			$sql3 =$db->prepare("SELECT items_line.line_id, items_line.mat_in_id , items_line.item_id , items_line.tot_price ,items_line.qty , items_line.unit ,  items_line.unit_price , items_line.location , items_line.comm , items_line.outt , items.item_name
														FROM items_line ,items WHERE items_line.item_id = items.item_id AND mat_in_id = ?") ;
			$sql3->bindParam(1,$mat_in_id) ;
			$sql3->execute();
			 if($sql3->rowCount()>0)
			{$html = '';
				 while($do = $sql3->fetch()){
					 $line_id   = $do["line_id"];
					 $html .= '<section class="form-row"><div class="col-1" ><input type="button" dd="'.$line_id.'" class="btn btn-danger btn-block btn-sm remove" value="حذف سجل"/></div>';
					 $html .= '<div class="col-1"><input type="number" class="form-control tot_price" name="tot_price[]" value="'.$do["tot_price"].'"/></div>';
					 $html .= '<div class="col-4"><input type="text" class="form-control item_search"  name="item_search[]" value="'.$do["item_name"].'" placeholder="البيان"/></div>';
					 $html .= '<div class="col-1"><input type="number" class="form-control qty" name = "qty[]"value="'.$do["qty"].'"/></div>';
					 $html .= '<div class="col-1"><input type="text" class="form-control unit" name="unit[]" value="'.$do["unit"].'"/></div>';
					 $html .= '<div class="col-1"><input type="text" class="form-control location" name="location[]" value="'.$do["location"].'" /></div>';
					 $html .= '<div class="col-3"><input type="text" class="form-control comm" name="comm[]" value="'.$do["comm"].'" /></div></section>';
							}
							echo $html ;
						}
			 ?>
			 <section>
      <div class="form-row">
        <div class="col-1">
          <input type="button" class="btn btn-success btn-block btn-sm add" value="أضافة سجل"/>
        </div>
          <div class="col-1">
            <input type="number" class="form-control tot_price" name="tot_price[]"/>
          </div>
          <div class="col-4">
            <input type="text" class="form-control item_search" name="item_search[]" placeholder="البيان"/>
          </div>
          <div class="col-1">
            <input type="number" class="form-control qty" name="qty[]" value="1.0"/>
          </div>
          <div class="col-1">
            <input type="text" class="form-control unit" name="unit[]" value="حبة"/>
          </div>
          <div class="col-1">
            <input type="text" class="form-control location"name="location[]" placeholder="في المخزن" />
          </div>
          <div class="col-3">
            <input type="text" class="form-control comm" name="comm[]" placeholder="ملاحظات"/>
          </div>
      </div></section>

  <section id="mass"></section>
  <div class="row" style="padding:2px;">
    <div class="col-6"></div>
		<?php
		$sql4 =$db->prepare("SELECT count(qty) as qty from item_line_out where line_in in (SELECT line_id	FROM items_line WHERE mat_in_id = ?)") ;
		$sql4->bindParam(1,$mat_in_id) ;
		$sql4->execute();
		 if($sql4->rowCount()>0){$so         = $sql4->fetch(PDO::FETCH_ASSOC);
						 $qty  = $so["qty"];
		 }
		 if($qty > 0){
			 echo "<br />";
			 echo "تم صرف عدد $qty من الفاتورة لذلك لا تسطيع تعديل الفاتورة";
		 }else{
			 echo '<div class="col-2">
	       <input type="button" id="add_line" name="add_line" class="btn btn-success btn-block" value="حفظ"/>
	     </div>';
		 }
		 ?>
  </div>
    </form>
<?php
$supp = array();
$sql =$db->prepare("SELECT mat_supp_id , mat_name from material_supp ORDER BY mat_name") ;
$sql->execute();
    $n=0;
    if($sql->rowCount()>0)
   {
      while($row = $sql->fetch()){
             $supp[$n] = array(
                           "value" => $row["mat_name"],
                           "data" => $row["mat_supp_id"]
                         );  $n++ ;
           } }
    else {  $supp[0]= 'لا يوجد '; }

        $output = array();
            $item_sr = $db->prepare("SELECT item_id , item_name FROM items");
            $item_sr->execute();
            $i=0;
            if($item_sr->rowCount()>0)
              {
                 while($row = $item_sr->fetch())
                 {
                     $output[$i] = array(
                                   "value" => $row["item_name"],
                                   "data" => $row["item_id"]
                                   );  $i++ ;
                   } }
            else {  $output[0]= 'لا يوجد '; }
        ?>
        </table>
          </div>
        </div><!-- end of avilable invoice items -->
      </div>
<script>
$(document).ready(function(){
  var arr  =  JSON.parse('<?php echo json_encode($output) ; ?>');
  var supp =  JSON.parse('<?php echo json_encode($supp) ; ?>');
  $('.item_search').autocomplete({
	 lookup: arr,
   maxHeight : 200,
   onSelect: function(suggestion) {
         }
})
$('#mat_supp_sr').autocomplete({
 lookup: supp,
 maxHeight : 200,
 onSelect: function(suggestion){
   $("#mat_supp_id").val(suggestion.data);
   // $('#add_material_in').attr("type","button");
 }
})
//end of add matrial invoice ajax code
$("#add_line").click(function(event){
event.preventDefault();
  var error = '';
  $('.tot_price').each(function(){
          var count = 1;
          if($(this).val() < 1)
          {
            // error += "<p> من فضلك راجع اجمالى السعر </p>";
						$(this).closest('section').remove();
            return false;
          }
          count = count + 1;
          });

$('.item_search').each(function(){
        var count = 1;
        if($(this).val() == '')
        {
        error += "<p> من فضلك راجع اسم القطعة </p>";
        return false;
        }
        count = count + 1;
        });

$('.qty').each(function(){
          var count = 1;
          if($(this).val() <= 0)
          {
            error += "<p>  من فضلك راجع الكمية </p>";
            return false;
          }
          count = count + 1;
          });
if(error == ''){
  $.ajax({
    url     : "new43line_in.php",
    method  : "POST",
    data    : $("#new_invoice_line").serialize(),
    success : function(inv){
       $("#line_msg").html(inv);
       $('#new_add').css("display","block");
      },error   :function(result){alert(result.statusText);}
  })}
  else{ $('#line_msg').html('<div class="alert alert-danger">'+error+'</div>');}
}); //end of add matrial invoice ajax code

function one_item(line_id){
  $.ajax({
  url:"wh/line_single.php",
  method:"POST",
  data:{line_id:line_id},
  dataType:"json",
  success:function(data)
  {
    $('#line_id').val(data.line_id);
    $('#invoic_id').val(data.mat_in_id);
    $('#tot_price').val(data.tot_price);
    $('#item_search').val(data.item_name);
    $('#qty').val(data.qty);
    $('#unit').val(data.unit);
    $('#unit_price').val(data.unit_price);
    $('#location').val(data.location);
    $('#comm').val(data.comm);
    $('#add_line').attr("type","hidden");
    $('#update_line').attr("type","button");
  }
});
};

$("#update_material_in").click(function(event){
  event.preventDefault();
  $.ajax({
    url     : "mat_in_update.php",
    method  : "POST",
    data    :$("#new_mat_invoice").serialize(),
    success : function(data){
    $("#msg").html(data);
  },
    error   :function(result){
      alert(result.statusText);
      }
  })
}); //end of update_branch ajax code ?act='update'

$(".add").click(function(event){
  event.preventDefault();
  var html = '';
      html += '<section class="form-row"><div class="col-1" ><input type="button" class="btn btn-danger btn-block btn-sm remove" value="حذف سجل"/></div>';
      html += '<div class="col-1"><input type="number" class="form-control tot_price" name="tot_price[]"/></div>';
      html += '<div class="col-4"><input type="text" class="form-control item_search"  name="item_search[]" placeholder="البيان"/></div>';
      html += '<div class="col-1"><input type="number" class="form-control qty" name = "qty[]" value="1.0"/></div>';
      html += '<div class="col-1"><input type="text" class="form-control unit" name="unit[]" value="حبة"/></div>';
      html += '<div class="col-1"><input type="text" class="form-control location" name="location[]" /></div>';
      html += '<div class="col-3"><input type="text" class="form-control comm" name="comm[]" /></div></section>';
  $('#mass').append(html);
  $('.item_search').autocomplete({
  lookup: arr,
  maxHeight : 200,
  onSelect: function(suggestion) {
       }
});
 });
 $(document).on('click', '.remove', function(){
  $(this).closest('section').remove();
 });

});//end of document ready
function uint_cost(){
  var tot = $("#tot_price").val();
  var qt = $("#qty").val();
  var a = tot / qt ;
  var unit_price = parseFloat(a.toFixed(2));
  $("#unit_price").val(unit_price);
}
function Gdate(ss){
  var date = $('#' + ss).val().split('/');
  var year = parseInt(date[2], 10);
    if (year < 100){ year = year + 2000 ;}
  var month = parseInt(date[1], 10);
  if(month > 12){month = 12 ;}else if(month < 1){month = 1 ;}
  var day = parseInt(date[0], 10);
  if(day > 31){day = 31 ;}else if(day < 1){day = 1 ;}
  $('#' + ss).val(year + "/" + month + "/" + day );
}
function vat_kind(){
  var vat_out = $('#vat_out').val();
  if(vat_out < 0){
    $('#vat_out').val(0);
  }
  if(vat_out > 0){
    $("#vat").val(1);
    if(vat_out < 5 ){$('#vat_out').val(5);vat_out = $('#vat_out').val();}
  }else{$("#vat").val(3);}
  if(vat_out == 15){ $("#vat_out").css( "background-color", "#42a5f5");}
					else 	if(vat_out == 5){ $("#vat_out").css( "background-color", "#ccffcc");}
          else { $("#vat_out").css( "background-color", "#ff8a80");}
}
</script>
