@extends('layout')
@section('title','Editer bon de livraison ')
@section('content')
	

    <div class="container mt-3">
	    <div class="row">
	        <div class="col-md-12">
	        @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>
	     	<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)->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('nouveauventeclientPost') }}" 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 hidden><font color="#000"><b>Prix : </b></font>
								<select class="form-control select2" name="typevente">
								        <option value="Gros">Gros</option>
                                        <option value="Détail" hidden>Détail</option>
                                        <option value="Semigros" hidden>Semigros</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>Date : </b></font>
								<input type="text" class="form-control" value="{{date('d/m/Y')}}" name="datet" id="champ_date2">
								<div id="calendarMain2"></div>
							</div>
							<div><font color="#000"><b>Nom client : </b></font>
								<select class="form-control select2" name="client" required>
										<option value=""> </option>
                                        @foreach($client as $clients)
                                        <option value="{{$clients->id}}">{{$clients->noms}}</option>
                                        @endforeach
                                </select>
							</div>
							<div><font color="#000"><b>Déstocké de : </b></font>
								<select class="form-control select2" name="stockage" id="stockage" required>
										<option value="">Sélectionner</option>
                                        <option value="Dépot">Dépot</option>
                                        <option value="Magasin">Magasin</option>
                                </select>
							</div>
							<div id="mag"><font color="#000"><b>Magasin : </b></font>
								<select class="form-control select2" name="magasin_id" required>
										<option value="">Sélectionner le magasin</option>
                						 @foreach($magasin as $magasins)
                						<option value="{{$magasins->id}}">{{$magasins->nom}} </option>
                						@endforeach
                                </select>
							</div>
							<div id="dep"><font color="#000"><b>Dépot : </b></font>
								<select class="form-control select2" name="depot_id" required>
										<option value="">Sélectionner le depot</option>
                						 @foreach($depot as $depots)
                						<option value="{{$depots->id}}">{{$depots->nom}} </option>
                						@endforeach
                                </select>
							</div>
							<div hidden><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</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 des BL</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">Type de vente</th>
                                    <th class="text-center">Date</th>
                                    <th class="text-center">Montant HT</th>
                                    <th class="text-center">Remise</th>
                                    <th class="text-center">Montant TTC</th>
                                    <th class="text-center">Etat</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;">BL{{$vente->numero}}</td>
							<td style="text-align:center;">{{DB::table('client_externe')->where('id',$vente->client_id)->first()->noms}}</td>
							<td style="text-align:center;">{{$vente->type_vente}}</td>
							@php
							$dd = implode('/', array_reverse(explode('-', $vente->date)));
							$mht =  number_format($vente->montant_ht, 0, ' ', ' ');
							$rem =  number_format($vente->montant_remise, 0, ' ', ' ');
							$total_taxe2 =  number_format($vente->total_taux, 0, ' ', ' ');
							$lh3 =  number_format($vente->montant, 0, ' ', ' ');

							@endphp
							<td style="text-align:center;">{{$dd}} {{$vente->heure}}</td>
							<td style="text-align:center;">{{$mht}} FCFA</td>
							<td style="text-align:center;">{{$rem}} FCFA</td>
							<td style="text-align:center;">{{$lh3}} FCFA</td>
							<td style="text-align:center;">
							@if( $vente->etat ==  "Proforma")
							<div class="badge badge-warning badge-shadow">Non validé</div>
							@elseif( $vente->etat ==  "Validée")
							<div class="badge badge-success badge-shadow">{{$vente->etat}}</div>
							@else
							<div class="badge badge-danger badge-shadow">{{$vente->etat}}</div>
							@endif
							</td>
							<td class="align-middle">
							<a type="button" href="{{route('ligne-vente-client',['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>
							 @if( $vente->etat ==  "Proforma")
							<a type="button" href="#" data-toggle="tooltip" data-id="{{$vente->id}}" data-placement="bottom" title="Valider" class="btn btn-icon btn-success data-valider"><i class="fas fa-check"></i></a>
							<a type="button" href="#" data-toggle="tooltip" data-id="{{$vente->id}}" data-placement="bottom" title="Supprimer" class="btn btn-icon btn-danger data-supprimer"><i class="fas fa-trash"></i></a>
							<a type="button" href="{{route('modifier_vente_client',['id'=>$vente->id])}}" data-toggle="tooltip"
                                            data-placement="bottom" title="Modifier"
                                            class="btn btn-icon btn-primary"><i
                                                class="fas fa-edit"></i></a>
							@endif
							@if( $vente->etat ==  "Validée")
							<a type="button" href="{{route('modifier_vente_client_',['id'=>$vente->id])}}" data-toggle="tooltip"
                                            data-placement="bottom" title="Modifier"
                                            class="btn btn-icon btn-primary"><i
                                                class="fas fa-edit"></i></a>
                            
							@endif
							<!--<a type="button" target="_blank" href="{{route('factureVenteclient',['id'=>$vente->id])}}" class="btn btn-icon btn-warning" data-toggle="tooltip" data-placement="bottom" title="BL AVEC PRIX"><i class="fas fa-print"></i></a>	-->
							<!--<a type="button" target="_blank" href="{{route('factureVenteclient2',['id'=>$vente->id])}}" class="btn btn-icon btn-danger" data-toggle="tooltip" data-placement="bottom" title="BL SANS PRIX"><i class="fas fa-print"></i></a>	-->
							<a type="button" target="_blank" href="{{route('factureclient',['id'=>$vente->id])}}" class="btn btn-icon btn-success" data-toggle="tooltip" data-placement="bottom" title="Facture"><i class="fas fa-print"></i></a>	
							<a type="button" target="_blank" href="{{route('factureclient21',['id'=>$vente->id])}}" class="btn btn-icon btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Invoice"><i class="fas fa-print"></i></a>
							@if( $vente->etat ==  "Validée")
							<!--<a type="button" href="{{route('livraison',['id'=>$vente->id])}}" class="btn btn-icon btn-primary" data-toggle="tooltip" data-placement="bottom" title="Editer bon de livraison"><i class="fas fa-file"></i></a>-->	
							@endif
							</td>
							
                          </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    @php
                    \Illuminate\Support\Facades\DB::table('vente')->where('montant', 0)->delete();
                    @endphp
                </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">Validation</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 le 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="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 ce BL ? 
            </div>
            <div class="modal-footer bg-whitesmoke br" style="background-color:#ffffff" id="delete">

            </div>
        </div>
    </div>
