@include('layouts.commons.errors')
@include('layouts.commons.success')

<form method="POST"
    action="{{ route("projets.update_achats_simples", $projet->id ?? '') }}">
    @csrf
    {{ method_field('PUT') }}
    <input type="hidden" name="projet_id" value="{{ $projet->id }}">

    <div class="row">
        <div class="col-6">
            <div class="form-group row">
                <label for="duree_mois" class="col-6 col-form-label text-right">Durée en nombre de mois</label>
                <div class="col-6">
                    <input type="number" class="form-control" id="duree_mois" value="{{$projet->duree_mois ?? 12}}" disabled>
                    <span class="text-danger error"></span>
                </div>
            </div>
        </div>
        <div class="col-6 text-right">
            <div class="form-group row">
                <label for="duree_mois" class="col-6 col-form-label">Date de notification</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="datepicker form-control flatpickr-input" id="date_notification"
                            name="date_notification"
                            value="{{ old('date_notification', isset($projet->date_mise_en_oeuvre) ? date('d/m/Y', strtotime($projet->date_mise_en_oeuvre)) : '') }}">
                        <div class="input-group-append">
                            <span class="input-group-text">
                                <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-calendar3"
                                    fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                    <path fill-rule="evenodd"
                                        d="M14 0H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM1 3.857C1 3.384 1.448 3 2 3h12c.552 0 1 .384 1 .857v10.286c0 .473-.448.857-1 .857H2c-.552 0-1-.384-1-.857V3.857z" />
                                    <path fill-rule="evenodd"
                                        d="M6.5 7a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z" />
                                </svg>
                            </span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>
    </div>


    <!-- Bloc Référentiel -->
    <h4>Référentiel</h4>
    <div class="row custom-frame pt-3">
        <div class="col-6">
            <div class="form-group row pb-0">
                <div class="col-6 d-flex">
                    <span class="align-self-center" data-toggle="tooltip" data-placement="top" title="Montant des dépenses de l'exercice N-1 relatifs à l'achat de produits ou de biens récurrents">
                        <i class="fas fa-question-circle text-primary"></i>
                    </span>
                    <label for="montant_reference" class="col-form-label ml-auto required">Montant de référence</label>
                </div>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="montant_reference" name="montant_reference"
                            value="{{ old('montant_reference', $projet->montant_reference ?? '') }}" {{ $projet->report ? 'readonly' : '' }}>
                        <div class="input-group-append">
                            <span class="input-group-text">€/an</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-6 text-right">
            <div class="form-group row pb-0">
                <label for="pourcentage_gains_cible" class="col-sm-6 col-form-label required">Gains cible</label>
                <div class="col-sm-6">
                    <div class="input-group">
                        <input type="number" class="form-control" id="pourcentage_gains_cible" name="pourcentage_gains_cible"
                            value="{{ old('pourcentage_gains_cible', $projet->pourcentage_gains_cible ?? '') }}" min="0" max="100"
                            {{ $projet->report ? 'readonly' : '' }}>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center align-self-end">Ventilation des gains cibles</label>
                <div class="col-3 text-center">
                    <strong>{{$annee_N}}</strong>
                    <input type="text" id="gains_cible_N" class="form-control" disabled>
                </div>
                @if(!$projet->report)
                <div class="col-3 text-center">
                    <strong>{{$annee_N1}}</strong>
                    <input type="text" id="gains_cible_N1" class="form-control" disabled>
                </div>
                @endif

            </div>

        </div>
    </div>

    <!-- Bloc Notifié -->
    <h4>Notifié</h4>
    <div class="row custom-frame pt-3">
        <div class="col-6">
            <div class="form-group row pb-0">
                <div class="col-6 d-flex">
                    <span class="align-self-center" data-toggle="tooltip" data-placement="top" title="Montant du marché notifié">
                        <i class="fas fa-question-circle text-primary"></i>
                    </span>
                    <label for="montant_notifie" class="col-form-label ml-auto">Montant notifié</label>
                </div>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="montant_notifie" name="montant_notifie"
                            value="{{ old('montant_notifie', $projet->montant_notifie ?? '') }}">
                        <div class="input-group-append">
                            <span class="input-group-text">€/an</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-6">
            <div class="form-group row pb-0">
                <label for="gains_notifie" class="col-6 col-form-label text-right">Gains notifiés</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" id="gains_notifie" class="form-control" disabled>
                        <div class="input-group-append">
                            <span class="input-group-text">€</span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>

        <div class="col-6 offset-6">
            <div class="form-group row pb-0">
                <label for="pourcentage_gains_notifie" class="col-6 col-form-label text-right">% de gains notifiés</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="number" id="pourcentage_gains_notifie" class="form-control" disabled>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>
        

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center align-self-end">Ventilation des gains notifiés</label>
                <div class="col-3 text-center">
                    <strong>{{$annee_N}}</strong>
                    <input type="text" id="gains_notifie_N" class="form-control" disabled>
                </div>
                @if(!$projet->report)
                <div class="col-3 text-center">
                    <strong>{{$annee_N1}}</strong>
                    <input type="text" id="gains_notifie_N1" class="form-control" disabled>
                </div>
                @endif

            </div>

        </div>
    </div>

    <!-- Bloc Réalisé -->
    <h4>Réalisé</h4>
    <div class="row custom-frame pt-3">
        <div class="col-6">
            <div class="form-group row pb-0">
                <div class="col-6 d-flex">
                    <span class="align-self-center" data-toggle="tooltip" data-placement="top" title="Montant de la GEF au terme de la 1ère année d'exécution">
                        <i class="fas fa-question-circle text-primary"></i>
                    </span>
                    <label for="montant_realise" class="col-form-label ml-auto">Montant réalisé</label>
                </div>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="montant_realise" name="montant_realise"
                            value="{{ old('montant_realise', $projet->montant_realise ?? '') }}">
                        <div class="input-group-append">
                            <span class="input-group-text">€/an</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-6">
            <div class="form-group row pb-0">
                <label for="gains_securise" class="col-6 col-form-label text-right">Gains sécurisés</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" id="gains_securise" class="form-control" disabled>
                        <div class="input-group-append">
                            <span class="input-group-text">€</span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>
        <div class="col-6 offset-6">
            <div class="form-group row pb-0">
                <label for="pourcentage_gains_securise" class="col-6 col-form-label text-right">% de gains sécurisés</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="number" id="pourcentage_gains_securise" class="form-control" disabled>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <span class="text-danger"></span>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center align-self-end">Ventilation des gains sécurisés</label>
                <div class="col-3 text-center">
                    <strong>{{$annee_N}}</strong>
                    <input type="text" id="gains_realise_N" class="form-control" disabled>
                </div>
                @if(!$projet->report)
                <div class="col-3 text-center">
                    <strong>{{$annee_N1}}</strong>
                    <input type="text" id="gains_realise_N1" class="form-control" disabled>
                </div>
                @endif

            </div>

        </div>
    </div>

    <!-- Bloc Synthèse -->
    <h4>Synthèse</h4>
    <div class="row custom-frame pt-3">
        <div class="col-sm-8">
            <table class="table">
                <tbody>
                    <tr>
                        <th></th>
                        @if(!$projet->report)
                        <th>{{$annee_N}}</th>
                        <th>{{$annee_N1}}</th>
                        @endif
                        <th>Total</th>
                    </tr>
                </tbody>
                <tbody>
                    <tr>
                        <td>Gains cibles en montant</td>
                        @if(!$projet->report)
                        <td><span id="synthese_gains_cible_N"></span></td>
                        <td><span id="synthese_gains_cible_N1"></span></td>
                        @endif
                        <td><span id="synthese_gains_cible_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains notifiés en montant</td>
                        @if(!$projet->report)
                        <td><span id="synthese_gains_notifie_N"></span></td>
                        <td><span id="synthese_gains_notifie_N1"></span></td>
                        @endif
                        <td><span id="synthese_gains_notifie_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains sécurisés en montant</td>
                        @if(!$projet->report)
                        <td><span id="synthese_gains_realise_N"></span></td>
                        <td><span id="synthese_gains_realise_N1"></span></td>
                        @endif
                        <td><span id="synthese_gains_realise_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains budgétaires en montant</td>
                        @if(!$projet->report)
                        <td><span id="synthese_gains_budgetaire_N"></span></td>
                        <td><span id="synthese_gains_budgetaire_N1"></span></td>
                        @endif
                        <td><span id="synthese_gains_budgetaire_total"></span></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Zone commentaire -->
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <div class="form-group">
                <label for="commentaire">Commentaire</label>
                <textarea class="form-control" name="commentaire" rows="3">{{ old('commentaire', $projet->commentaire ?? '') }}</textarea>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="form-group text-right">
                <a href="{{ route('projets.index') }}" class="btn btn-outline-warning">Annuler</a>
                @if($editable)
                    <input type="submit" class="btn btn-outline-success" value="Enregistrer">
                @endif
            </div>
        </div>
    </div>
