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

<form method="POST" id="form_achats_complexes"
    action="{{ route("projets.update_achats_complexes_dgos", $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 required">Durée en nombre de mois</label>
                <div class="col-6">
                    <input type="number" class="form-control" id="duree_mois" name="duree_mois" min="12" step="12"
                        value="{{ old('duree_mois', $projet->duree_mois ?? 12) }}">
                </div>
            </div>
        </div>
        <div class="col-6 text-right">
            <div class="form-group row">
                <label for="date_notification" 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>
                </div>
            </div>
        </div>
    </div>


    <h4>Référentiel</h4>
    <div class="row custom-frame pt-3">
        <div class="col-6 border-right">
            <div class="form-group">
                <label for="montant_tco_reference" class="col-form-label required">Montant de
                référence sur la durée du projet</label>
                <div class="input-group">
                    <input type="text" class="form-control autonumeric" id="montant_reference" name="montant_reference"
                    value="{{ old('montant_reference', $projet->montant_reference ?? '') }}">
                    <div class="input-group-append">
                        <span class="input-group-text">€ / an</span>
                    </div>
                </div>
            </div>

            <div class="h5">Détail des composantes de coût sur la durée total du projet</div>
            
            <div class="form-group row">
                <label for="amortissements_investissements" class="col-6 col-form-label">Investissements</label>
                <div class="col-6">
                    <input type="text" name="amortissements_investissements" class="form-control autonumeric"
                                value="{{ old('amortissements_investissements',
                                $detail_achats_complexes['amortissements_investissements'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="maintenances" class="col-6 col-form-label">Maintenance</label>
                <div class="col-6">
                    <input type="text" name="maintenances" class="form-control autonumeric"
                                value="{{ old('maintenances',
                                $detail_achats_complexes['maintenances'] ?? '') }}">
                </div>
            </div>
            
            <div class="form-group row">
                <label for="couts_installations" class="col-6 col-form-label">Coûts des installations</label>
                <div class="col-6">
                    <input type="text" name="couts_installations" class="form-control autonumeric"
                                value="{{ old('couts_installations',
                                $detail_achats_complexes['couts_installations'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="consommables" class="col-6 col-form-label">Consommables</label>
                <div class="col-6">
                    <input type="text" name="consommables" class="form-control autonumeric"
                                value="{{ old('consommables',
                                $detail_achats_complexes['consommables'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="couts_formations" class="col-6 col-form-label">Coûts de formation</label>
                <div class="col-6">
                    <input type="text" name="couts_formations" class="form-control autonumeric"
                                value="{{ old('couts_formations',
                                $detail_achats_complexes['couts_formations'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="resources_internes" class="col-6 col-form-label">Ressources internes</label>
                <div class="col-6">
                    <input type="text" name="resources_internes" class="form-control autonumeric"
                            value="{{ old('resources_internes',
                                $detail_achats_complexes['resources_internes'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="energies" class="col-6 col-form-label">Energies</label>
                <div class="col-6">
                    <input type="text" name="energies" class="form-control autonumeric"
                            value="{{ old('energies',
                                $detail_achats_complexes['energies'] ?? '') }}">
                </div>
            </div>

            <div class="form-group row">
                <label for="autres" class="col-6 col-form-label">Autres</label>
                <div class="col-6">
                    <input type="text" name="autres" class="form-control autonumeric"
                            value="{{ old('autres',
                                $detail_achats_complexes['autres'] ?? '') }}">
                </div>
            </div>
        </div>



        <div class="col-6">
            
            <div class="form-row">
                <div class="form-group col-6">
                    <label for="montant_annuel" class="col-form-label required">Montant annuel</label>
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="montant_annuel" name="montant_annuel"
                            value="{{ old('montant_annuel', $projet->montant_annuel ?? '') }}" readonly>
                        <div class="input-group-append">
                            <span class="input-group-text">€ / an</span>
                        </div>
                    </div>
                </div>
                <div class="form-group col-6">
                    <label for="pourcentage_gains_cible" class="col-form-label required">Gains cible</label>
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="pourcentage_gains_cible" name="pourcentage_gains_cible"
                            value="{{ old('pourcentage_gains_cible', $projet->pourcentage_gains_cible ?? '') }}" min="0" max="100">
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <label class="col-4 col-form-label text-center align-middle">Gains cibles en base 12 mois</label>
                <div class="col-4 text-center">
                    <strong>{{$annee_N}}</strong>
                    <input type="text" id="gains_cible_N" class="form-control autonumeric" disabled>
                </div>
                <div class="col-4 text-center">
                    <strong>{{$annee_N1}}</strong>
                    <input type="text" id="gains_cible_N1" class="form-control autonumeric" disabled>
                </div>

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


    <h4>Notifié</h4>
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <div class="row">
                <div class="col-6 form-row">
                    <label for="montant_notifie" class="col-6 col-form-label">Montant notifié sur la durée du projet</label>
                    <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">€</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-6 form-row">
                    <label for="moyenne_offres_duree_projet" class="col-6 col-form-label">Moyenne des offres sur la durée du projet</label>
                    <div class="col-6">
                        <div class="input-group">
                            <input type="text" class="form-control autonumeric" id="moyenne_offres_duree_projet" name="moyenne_offres_duree_projet"
                            value="{{ old('moyenne_offres_duree_projet', $projet->moyenne_offres_duree_projet ?? '') }}">
                            <div class="input-group-append">
                                <span class="input-group-text">€</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row my-3">
                <div class="col-6 form-row">
                    <label for="montant_notifie_12_mois" class="col-6 col-form-label">Montant notifié en base 12 mois</label>
                    <div class="col-6">
                        <div class="input-group">
                            <input type="text" class="form-control autonumeric" id="montant_notifie_12_mois" name="montant_notifie_12_mois"
                            value="" disabled>
                            <div class="input-group-append">
                                <span class="input-group-text">€ / an</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-6 form-row">
                    <label for="moyenne_offres_12_mois" class="col-6 col-form-label">Moyenne des offres en base 12 mois</label>
                    <div class="col-6">
                        <div class="input-group">
                            <input type="text" class="form-control autonumeric" id="moyenne_offres_12_mois" name="moyenne_offres_12_mois"
                            value="" disabled>
                            <div class="input-group-append">
                                <span class="input-group-text">€ / an</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row my-3">
                <div class="col-6 form-row">
                    <label for="gains_notifies_12_mois" class="col-6 col-form-label">Gains notifiés en base 12 mois</label>
                    <div class="col-6">
                        <div class="input-group">
                            <input type="text" class="form-control autonumeric" id="gains_notifies_12_mois" name="gains_notifies_12_mois"
                            value="" disabled>
                            <div class="input-group-append">
                                <span class="input-group-text">€</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row my-3">
                <label class="col-3 col-form-label text-center">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 autonumeric" disabled>
                </div>
                <div class="col-3 text-center">
                    <strong>{{$annee_N1}}</strong>
                    <input type="text" id="gains_notifie_N1" class="form-control autonumeric" disabled>
                </div>

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


    <h4>Sécurisé</h4>
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <div class="form-group row">
                <div class="col-3 offset-3 text-center">
                    <strong>{{$annee_N}}</strong>
                </div>
                <div class="col-3 text-center">
                    <strong>{{$annee_N1}}</strong>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center">Montant réalisé</label>
                <div class="col-3 text-center">
                    <input type="text" name="montant_realise[]" class="form-control autonumeric"
                    value="{{ old('montant_realise[$annee_N]',
                                $achats_complexes[$annee_N]['realise'] ?? '') }}">
                </div>
                <div class="col-3 text-center">
                    <input type="text" name="montant_realise[]" class="form-control autonumeric"
                    value="{{ old('montant_realise[$annee_N1]',
                                $achats_complexes[$annee_N1]['realise'] ?? '') }}">
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center">Gains sécurisés</label>
                <div class="col-3 text-center">
                    <input type="text" name="gains_securises[]" class="form-control autonumeric" disabled>
                </div>
                <div class="col-3 text-center">
                    <input type="text" name="gains_securises[]" class="form-control autonumeric" disabled>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="form-group row">
                <label class="col-3 col-form-label text-center">Gains sécurisés en %</label>
                <div class="col-3 text-center">
                    <input type="text" id="pourcentage_gains_securise_N" class="form-control autonumeric" disabled>
                </div>
                <div class="col-3 text-center">
                    <input type="text" id="pourcentage_gains_securise_N1" class="form-control autonumeric" disabled>
                </div>
            </div>
        </div>
    </div>

    <h4>Synthèse</h4>
    <div class="row custom-frame pt-3">
        <div class="col-sm-8">
            <table class="table">
                <tbody>
                    <tr>
                        <th></th>
                        <th>{{$annee_N}}</th>
                        <th>{{$annee_N1}}</th>
                        <th>Total</th>
                    </tr>
                </tbody>
                <tbody>
                    <tr>
                        <td>Gains cibles en montant</td>
                        <td><span id="synthese_gains_cible_N"></span></td>
                        <td><span id="synthese_gains_cible_N1"></span></td>
                        <td><span id="synthese_gains_cible_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains notifiés en montant</td>
                        <td><span id="synthese_gains_notifie_N"></span></td>
                        <td><span id="synthese_gains_notifie_N1"></span></td>
                        <td><span id="synthese_gains_notifie_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains sécurisés en montant</td>
                        <td><span id="synthese_gains_realise_N"></span></td>
                        <td><span id="synthese_gains_realise_N1"></span></td>
                        <td><span id="synthese_gains_realise_total"></span></td>
                    </tr>
                    <tr>
                        <td>Gains budgétaires en montant</td>
                        <td><span id="synthese_gains_budgetaire_N"></span></td>
                        <td><span id="synthese_gains_budgetaire_N1"></span></td>
                        <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_complexes_dgos();

        $("#duree_mois, #date_notification, #montant_reference, #pourcentage_gains_cible, #montant_notifie, #moyenne_offres_duree_projet, input[name='montant_realise[]']").on("change", function() {
            calcul_achats_complexes_dgos();
        });
    });

    function calcul_achats_complexes_dgos(){
        var duree_amortissement = $("#duree_mois").val()
		var montant_reference = parseInt($("#montant_reference").val().replace(/ /g, ''));
        var gains_cible = $("#pourcentage_gains_cible").val().replace(/ /g, '');

        // S'il manque le montant estimé ou le gain cible, on annule
        if (montant_reference == "" || gains_cible == "" || duree_amortissement == "")
            return;


        // Calcul des dates
        var nbAnnees = parseInt(duree_amortissement) / 12;
        var date_fin = new Date("{{$projet->date_fin}}");
        var date_fin_comptabilisation = new Date("{{ $date_fin_comptabilisation }}");
        var nbJoursAnneeN = Math.floor((date_fin_comptabilisation.getTime() - date_fin.getTime())/ (1000 * 3600 * 24));

        // Montant annuel
        var montant_annuel = Math.floor(montant_reference / nbAnnees); 
        $("#montant_annuel").val(montant_annuel);
        createOrUpdateAutoNumeric($('#montant_annuel'));

        // Ventilation des gains cibles
        var ventilation_gains_cibles = ((montant_reference / nbAnnees) * gains_cible) / 100;
        var gains_cible_N = Math.ceil(( ventilation_gains_cibles * nbJoursAnneeN) / 364);
        var gains_cible_N1 = Math.ceil( ventilation_gains_cibles * (( 364 - nbJoursAnneeN) / 364));
        $("#gains_cible_N").val(gains_cible_N);
        createOrUpdateAutoNumeric($('#gains_cible_N'));
        $("#gains_cible_N1").val(gains_cible_N1);
        createOrUpdateAutoNumeric($('#gains_cible_N1'));



        var date_notification = $('#date_notification').val();
        var montant_notifie = parseInt($("#montant_notifie").val().replace(/ /g, ''));
        var moyenne_offres = parseInt($("#moyenne_offres_duree_projet").val().replace(/ /g, ''));

        // S'il manque la date de notification ou le montant notifié ou la moyenne des offres, on annule
        if(date_notification != "" && montant_notifie != "" && moyenne_offres != "" ) {
            // Montant notifié base 12 mois
            var montant_notifie_12_mois = Math.floor(montant_notifie / nbAnnees);
            $("#montant_notifie_12_mois").val(montant_notifie_12_mois);
            createOrUpdateAutoNumeric($('#montant_notifie_12_mois'));

            // Gains notifiés
            var gains_notifies_12_mois = (parseInt(moyenne_offres) - parseInt(montant_notifie)) / nbAnnees;
            $("#gains_notifies_12_mois").val(gains_notifies_12_mois);
            createOrUpdateAutoNumeric($('#gains_notifies_12_mois'));
            var pourcentage_gains_notifies = (((parseInt(moyenne_offres) - parseInt(montant_notifie)) / parseInt(moyenne_offres)) * 100).toFixed(2);
            $("#pourcentage_gains_notifie").val(pourcentage_gains_notifies);

            // Moyenne des offres 12 mois
            var moyenne_offres_12_mois = Math.floor(moyenne_offres / nbAnnees);
            $("#moyenne_offres_12_mois").val(moyenne_offres_12_mois);
            createOrUpdateAutoNumeric($('#moyenne_offres_12_mois'));

            // Gains notifiés base 12 mois


            // 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));
            var gains_notifie_N = Math.ceil(( gains_notifies_12_mois * nb_jours_annee_N_date_notification) / 364);
            var gains_notifie_N1 = Math.ceil( gains_notifies_12_mois * (( 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_budgetaires = (montant_reference - gains_notifies_12_mois) * impact_budgetaire / 100;
            // var gains_budgetaire_N = Math.round(( gains_notifie_N * impact_budgetaire) / 100);
            // var gains_budgetaire_N1 = Math.round(( gains_notifie_N1 * impact_budgetaire) / 100);
            var gains_budgetaire_N = Math.ceil(( gains_budgetaires * nb_jours_annee_N_date_notification) / 364);
            var gains_budgetaire_N1 = Math.ceil( gains_budgetaires * (( 364 - nb_jours_annee_N_date_notification) / 364));
        }

        var montant_realise_N = parseInt($("input[name='montant_realise[]']").get(0).value.replace(/ /g, ''));
        if(montant_realise_N != "") {
            // Gains sécurisés
            var gains_securise_N = Math.round(montant_annuel - montant_realise_N);
            $("input[name='gains_securises[]']").get(0).value = gains_securise_N;
            createOrUpdateAutoNumeric($($("input[name='gains_securises[]']:first")));


            // % de gains sécurisés
            var pourcentage_gains_securise = (((montant_annuel - montant_realise_N) / montant_annuel) * 100).toFixed(2);
            $("#pourcentage_gains_securise_N").val(pourcentage_gains_securise);
            createOrUpdateAutoNumeric($($("#pourcentage_gains_securise_N")));
        }

        var montant_realise_N1 = parseInt($("input[name='montant_realise[]']").get(1).value.replace(/ /g, ''));
        if(montant_realise_N1 != "") {
            // Gains sécurisés
            var gains_securise_N1 = Math.round(montant_annuel - montant_realise_N1);
            $("input[name='gains_securises[]']").get(1).value = gains_securise_N1;
            createOrUpdateAutoNumeric($($("input[name='gains_securises[]']:last")));


            // % de gains sécurisés
            var pourcentage_gains_securise = (((montant_annuel - montant_realise_N1) / montant_annuel) * 100).toFixed(2);
            $("#pourcentage_gains_securise_N1").val(pourcentage_gains_securise);
            createOrUpdateAutoNumeric($($("#pourcentage_gains_securise_N1")));
        }

        var montant_realise = montant_realise_N + montant_realise_N1;


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

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

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

        if(montant_realise != "") {
            $("#synthese_gains_realise_N").html(gains_securise_N);
            $("#synthese_gains_realise_N1").html(gains_securise_N1);
            $("#synthese_gains_realise_total").html((gains_securise_N + gains_securise_N1));
        }
	}

    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
