@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">
				<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>
    @php
    $dd = date('d/m/Y');
    @endphp
	<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>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 class="mb-2">
                            <label><b>Remise <font color="red">*</font></b></label>
                            <input type="number" class="form-control" value="0" name="remise">
                        </div>

                        <div class="mb-2">
                            <label><b>Date <font color="red">*</font></b></label>
                            <input type="text" class="form-control" name="datet" value="{{$dd}}" id="champ_date2">
                            <div id="calendarMain2"></div>
                        </div>

                        <div class="mb-2">
                            <label><b>Nom client <font color="red">*</font></b></label>
                            <select class="form-control select2" name="client_id" required>
                                <option value="">Sélectionner</option>
                                @foreach($client as $clients)
                                <option value="{{$clients->id}}">{{$clients->noms}}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="mb-2">
                            <label><b>Au nom du Magasin <font color="red">*</font></b></label>
                            <select class="form-control select2" name="magasin_id" required>
                                <option value="">Sélectionner</option>
                                @foreach($magasin as $magasins)
                                <option value="{{$magasins->id}}">{{$magasins->nom}}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="mb-2">
                            <label><b>Taxes</b></label>
                            <select class="form-control select2" name="taxes">
                                <option value="Non">Non</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 : <b id="total" style="color: red"></b>
                        </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>
</form>


<div class="container section-body">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4>Liste des proformas</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">Date</th>
                                    <th class="text-center">Montant Rem.</th>
                                    <th class="text-center">Montant TTC</th>
                                    <th class="text-center">Etat</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($proforma as $proformas)
                                <tr>
                                    <td style="text-align:center;">{{$loop->iteration}}</td>
                                    <td style="text-align:center;">{{$proformas->numero}}</td>
                                    <td style="text-align:center;">{{DB::table('client_externe')->where('id', $proformas->client_id)->first()->noms}}</td>
                                    @php
                                    $dd = implode('/', array_reverse(explode('-', $proformas->date)));
                                    $mht = number_format($proformas->montant_ht, 0, ' ', ' ');
                                    $total_taxe2 = number_format($proformas->total_taux, 0, ' ', ' ');
                                    $lh3 = number_format($proformas->montant, 0, ' ', ' ');

                                    @endphp
                                    <td style="text-align:center;">{{$dd}} </td>
                                    <td style="text-align:center;">{{$proformas->montant_remise}} F</td>
                                    <td style="text-align:center;">{{$lh3}} F</td>
                                    <td style="text-align:center;">
                                        @if( $proformas->etat == "Proforma")
                                        <div class="badge badge-warning badge-shadow">{{$proformas->etat}}</div>
                                        @elseif( $proformas->etat == "Validée")
                                        <div class="badge badge-success badge-shadow">{{$proformas->etat}}</div>
                                        @else
                                        <div class="badge badge-danger badge-shadow">{{$proformas->etat}}</div>
                                        @endif
                                    </td>
                                    <td class="align-middle">
                                        <a type="button" href="{{route('ligne-proforma',['id'=>$proformas->id])}}"
                                            data-toggle="tooltip" data-placement="bottom" title="Détails"
                                            class="btn btn-icon btn-info"><i class="fas fa-info"></i></a>
                                        @if( $proformas->etat == "Proforma")
                                        <!--<a type="button" href="#" data-toggle="tooltip" data-id="{{$proformas->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="{{$proformas->id}}"
                                            data-placement="bottom" title="Supprimer"
                                            class="btn btn-icon btn-danger data-supprimer"><i
                                                class="fas fa-trash"></i></a>
										<a href="{{route('modifierproforma',['id'=>$proformas->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" href="{{route('invoicegenerate',['id'=>$proformas->id])}}" class="btn btn-icon btn-warning" hidden><i class="fas fa-print">GN</i></a>-->
            								<a type="button" target="_blank" 
            								data-toggle="tooltip" data-placement="bottom" title="Imprimer" href="{{route('facture-proforma',['id'=>$proformas->id])}}" class="btn btn-icon btn-success"><i class="fas fa-print"></i>PR</a>	
                                    </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="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 cet enregistrement ?
            </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 + '/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;

    // Recherche par code barre
    $("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();
        var barcode = $(this).val();
        var data = { search: barcode };
        data._token = "{{ csrf_token() }}";

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

            // Vérifie si le produit existe déjà
            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;
            }

            if (result) {
                const row = `
                    <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}][]" autofocus>
                        </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(row);
                onMouseMove();

                $("input[name=search]").val('').focus();
                iteration++;
            }
        });
    });

    // Recalcul automatique
    $(document).on('input', 'input[type=number]', function () {
        onMouseMove();
    });

    function onMouseMove() {
        var total = 0;
        var 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 ($('select[name="client_id"]').val() == '') {
            alert('Veuillez sélectionner le client');
            return;
        }

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

        if ($("input[name=datet]").val() == '') {
            alert('Veuillez renseigner la date');
            return;
        }

        if ($("#item>tr").length === 0) {
            alert('Veuillez ajouter au moins un produit');
            return;
        }

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

    // Recalcul même au clic hors champ
    $("body").on('click', function () {
        onMouseMove();
    });
</script>

	@endpush
@endsection