</form>

@if(isset($projet))
<script>
    $(document).ready(function(){
        calcul_achats_simples();

        $("#date_notification, #montant_reference, #pourcentage_gains_cible, #montant_notifie, #montant_realise").on("change", function() {
            calcul_achats_simples();
        });
    });

    function calcul_achats_simples(){
		var montant_reference = parseInt($("#montant_reference").val().replace(/ /g, ''));
        var gains_cible = $("#pourcentage_gains_cible").val();
        var montant_notifie = parseInt($("#montant_notifie").val().replace(/ /g, ''));
        var montant_realise = parseInt($("#montant_realise").val().replace(/ /g, ''));
        var date_notification = $('#date_notification').val();

        // S'il manque le montant de référence, on annule
        if (montant_reference == "" || gains_cible == "") {
            return;
        }

        // Calcul des dates
        var date_fin_comptabilisation = new Date("{{$date_fin_comptabilisation}}");
		var date_fin = new Date("{{$projet->date_fin}}");
        // On calcule le nombre de jours entre la date de fin prévisionnelle et la fin de l'année
        var day_diff = Math.floor((date_fin_comptabilisation.getTime() - date_fin.getTime())/ (1000 * 3600 * 24));
        var duree_mois = 12; // 12 en dur car on est dans les achats simples
		var nb_mois = 12 - parseInt($('#date_notification').val().substr(3,2)) + 1;


        if (gains_cible != "") {
        // Ventilation des gains cibles
            var ventilation_gains_cibles = (montant_reference * gains_cible)/100;
            // Si la fiche est un report, les gains sont ceux reportés pour l'année N et 0 pour l'année N+1
            if ({{$projet->report}}) {
                var gains_cible_N = {{$gains_cibles_N}};
                var gains_cible_N1 = 0;
            } else {
                var gains_cible_N = Math.ceil(( ventilation_gains_cibles * day_diff) / 364);
                var gains_cible_N1 = Math.ceil( ventilation_gains_cibles * (( 364 - day_diff) / 364));
            }
            $("#gains_cible_N").val(gains_cible_N);
            createOrUpdateAutoNumeric($('#gains_cible_N'));
            $("#gains_cible_N1").val(gains_cible_N1);
            createOrUpdateAutoNumeric($('#gains_cible_N1'));
        }


        if(montant_notifie != "" && date_notification != "") {
            // Gains notifiés
            var gains_notifies = Math.round(montant_reference - montant_notifie);
            $("#gains_notifie").val(gains_notifies);
            createOrUpdateAutoNumeric($('#gains_notifie'));

            // % de gains notifiés
            var pourcentage_gains_notifies = (((montant_reference - montant_notifie) / montant_reference) * 100).toFixed(2);
            $("#pourcentage_gains_notifie").val(pourcentage_gains_notifies);


            // Ventilation des gains notifiés
            var date_notification_from = date_notification.split("/")
            var date_notification_object = new Date(date_notification_from[2], date_notification_from[1] - 1, date_notification_from[0])
            var nb_jours_annee_N_date_notification = Math.floor((date_fin_comptabilisation.getTime() - date_notification_object.getTime())/ (1000 * 3600 * 24));
            // Si la fiche est un report, les gains sont ceux reportés pour l'année N et 0 pour l'année N+1
            if ({{$projet->report}}) {
                var gains_notifie_N = {{$gains_notifies_N}};
                var gains_notifie_N1 = 0;
            } else {
                var gains_notifie_N = Math.ceil(( gains_notifies * nb_jours_annee_N_date_notification) / 364);
                var gains_notifie_N1 = Math.ceil( gains_notifies * (( 364 - nb_jours_annee_N_date_notification) / 364));
            }
            $("#gains_notifie_N").val(gains_notifie_N);
            createOrUpdateAutoNumeric($('#gains_notifie_N'));
            $("#gains_notifie_N1").val(gains_notifie_N1);
            createOrUpdateAutoNumeric($('#gains_notifie_N1'));

            // Gains budgétaires (pour le tableau de synthèse)
            var impact_budgetaire = {{$projet->impact_budgetaire}};
            var gains_budgetaire_N = Math.round((gains_notifie_N * impact_budgetaire) / 100);
            var gains_budgetaire_N1 = Math.round((gains_notifie_N1 * impact_budgetaire) / 100);
        }


        if(montant_realise != "") {
            // Gains sécurisés
            var gains_securise = Math.round(montant_reference - montant_realise);
            $("#gains_securise").val(gains_securise);
            createOrUpdateAutoNumeric($('#gains_securise'));


            // % de gains sécurisés
            var pourcentage_gains_securise = (((montant_reference - montant_realise) / montant_reference) * 100).toFixed(2);
            $("#pourcentage_gains_securise").val(pourcentage_gains_securise);


            // Ventilation des gains sécurisés
            var date_notification_from = date_notification.split("/")
            var date_notification_object = new Date(date_notification_from[2], date_notification_from[1] - 1, date_notification_from[0])
            var nb_jours_annee_N_date_notification = Math.floor((date_fin_comptabilisation.getTime() - date_notification_object.getTime())/ (1000 * 3600 * 24));
            // Si la fiche est un report, les gains sont ceux reportés pour l'année N et 0 pour l'année N+1
            if ({{$projet->report}}) {
                var gains_realise_N = {{$gains_realises_N}};
                var gains_realise_N1 = 0;
            } else {
                var gains_realise_N = Math.ceil(( gains_securise * nb_jours_annee_N_date_notification) / 364);
                var gains_realise_N1 = Math.ceil(gains_securise * (( 364 - nb_jours_annee_N_date_notification) / 364));
            }
            $("#gains_realise_N").val(gains_realise_N);
            createOrUpdateAutoNumeric($('#gains_realise_N'));
            $("#gains_realise_N1").val(gains_realise_N1);
            createOrUpdateAutoNumeric($('#gains_realise_N1'));
        }


        // Tableau de synthèse
        if (gains_cible != "") {
            $("#synthese_gains_cible_N").html(gains_cible_N);
            createOrUpdateAutoNumeric($('#synthese_gains_cible_N'));
            $("#synthese_gains_cible_N1").html(gains_cible_N1);
            createOrUpdateAutoNumeric($('#synthese_gains_cible_N1'));
            $("#synthese_gains_cible_total").html((gains_cible_N + gains_cible_N1));
            createOrUpdateAutoNumeric($('#synthese_gains_cible_total'));
        }

        if(montant_notifie != "") {
            $("#synthese_gains_notifie_N").html(gains_notifie_N);
            createOrUpdateAutoNumeric($('#synthese_gains_notifie_N'));
            $("#synthese_gains_notifie_N1").html(gains_notifie_N1);
            createOrUpdateAutoNumeric($('#synthese_gains_notifie_N1'));
            $("#synthese_gains_notifie_total").html((gains_notifie_N + gains_notifie_N1));
            createOrUpdateAutoNumeric($('#synthese_gains_notifie_total'));

            $("#synthese_gains_budgetaire_N").html(gains_budgetaire_N);
            createOrUpdateAutoNumeric($('#synthese_gains_budgetaire_N'));
            $("#synthese_gains_budgetaire_N1").html(gains_budgetaire_N1);
            createOrUpdateAutoNumeric($('#synthese_gains_budgetaire_N1'));
            $("#synthese_gains_budgetaire_total").html((gains_budgetaire_N + gains_budgetaire_N1));
            createOrUpdateAutoNumeric($('#synthese_gains_budgetaire_total'));
        }

        if(montant_realise != "") {
            $("#synthese_gains_realise_N").html(gains_realise_N);
            createOrUpdateAutoNumeric($('#synthese_gains_realise_N'));
            $("#synthese_gains_realise_N1").html(gains_realise_N1);
            createOrUpdateAutoNumeric($('#synthese_gains_realise_N1'));
            $("#synthese_gains_realise_total").html((gains_realise_N + gains_realise_N1));
            createOrUpdateAutoNumeric($('#synthese_gains_realise_total'));
        }
	}

	function createOrUpdateAutoNumeric(DOMElement)
    {
        if(DOMElement.length) {
            if (AutoNumeric.getAutoNumericElement(DOMElement[0]) === null) {
                new AutoNumeric(DOMElement[0], autonumericConfig);
            }
            else {
                // Permet de gérer les élements de synthèse qui sont des span et non des inputs
                DOMElement.val() === '' ?
                    AutoNumeric.getAutoNumericElement(DOMElement[0]).set(DOMElement.html())
                    : AutoNumeric.getAutoNumericElement(DOMElement[0]).set(DOMElement.val());
            }
        }
    }
</script>
@endif
