@extends('layout')
@section('title','Destockage')
@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">
				<datalist id="searchi keyword">
				@foreach($produit as $p)
				@php
				$dd = date('d/m/Y');
				$v = DB::table('stock_magasin')->where('produit_id', $p->id)->where('magasin_id', session('user')->magasin_id)->first();
				if ($v){
					$st = DB::table('stock_magasin')->where('produit_id', $p->id)->where('magasin_id', session('user')->magasin_id)->orderBydesc('id')->take(1)->first()->apres;
				}else{
					$st=0;
				}
				@endphp
					<option value="{{ $p->desi}}">{{ $p->barcode}}- {{ $p->desi}} | Stock : {{$st}}</option>
					@endforeach
				</datalist>
			</div>
		</div>
	</div>

	<form action="{{ route('destockagepost') }}" 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>PU</th>
							<th>Montant</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>Observations : </b></font>
								<input type="text" class="form-control" name="observations" required>
							</div>
							<div><font color="#000"><b>Date : </b></font>
								<input type="text" class="form-control" name="datet" id="champ_date2" required>
								<div id="calendarMain2"></div>
							</div>
							</div>
							<div class="card-footer" style="background-color: #FAFAD2;border-radius: 10px">
								<div style="font-weight: 800;font-size: 16px" hidden>Montant Total : <blink><b id="total" style="color: red"></b></blink></div>
								<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 la sortie</button>
								</div>
							</div>
							
					</div>	
					
				</div>
			</div>
		</div>
	</form>

<div class="container section-body">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4>Liste</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">Date</th>
                                    <th class="text-center">Lignes</th>
                                    <th class="text-center">Observations</th>
                                    <th class="text-center">Etat</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($destockage as $destockages)
                                <tr>
                                    <td style="text-align:center;">{{$loop->iteration}}</td>
                                    @php
                                    $dd = implode('/', array_reverse(explode('-', $destockages->date)));
                                    $lh3 = number_format($destockages->montant, 0, ' ', ' ');
                                    $ligne = DB::table('ligne_destockage')->where('destockage_id', $destockages->id)->get();
                                    @endphp
                                    <td style="text-align:center;">{{$dd}} </td>
                                    <td style="text-align:center;">
                                        <table class="table table-striped" id="table-1">
                                            <thead>
                                                <th>Produit</th>
                                                <th>Qté</th>
                                            </thead>
                                            <tbody>
                                                @foreach($ligne as $lignes)
                                                <tr>
                                                    <td>{{DB::table('produit_vendable')->where('id', $lignes->produit_id)->first()->designation}}</td>
                                                    <td>{{$lignes->qte}}</td>
                                                </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </td>
                                    <td style="text-align:center;">{{$destockages->observations}} </td>
                                    <td style="text-align:center;">
                                        @if( $destockages->etat == "En cours")
                                        <div class="badge badge-warning badge-shadow">{{$destockages->etat}}</div>
                                        @elseif( $destockages->etat == "Validée")
                                        <div class="badge badge-success badge-shadow">{{$destockages->etat}}</div>
                                        @else
                                        <div class="badge badge-danger badge-shadow">{{$destockages->etat}}</div>
                                        @endif
                                    </td>
                                    <td class="align-middle">
                                        @if( $destockages->etat == "En cours")
                                        <a type="button" href="#" data-toggle="tooltip" data-id="{{$destockages->id}}"
                                            data-placement="bottom" title="Valider"
                                            class="btn btn-icon btn-success data-valider"><i
                                                class="fas fa-check"></i></a>
                                        <a type="hidden" href="#" data-toggle="tooltip" data-id="{{$destockages->id}}"
                                            data-placement="bottom" title="Supprimer"
                                            class="btn btn-icon btn-danger data-supprimer"><i
                                                class="fas fa-trash"></i></a>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </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"></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 ? 
                </p>
                
              </div>
            <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="valider">

            </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 ?
            </div>
            <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="delete">

            </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 + '/he/es/Destockage/' + id, function (data) {
            var html = `
            <button type="button" class=" btn btn-danger" data-dismiss="modal">Non</button>
                      <form action="{{route('Supprimerdestockagepost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+ data.destockage.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 + '/he/es/Destockage/' + id, function (data) {
            var html = `
			<button type="button" class=" btn btn-danger" data-dismiss="modal" id="bregister2">Non</button>
            <form action="{{route('Validerdestockagepost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+ data.destockage.id + `" name="id" >
                      </div>
					 
					  <button type="submit" class="btn btn-success" onclick="myFunction()" id="bregister">Oui</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>
									<span style="font-size:12px">${result.designation}</span> <span style="font-size:11px"></span>
									<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}][]" autofocus>
								</td>
								<td>
									<input type="number" class="form-control" value="${result.prix_detail}"  name="item[${iteration}][]" readOnly>
								</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 && $("input[name=datet]").val() != '' && $("input[name=observations]").val() != ''){
					document.getElementById('sell-form').submit();
				}
				
			}


		</script>

	@endpush
@endsection