@extends('layout')
@section('title','Proforma ')
@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->barcode}}-{{ $p->desi}} | Stock : {{$st}}</option>
					@endforeach
				</datalist>
			</div>
		</div>
	</div>

	<form action="{{ route('proformaPost') }}" 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>Quantité</th>
							<th>Prix Unitaire</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>Prix : </b></font>
								<select class="form-control select2" name="typevente">
                                        <option value="Détail">Détail</option>
                                        <option value="Semigros">Semigros</option>
                                        <option value="Gros">Gros</option>
                                    </select>
							</div>
							<div><font color="#000"><b>Remise : </b></font>
								<input type="number" class="form-control" value="0" name="remise">
							</div>
							<div><font color="#000"><b>Nom client : </b></font>
								<select class="form-control select2" name="client_id" required>
										<option value=""> </option>
                                        @foreach($client as $clients)
                                        <option value="{{$clients->id}}">{{$clients->noms}}</option>
                                        @endforeach
                                </select>
							</div>
							<div><font color="#000"><b>Taxes : </b></font>
								<select class="form-control select2" name="taxes">
                                        <option value="Non">Non</option>
                                        <option value="Oui">Oui</option>
                                    </select>
							</div>
							</div>
							<div class="card-footer" style="background-color: #FAFAD2;border-radius: 10px">
								<div style="font-weight: 800;font-size: 16px">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 Proforma</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>Proforma récents</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped" id="table-1">
                            <thead>
                                <tr>
                                    <th class="text-center"> ID </th>
                                    <th class="text-center"> N° </th>
                                    <th class="text-center"> Client </th>
                                    <th class="text-center">Montant HT</th>
                                    <th class="text-center">Montant Rem.</th>
                                    <th class="text-center">Montant TTC</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($ventes as $vente)
                                <tr>
                                    <td style="text-align:center;">{{$loop->iteration}}</td>
                                    <td style="text-align:center;">D{{$vente->numero}}</td>
                                    <td style="text-align:center;">{{DB::table('client_externe')->where('id',$vente->client_id)->first()->noms}}</td>
                                    @php
                                    $dd = implode('/', array_reverse(explode('-', $vente->date)));
                                    $mht = number_format($vente->montant_ht, 0, ' ', ' ');
                                    $total_taxe2 = number_format($vente->total_taux, 0, ' ', ' ');
                                    $lh3 = number_format($vente->montant, 0, ' ', ' ');

                                    @endphp
                                    <td style="text-align:center;">{{$mht}} F</td>
                                    <td style="text-align:center;">{{$vente->montant_remise}} F</td>
                                    <td style="text-align:center;">{{$lh3}} F</td>
                                    <td class="align-middle">
                                        <a type="button" href="{{route('ligne-proforma',['id'=>$vente->id])}}"
                                            data-toggle="tooltip" data-placement="bottom" title="Détails"
                                            class="btn btn-icon btn-info"><i class="fas fa-info"></i></a>
                                        <a type="button" target="_blank"
                                            href="{{route('facture-proforma',['id'=>$vente->id])}}" data-placement="bottom" data-toggle="tooltip"
										title="Imprimer" 
                                            class="btn btn-icon btn-warning"><i class="fas fa-print"></i></a>
										<a type="button" href="#" data-toggle="tooltip" data-id="{{$vente->id}}" data-placement="bottom" 
										title="Transformer en BL" class="btn btn-icon btn-success data-valider"
										data-toggle="tooltip" data-placement="bottom" title="Transformer en BL"
										><i class="fas fa-file-import"></i></a>
										<a type="button" href="#" data-toggle="tooltip" data-id="{{$vente->id}}" data-placement="bottom" 
										title="Transformer en Facture" class="btn btn-icon btn-danger data-valider2"
										data-toggle="tooltip" data-placement="bottom" title="Transformer en Facture"
										><i class="fas fa-file-import"></i></a>
										<a type="button" href="{{route('modifierproforma',['id'=>$vente->id])}}"
                                            data-toggle="tooltip" data-placement="bottom" title="Modifier"
                                            class="btn btn-icon btn-primary"><i class="fas fa-edit"></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 cette vente ?
            </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">Transformer en BL</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 transformer en BL?</p>
            </div>
            <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="valider">

            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="Validermodal2">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Transformer en Facture</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 transformer en Facture?</p>
            </div>
            <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="valider2">

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

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

            </form>`
            ;
            $('#valider2').html('').append(html);
          })
          $('#Validermodal2').modal();
        });
    </script>
	<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/Proformav/' + id, function (data) {
            var html = `
            <button type="button" class=" btn btn-danger" data-dismiss="modal">Non</button>
                      <form action="{{route('SupprimerproformaPost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+ data.proforma.id + `" name="id" >
                      <button type="submit" class="btn btn-success">Oui</button>

            </form>`
                ;
            $('#delete').html('').append(html);
        })
        $('#Supprimermodal').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:12px">(${result.prix_detail}/ ${result.prix_semigros}/ ${result.prix_gros})</span>
									<input type="hidden" class="form-control" value="${result.id}" name="item[${iteration}][]">
								</td>
								<td>
									<input type="number" class="form-control" min="1" value="1" name="item[${iteration}][]">
								</td>
								<td>
									<input type="number" class="form-control" value="${result.prix_detail}"  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="client_id"]').val() != ''){
					document.getElementById('sell-form').submit();
				}
				
			}


		</script>

	@endpush
@endsection