@extends('layout')
@section('title','Editer BL')
@section('content')
<br />
<div class="section-body">
    <div class="row">
        <div class="col-lg-10 offset-1 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
            <br />
@php

	$dd = date('d/m/Y');
	@endphp
            <div class="card">
                <div class="card-header">
                    <h4>Edition nouveau BL (<h7>Les champs en * sont obligatoires</h7>)</h4>
                </div>

                <div class="card-body">
                    <form action="" method="POST">
						{{csrf_field()}}
                        <div class="row" style="padding-top: 30px">
                            <div class="col-lg-3 col-md-3" hidden>
                                <div class="form-group">
                                    <label>Type de vente <font color="red">*</font></label>
                                    <select class="form-control select2" name="typevente">
                                        <option value="Détail">Détail</option>
                                        <option value="Gros">Gros</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-5 col-md-5">
                                <div class="form-group">
                                    <label>Client <font color="red">*</font></label>
                                    <select class="form-control select2" name="client">
										<option value="">Sélectionner </option>
                                        @foreach($client as $clients)
                                        <option value="{{$clients->id}}">{{$clients->noms}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
				<div class="col-lg-2 col-md-2"> 
					  <div class="form-group">
                      <label>Date<font color="red">*</font></label>
                      <input type="text" class="form-control" name="datet" id="champ_date2" value="{{$dd}}" required>
					  <div id="calendarMain2"></div>
                    </div>
					</div>
				<div class="col-lg-2 col-md-2">
                                <div class="form-group">
                                    <label>Remise (FCFA)<font color="red">*</font></label>
                                    <input class="form-control" name="remise" value="0">
                                </div>
                            </div>
                        </div>
                        <div class="row venteProduits">
                            <div class="col-lg-6 col-md-6">
                                <div class="form-group">
                                    <label>Produit <font color="red">*</font></label>
                                    <select title="sélectionner le produit" class="form-control select2"
                                        id="selectproduit-0" name="peps[0][produit][]" required>
                                        <option>Sélectionner le produit</option>
                                        @foreach($produit as $produits)
                                        <option value="{{$produits->id}}">{{$produits->designation}}| {{$produits->barcode}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-3">
                                <div class="form-group">
                                    <label>Qte<font color="red">*</font></label>
                                    <input title="saisir la quantité" type="text" class="form-control"
                                        name="peps[0][qte][]" required>
                                </div>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="padding: 30px">

                                <button data-toggle="tooltip" data-placement="bottom" title="Ajouter produit"
                                    type="button" class="btn btn-icon btn-primary" id="addNewblock"><i
                                        class="fas fa-plus"></i></button>

                            </div>

                        </div>
                        <div class="addNouveau"></div>
						<hr>
						<div class="row">
							<div class="col-lg-3 col-md-3">
                                <div class="form-group">
                                    <label>Appliquer les taxes <font color="red">*</font></label>
                                    <select class="form-control select2" name="taxes">
                                        <option value="Non">Non</option>
                                        <option value="Oui">Oui</option>
                                    </select>
                                </div>
                            </div>
						</div>
                        <div class="pull-left">

                            <button type="reset" class="btn btn-icon icon-left btn-danger"><i class="fas fa-times"></i>
                                Annuler</button>
                            <button class="btn btn-icon icon-left btn-primary" id="addvente"><i
                                    class="fas fa-check"></i> Enregistrer</button>
                        </div>

                        <br><br>

                    </form>

                </div>

            </div>
        </div>
    </div>



</div>


<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;">{{$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">{{$vente->etat}}</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('modifierventeclient',['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"><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>
	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>

<script>

    $('#ticket').hide();

    $('select[name="client"]').change(function () {
        var valeur = $(this).val();
        if (valeur != '') {
            if (valeur == '2') {
                $('#ticket').show();
            } else {
                $('#ticket').hide();
            }
        }
    });

</script>

<script>

    function removeBlock() {
        $(".deleteblock").on("click", function () {
            $(this).parent().parent().remove()
        })
    }

    var iteration = 1;
    $("#addNewblock").on("click", function () {
        var venteProduitsDiv = `<div class="row venteProduits" style="margin-top:-20px">
                            
                            <div class="col-lg-6 col-md-6">
                                <div class="form-group">
                                    <label>Produit <font color="red">*</font></label>
                                    <select title="sélectionner le produit" class="form-control select2"
                                        name="peps[`+ iteration +`][produit][]" required>
                                        <option>Sélectionner le produit</option>
                                        @foreach($produit as $produits)
                                        <option value="{{$produits->id}}">{{$produits->designation}}| {{$produits->barcode}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-3">
                                <div class="form-group">
                                    <label>Qte<font color="red">*</font></label>
                                    <input title="saisir la quantité" type="text" class="form-control"
                                        name="peps[`+ iteration +`][qte][]" required>
                                </div>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="padding: 30px">

                                <button data-toggle="tooltip" data-placement="bottom" title="Ajouter produit"
                                    type="button" class="btn btn-icon btn-danger deleteblock"><i
                                        class="fas fa-times"></i></button>

                            </div>

                        </div>`;
        console.log(venteProduitsDiv)
        $('.addNouveau').append(venteProduitsDiv);
        if ($(".form-control select2").length) {
            $(".form-control select2").select2();
        }

        $(".addNouveau").find(".venteProduits").each(function (index, element) {
            //$(element).find(".form-control select2").children().eq(3).remove();

        });

		selectcat(iteration);
		$('.select2').select2();
        removeBlock();
		iteration++;

    });
</script>

<script>

	function selectcat(iteration = 0) {
		$('.selectcat-'+iteration).change(function () {

			var typenivo11 = $('#produits').val();
			console.log(typenivo11)
			var typeselectionner11 = $(this).val();
			typenivo11 = JSON.parse(typenivo11);
			typenivo11 = typenivo11.filter(function (x) {
				return x.categorie_id == typeselectionner11;
			});
			var option = ' <option value="">Sélectionner le produit</option> ';
			for (var i = 0; i < typenivo11.length; i++) {
				option += `
			<option value="`+ typenivo11[i].id + `">` + typenivo11[i].desi + ` </option>
			`;

			}
			$('#selectproduit-'+iteration).html(option);

		})
	}

	selectcat(0);
    

</script>

<script>
    $("#addvente").on('click', function (e) {
        e.preventDefault();
        var data = {};
        var isValide = true;
        data.typevente = $("select[name=typevente]").val();
	data.client = $("select[name=client]").val();
	data.remise = $("input[name=remise]").val();
	data.datet = $("input[name=datet]").val();
	data.taxes = $("select[name=taxes]").val();
        data.peps = [];

        $("[name*=peps]").each(function (index, element) {
            if ($(element).val() != "") {
                if (!Number($(element).val())) {
                    isValide = false;
                    toastr.error('Veuillez ' + $(element)[0].attributes[0].textContent, 'Attention', { timeOut: 5000 });
                }
                console.log($(element).val());
                data.peps.push($(element).val());
            } else {
                toastr.error('Veuillez ' + $(element)[0].attributes[0].textContent, 'Attention', { timeOut: 5000 });
                console.log($(element));
                isValide = false;
                return false;
            }
        });


        if (!data.typevente) {
            toastr.error('Veuillez sélectionner le type de vente ', 'Erreur !', { timeOut: 5000 })
            return false;
        }
		if(!data.client){
				toastr.error('Veuillez sélectionner le client ', 'Erreur !', {timeOut: 5000})
				return false;
			}
		if (!data.datet) {
            toastr.error('Veuillez saisir la date de vente ', 'Erreur !', { timeOut: 5000 })
            return false;
        }
			if (!data.remise) {
            toastr.error('Le champ remise ne doit pas être vide ! ', 'Erreur !', { timeOut: 5000 })
            return false;
        }
		if (!data.taxes) {
            toastr.error('Le champ taxe ne doit pas être vide ! ', 'Erreur !', { timeOut: 5000 })
            return false;
        }

        data._token = "{{csrf_token()}}";

        if (data.peps.length && isValide) {
            $.post("{{route('nouveauventeclientPost')}}", data, function (result) {
                if (result.type == 'error') {
                    toastr.error(result.response, result.title, { timeOut: 5000 })
                } else {

                    toastr.success(result.response, result.title, { timeOut: 15000 })
                    location.reload();
                }

            })
        }
    });

</script>


@endpush

@endsection