</div>
	@push('scripts')
	 <script>
	 
			$('#mag').hide();
			$('#dep').hide();	
			$('select[name="stockage"]').change(function(){
				var valeur = $(this).val();
				if (valeur != ''){
					if (valeur == 'Magasin'){
						$('#mag').show();
						$('#dep').hide();
					} else if (valeur == 'Dépot') {
						$('#dep').show();
						$('#mag').hide();
					} else {
					    $('#dep').hide();
						$('#mag').hide();
					}
					
				}
			});
			
	 </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-valider").on('click', function () {
                var id=$(this).data('id');
                $.get(location.origin+'/es/Validerventeclient/'+id, function (data) {
                  var html = `
                      <form action="{{route('ValiderventeclientPot')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+data.vente.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-supprimer").on('click', function () {
                var id=$(this).data('id');
                $.get(location.origin+'/es/Venteclient/'+id, function (data) {
                  var html = `
            <button type="button" class=" btn btn-danger" data-dismiss="modal">Non</button>
                      <form action="{{route('SupprimerventeclientPost')}}" method="post" style="display: inline">
                        {{csrf_field()}}
                      <input type="hidden" value="`+data.ven.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;

    // Afficher/masquer dépôt et magasin selon stockage
    $("#stockage").on('change', function () {
        let val = $(this).val();
        if (val === "Dépot") {
            $("#dep").show();
            $("#mag").hide();
        } else if (val === "Magasin") {
            $("#dep").hide();
            $("#mag").show();
        } else {
            $("#dep").hide();
            $("#mag").hide();
        }
    }).trigger('change');

    // Permet d’ajouter un produit au scan ou saisie
    $("input[name=search]").on('keypress', function (e) {
        if (e.which == 13) {
            e.preventDefault();
            $(this).trigger('change');
        }
    });

    $("input[name=search]").on('change', function (event) {
        event.stopImmediatePropagation();
        const barcode = $(this).val();
        const data = {
            search: barcode,
            _token: "{{ csrf_token() }}"
        };

        $.post("{{ route('vente-code2') }}", data, function (result) {
            result = JSON.parse(result);

            if (result) {
                // Vérifie doublon
                let exists = false;
                $("#item input[type=hidden]").each(function () {
                    if ($(this).val() == result.id) {
                        exists = true;
                        return false;
                    }
                });
                if (exists) {
                    alert("Produit déjà ajouté !");
                    $("input[name=search]").val('').focus();
                    return;
                }

                let tr = `
                <tr>
                    <td>
                        <span style="font-size:12px">${result.designation}</span>
                        <span style="font-size:11px">(${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" value="1" min="1" name="item[${iteration}][]"></td>
                    <td><input type="number" class="form-control" value="${result.prix_gros}" 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(tr);
                onMouseMove();
                $("input[name=search]").val('').focus();
                iteration++;
            }
        });
    });

    // Recalcul montant à chaque changement de valeur
    $(document).on('input', 'input[type=number]', function () {
        onMouseMove();
    });

    function onMouseMove() {
        let total = 0;
        const remise = Number($("input[name=remise]").val());

        $("#item>tr").each(function () {
            const td = $(this).find('td');
            const qt = Number(td.eq(1).find('input').val());
            const pu = Number(td.eq(2).find('input').val());
            const montant = qt * pu;

            td.eq(3).find('input').val(montant);
            td.eq(3).find('span').text(montant.toLocaleString('fr-FR'));

            total += montant;
        });

        $("#total").text((total - remise).toLocaleString('fr-FR'));
    }

    function removeTr(button) {
        $(button).closest('tr').remove();
        onMouseMove();
    }

    function submitForm() {
        if ($("#item>tr").length === 0) {
            alert('Veuillez sélectionner les produits qui composent la commande');
            return;
        }

        if ($('select[name="client"]').val() == '') {
            alert('Veuillez sélectionner le client');
            return;
        }

        const stockage = $('select[name="stockage"]').val();
        if (stockage == '') {
            alert('Veuillez sélectionner un mode de déstockage (magasin ou dépot)');
            return;
        }

        if (stockage == 'Magasin' && $('select[name="magasin_id"]').val() == '') {
            alert('Veuillez sélectionner le magasin');
            return;
        }

        if (stockage == 'Dépot' && $('select[name="depot_id"]').val() == '') {
            alert('Veuillez sélectionner le dépot');
            return;
        }

        $('button[type=button]').prop('disabled', true);
        document.getElementById('sell-form').submit();
    }

    // Recalcul automatique sur clic
    $("body").on('click', function () {
        onMouseMove();
    });
</script>

	@endpush
@endsection