@extends('layout')
@section('title','Inventaire magasin ')
@section('content')
	@if (session('status'))
            <div class="alert alert-warning" style="font-size: 15px; background-color: #328039; color: white">
                <i class="fa fa-check"></i> &nbsp; {{ session('status') }}
            </div>
            @endif

            @if (session('error'))
            <div class="alert alert-danger" style="font-size: 15px; background-color: #fb5757; color: white">
                <i class="ti-na"></i> {{ session('error') }}
            </div>
            @endif
            @if ($errors->any())
            <div class="alert alert-danger" style="font-size: 15px; background-color: #fb5757; color: white">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li> <i class="ti-na"></i> {{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif

    <div class="container mt-3">
	    <div class="row">
	     	<div class="col-md4"></div>
			<div class="col-md-8">
				<input type="text" list="searchi keyword" class="form-control" name="search" id="search" autofocus>
				<datalist id="searchi keyword">
				@foreach($produit as $p)
				@php
				$v = DB::table('stock_magasin')->where('produit_id', $p->id)->first();
				if ($v){
					$st = DB::table('stock_magasin')->where('produit_id', $p->id)->orderBydesc('id')->take(1)->first()->apres;
				}else{
					$st=0;
				}
				@endphp
					<option value="{{ $p->desi}}">{{ $p->desi}} | Stock : {{$st}}</option>
					@endforeach
				</datalist>
			</div>
		</div>
	</div>

	<form action="{{ route('inventairemagasinPost') }}" method="POST" id="sell-form">
		{{csrf_field()}}
		<div class="container">
			
			<div class="row mt-2">
				<div class="card col-md-8">
					<table class="table">
						<tr>
							<th>Produit</th>
							<th>Qté</th>
							<th>P.Vente</th>
							<th>P.Revient</th>
							<th></th>
						</tr>
						<tbody id="item">
						</tbody>
					</table>
				</div>

				<div class="col-md-4">
					<div class="card">
						<div class="card-body">
							<div><font color="#000"><b>Boutique  <font color="red">*</font></b></font>
								<select  class="form-control select2" name="magasin">
                        <option value="">Sélectionner une boutique</option>
						   @foreach($magasin as $magasins)
							<option value="{{$magasins->id}}">{{DB::table('magasin')->where('id', $magasins->id)->first()->nom}}</option>
							@endforeach
                      </select>
							</div>
							</div>
							<div class="card-footer" style="background-color: #FAFAD2;border-radius: 10px">
								<div>
									<br>
									<button type="button" class="btn btn-success" onclick="submitForm()" style="width: 100%;font-weight: 800;font-size: 16px"><i class="fa fa-save"></i> Enregistrer</button>
								</div>
							</div>
							
					</div>	
					
				</div>
			</div>
		</div>
	</form>

<div class="section-body">
    <div class="row">
        <div class="col-12">
            <div class="card">
                  <div class="card-header">
                    <h4>Liste inventaires</h4>
                  </div>
                  <div class="card-body">
                    <div class="table-responsive">
                      <table class="table table-striped" id="table-1">
                        <thead>
                          <tr>
                            <th class="text-center"> N° </th>
                            <th class="text-center"> Réf. </th>
							<th class="text-center">Magasin</th>
							<th class="text-center">Etat</th>
                            <th class="text-center">Date</th>
                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody>
						@foreach($inventaire as $inventaires)
                          <tr>
							<td style="text-align:center;">{{$loop->iteration}}</td>
							<td style="text-align:center;">{{$inventaires->reference}}</td>
							<td style="text-align:center;">{{DB::table('magasin')->where('id', $inventaires->magasin_id)->first()->nom}}</td>
							
							@php
							
							$dd = implode('/', array_reverse(explode('-', $inventaires->date)));
							@endphp
							<td style="text-align:center;">
								@if( $inventaires->etat == "En cours")
								<div class="badge badge-warning badge-shadow">{{$inventaires->etat}}</div>
								@elseif( $inventaires->etat == "Validée")
								<div class="badge badge-success badge-shadow">{{$inventaires->etat}}</div>
								@else
								<div class="badge badge-danger badge-shadow">{{$inventaires->etat}}</div>
								@endif
							</td>
							<td style="text-align:center;">{{$dd}} </td>
						
							<td class="align-middle">
							@if( $inventaires->etat == "En cours")
							<a type="button" href="#" data-id="{{$inventaires->id}}" data-toggle="tooltip" data-placement="bottom" title="Supprimer" class="btn btn-icon btn-danger data-supprimer"><i class="fas fa-trash"></i></a>
							<a type="button" href="#" data-id="{{$inventaires->id}}" data-toggle="tooltip" data-placement="bottom" title="Valider" class="btn btn-icon btn-success data-valider"><i class="fas fa-check"></i></a>
							<!--<a type="button" href="{{route('modifier_inventaire_magasin',['id'=>$inventaires->id])}}" data-toggle="tooltip" data-placement="bottom" title="Modifier" class="btn btn-icon btn-info"><i class="fas fa-edit"></i></a>-->
							@endif
							<a type="button" target="_blank" href="{{route('fichemagasin',['id'=>$inventaires->id])}}" class="btn btn-icon btn-warning"><i class="fas fa-print"></i></a>	
							<a type="button" href="{{route('detail_magasin',['id'=>$inventaires->id])}}" data-toggle="tooltip" data-placement="bottom" title="Details" class="btn btn-icon btn-info"><i class="fas fa-info"></i></a>
							
							</td>
                          </tr>
						  @endforeach
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
        </div>
    </div>
</div>
</div>
</div>
<div class="modal fade" id="Supprimermodal" >
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Suppression</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                Voulez-vous supprimer définitivement cet inventaire ?
              </div>
              <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="delete">
                
              </div>
            </div>
          </div>
        </div>
		<div class="modal fade" id="Validermodal" >
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Valider l'inventaire</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="progress progress-lg" id="pg" style="display:none">
					<div class="progress-bar progress-bar-warning progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%;height:50px">
						<br>Traitement en cours, veuillez patienter...
					</div>
				</div>
                <p id="nn" style="text-align:center">
                Voulez-vous valider cet inventaire ? <font color="red">Veuillez bien vérifier les quantités saisies avant
				la validation car cette action est irréversible</font>
                </p>
                
              </div>
              <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="valider">
                
              </div>
            </div>
          </div>
        </div>
	@push('scripts')
	<script>
	function myFunction() {
		$('#bregister').hide();
		$('#bregister2').hide();
		$('#bregister3').hide();
		$('#pg').show();
		$('#mm').hide();
		$('#nn').hide();
		//$("#nn").attr("value", "Traitement en cours, veuillez patienter...");
		//document.getElementById("nn").value = "Traitement en cours, veuillez patienter...";
		//document.getElementById("nn").innerHTML = "Traitement en cours, veuillez patienter...";
	}
	</script>
	     
	   
	   <script>
        $(".data-supprimer").on('click', function () {
                var id=$(this).data('id');
                $.get(location.origin+'/es/Inventaire_magasin/'+id, function (data) {
                  var html = `
            <button type="button" class=" btn btn-danger" data-dismiss="modal">Non</button>
                      <form action="{{route('SupprimerInventairemagasinPost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+data.invent.id+`" name="id" >
                      <button type="submit" class="btn btn-success">Oui</button>

            </form>`
            ;
            $('#delete').html('').append(html);
          })
          $('#Supprimermodal').modal();
        });
    </script>
	<script>
        $(".data-valider").on('click', function () {
                var id=$(this).data('id');
                $.get(location.origin+'/es/Inventaire_magasin/'+id, function (data) {
                  var html = `
                      <form action="{{route('ValiderInventairemagasinPost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+data.invent.id+`" name="id" >
                      <button type="submit" class="btn btn-success" onclick="myFunction()" id="bregister">Oui</button>
					  <button type="button" class=" btn btn-danger" data-dismiss="modal" id="bregister2">Non</button>

            </form>`
            ;
            $('#valider').html('').append(html);
          })
          $('#Validermodal').modal();
        });
    </script>
		<script type="text/javascript">
			var iteration  = 0;
			var appendTr='';
			$("input[name=search]").on('change', function (event) {
				event.stopImmediatePropagation();
				var barcode = $(this).val()
				var data = {search : barcode};
				data._token = "{{ csrf_token() }}";
				
				$.post("{{ route('vente-code2') }}", data, function (result) {
					result = JSON.parse(result);
					if(result != undefined && result != null &&  result != ""){
						appendTr = `
							<tr style="margin-bottom:-5px">
								<td>
									${result.designation}
									<input type="hidden" class="form-control" value="${result.id}" name="item[${iteration}][]">
								</td>
								<td>
									<input type="number" class="form-control" value="1" min="1" name="item[${iteration}][]">
								</td>
								<td>
									<input type="number" class="form-control" value="${result.prix_detail}"  name="item[${iteration}][]">
								</td>
								<td>
									<input type="number" class="form-control" value="${result.pr}"  name="item[${iteration}][]">
								</td>
								<td>
									<input type="hidden"  name="item[${iteration}][]">
									<span></span>
								</td>
								<td>
									<button class="btn btn-danger" onclick="removeTr(this);onMouseMove();"><i class="fa fa-times"></i></button>
								</td>
							</tr>
						`;

						$("#item").append(appendTr);
						onMouseMove();

						$("input[name=search]").val('');
						document.getElementById('search').focus();

						iteration++;
					}


					
				});
			});


			$("body").on('click', function () {
				onMouseMove();
			})

			function onMouseMove() {

				var td = null;
				var qt = 0;
				var pu = 0;
				//var montant = 0;
				//var total = 0;
				//var remise = Number($("input[name=remise]").val());

				$("#item>tr").each(function (index, element) {
					td = $(element).find('td');
					qt = Number(td.eq(1).find('input').eq(0).val());
					pu = Number(td.eq(2).find('input').eq(0).val());

					//montant = qt*pu;
					//total +=montant;

					//td.eq(3).find('input').eq(0).val(montant);
					//td.eq(3).find('span').eq(0).text(montant);
				});



				//$("#total").text(total - remise);
			}



			function removeTr(td){
				$(td).parent().parent().remove();
			}

			function submitForm(){
				if($("#item>tr").length > 0 && $('select[name="magasin"]').val() != ''){
					document.getElementById('sell-form').submit();
				}
				
			}


		</script>

	@endpush
@endsection