<?php

use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\CoreExtension;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
use Twig\TemplateWrapper;

/* plan/notation_form_ia.html.twig */
class __TwigTemplate_2f4b0f4efa317bc9eaad95f64bea61b2 extends Template
{
    private Source $source;
    /**
     * @var array<string, Template>
     */
    private array $macros = [];

    public function __construct(Environment $env)
    {
        parent::__construct($env);

        $this->source = $this->getSourceContext();

        $this->blocks = [
            'page_title' => [$this, 'block_page_title'],
            'page_content' => [$this, 'block_page_content'],
            'stylesheets' => [$this, 'block_stylesheets'],
            'javascripts' => [$this, 'block_javascripts'],
        ];
    }

    protected function doGetParent(array $context): bool|string|Template|TemplateWrapper
    {
        // line 1
        return "@AdminLTE/layout/mesodd-layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        $this->parent = $this->load("@AdminLTE/layout/mesodd-layout.html.twig", 1);
        yield from $this->parent->unwrap()->yield($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_page_title(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        yield $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("notation.titleia", [], "messages");
        yield from [];
    }

    // line 4
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_page_content(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        // line 5
        yield "    ";
        yield         $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->renderBlock(($context["form"] ?? null), 'form_start');
        yield "
    ";
        // line 6
        yield from $this->load("plan/notation_form_ia.html.twig", 6, "2010894353")->unwrap()->yield($context);
        // line 24
        yield "
    ";
        // line 25
        if (((($context["actionId"] ?? null) > 0) && (Twig\Extension\CoreExtension::length($this->env->getCharset(), CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "notationModels", [], "any", false, false, false, 25)) > 0))) {
            // line 26
            yield "    ";
            yield from $this->load("plan/notation_form_ia.html.twig", 26, "2042409447")->unwrap()->yield($context);
            // line 60
            yield "
   <!-- Nouveau tableau pour les résultats de l'IA -->
    ";
        } else {
            // line 63
            yield "        <div class=\"alert alert-info\" role=\"alert\">
            ";
            // line 64
            yield $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("Veuillez sélectionner une action pour afficher ces activités", [], "messages");
            // line 65
            yield "        </div>
    ";
        }
        // line 67
        yield "    ";
        yield         $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->renderBlock(($context["form"] ?? null), 'form_end');
        yield "
";
        yield from [];
    }

    // line 70
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_stylesheets(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        // line 71
        yield "    ";
        yield from $this->yieldParentBlock("stylesheets", $context, $blocks);
        yield "
    <style>
        #iaResultsTable {
            width: 100%;
        }
        #iaResultsTable td {
            vertical-align: middle !important;
        }
        #iaResultsTable select[multiple] {
            min-height: 80px;
        }
        .ia-apply-btn {
            background-color: #28a745;
            color: white;
        }
    </style>
";
        yield from [];
    }

    // line 89
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_javascripts(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        // line 90
        yield "    <script>
        // Variables globales
        let maxRate = \$('#notation_collection_model_maxRate').val();
        let minRate = \$('#notation_collection_model_minRate').val();
        let weighting = \$('#notation_collection_model_weighting').val();
        let grouping = '";
        // line 95
        yield $this->env->getRuntime('Twig\Runtime\EscaperRuntime')->escape(($context["grouping"] ?? null), "html", null, true);
        yield "';

        // Fonctions existantes (inchangées)
        function locationTypeChange(row) {
            if (\$('#'+row+'_locationType').val() == 'arrondissement') {
                document.getElementById(row+'_arrondissements').disabled = true;
            } else if (\$('#'+row+'_locationType').val() == 'poste') {
                \$('#'+row+'_communes_div').hide();
                \$('#'+row+'_postes_div').show();
                document.getElementById(row+'_communes').disabled = true;
                document.getElementById(row+'_postes').disabled = false;
            } else {
                \$('#'+row+'_communes_div').show();
                \$('#'+row+'_postes_div').hide();
                document.getElementById(row+'_communes').disabled = false;
                document.getElementById(row+'_postes').disabled = true;
            }
        }

        function calculTargetRate(row) {
    console.log(\"=== calculTargetRate START ===\");
    console.log(\"Row:\", row);

    let natureRate = getSelectedRate(\$('#' + row + '_nature').val());
    console.log(\"natureRate:\", natureRate);

    let targetRate = natureRate;
    let nbSelec = 0;

    if (natureRate && (natureRate - minRate) != 0) {
        console.log(\"Condition natureRate OK\");

        document.getElementById(row + '_goal').disabled = false;
        document.getElementById(row + '_target').disabled = false;
        document.getElementById(row + '_indicators').disabled = false;
        document.getElementById(row + '_locationType').disabled = false;

        let locType = \$('#' + row + '_locationType').val();
        console.log(\"locationType:\", locType);

        if (locType == 'arrondissement') {
            document.getElementById(row + '_arrondissements').disabled = false;
        } else if (locType == 'poste') {
            document.getElementById(row + '_postes').disabled = false;
        } else {
            document.getElementById(row + '_communes').disabled = false;
        }

        nbSelec = getSelectedOptions(document.getElementById(row + '_indicators')).length;
        console.log(\"nbSelec (indicators):\", nbSelec);

        if (nbSelec > 0) {
            targetRate = maxRate;
            console.log(\"targetRate mis à maxRate:\", targetRate);
        }
    } else {
        console.log(\"Condition natureRate NON OK\");

        document.getElementById(row + '_goal').disabled = true;
        document.getElementById(row + '_target').disabled = true;
        document.getElementById(row + '_indicators').disabled = true;
        document.getElementById(row + '_locationType').disabled = true;

        let locType = \$('#' + row + '_locationType').val();
        console.log(\"locationType:\", locType);

        if (locType == 'arrondissement') {
            document.getElementById(row + '_arrondissements').disabled = true;
        } else if (locType == 'poste') {
            document.getElementById(row + '_postes').disabled = true;
        } else {
            document.getElementById(row + '_communes').disabled = true;
        }
    }

    console.log(\"Final targetRate:\", targetRate);
    \$('#' + row + '_targetRate').val(targetRate);

    calculSensitivity(row);

    console.log(\"=== calculTargetRate END ===\");
}

function calculLocationRate(row) {
    console.log(\"=== calculLocationRate START ===\");
    console.log(\"Row:\", row);

    let locationRate = 0;
    let nbTotal = 0;
    let nbSelec = 0;

    let locType = \$('#' + row + '_locationType').val();
    console.log(\"locationType:\", locType);

    if (locType == 'arrondissement') {
        nbSelec = getSelectedOptions(document.getElementById(row + '_arrondissements')).length;
        nbTotal = document.getElementById(row + '_arrondissements') ? document.getElementById(row + '_arrondissements').options.length : 0;
    } else if (locType == 'poste') {
        nbSelec = getSelectedOptions(document.getElementById(row + '_postes')).length;
        nbTotal = document.getElementById(row + '_postes').options.length;
    } else {
        nbSelec = getSelectedOptions(document.getElementById(row + '_communes')).length;
        nbTotal = document.getElementById(row + '_communes') ? document.getElementById(row + '_communes').options.length : 0;
    }

    console.log(\"nbSelec:\", nbSelec, \"nbTotal:\", nbTotal);

    if (nbTotal != 0) {
        locationRate = (nbSelec / nbTotal) * 100;
    }

    console.log(\"Final locationRate:\", locationRate);
    \$('#' + row + '_locationRate').val(locationRate);

    calculSensitivity(row);

    console.log(\"=== calculLocationRate END ===\");
}

function calculSensitivity(row) {
    console.log(\"=== calculSensitivity START ===\");
    console.log(\"Row:\", row);

    let natureRate = getSelectedRate(\$('#' + row + '_nature').val());
    let locationRate = \$('#' + row + '_locationRate').val();
    let sensitivity = \$('#' + row + '_targetRate').val();

    console.log(\"natureRate:\", natureRate);
    console.log(\"locationRate:\", locationRate);
    console.log(\"initial sensitivity:\", sensitivity);

    if (natureRate && (natureRate - minRate) != 0) {
        sensitivity = (sensitivity - ((100 - locationRate) / 10)) * weighting / 100;
        console.log(\"Adjusted sensitivity:\", sensitivity);
    }

    \$('#' + row + '_sensitivity').val(sensitivity);
    \$('#' + row + '_sensHtml').val(sensitivity);

    console.log(\"Final sensitivity:\", sensitivity);
    console.log(\"=== calculSensitivity END ===\");
}

        function getSelectedOptions(sel, fn) {
            var opts = [], opt;
            for (var i=0, len=sel ? sel.options.length : 0; i<len; i++) {
                opt = sel.options[i];
                if (opt.selected) {
                    opts.push(opt);
                    if (fn) {
                        fn(opt);
                    }
                }
            }
            return opts;
        }

        function getSelectedRate(nature) {
            let allRate = \$('#notation_collection_model_allRate').val();
            allRate = JSON.parse(allRate);
            for (var i = 0; i < allRate.length; i++) {
                if (allRate[i].id == nature) {
                    return allRate[i].rate;
                }
            }
        }

        function goalChange(row, field) {
            let \$field = \$('#'+field);
            let \$goal = \$('#'+row+'_goal');
            let \$location = \$('#'+row+'_locationType');
            let \$form = \$(\$field).closest('form');
            let data = {};
            data[\$goal.attr('name')] = \$goal.val();
            data[\$location.attr('name')] = \$location.val();
            data[\$(\$field).attr('name')] = \$(\$field).val();
            \$.ajax({
                url: \$form.attr('action'),
                type: \$form.attr('method'),
                data: data,
                success: function(html) {
                    if (field == row+'_goal') {
                        \$('#'+row+'_target').replaceWith(
                            \$(html).find('#'+row+'_target')
                        );
                        \$('#'+row+'_indicators').replaceWith(
                            \$(html).find('#'+row+'_indicators')
                        );
                        \$('#'+row+'_target').attr('required', false);
                        if (\$('#'+row+'_treated').is(':checked')) {
                            \$('#'+row+'_target').attr('required', true);
                        }
                    }
                    if (field == row+'_target') {
                        \$('#'+row+'_indicators').replaceWith(
                            \$(html).find('#'+row+'_indicators')
                        );
                    }
                }
            });
        }

        function treatedChange(row) {
            let \$treated = \$('#'+row+'_treated');
            let \$nature = \$('#'+row+'_nature');
            let \$goal = \$('#'+row+'_goal');
            let \$target = \$('#'+row+'_target');
            let \$communes = \$('#'+row+'_communes');
            let \$postes = \$('#'+row+'_postes');
            \$nature.attr('required', false);
            \$goal.attr('required', false);
            \$target.attr('required', false);
            \$communes.attr('required', false);
            \$postes.attr('required', false);
            if (\$treated.is(':checked')) {
                \$nature.attr('required', true);
                \$goal.attr('required', true);
                \$target.attr('required', true);
                \$communes.attr('required', true);
                \$postes.attr('required', true);
            }
        }

        function collectActivities() {
            let activities = [];
            \$(\"#notationTable .activity-col\").each(function() {
                let activityName = \$(this).text().trim();
                let activityId = \$(this).data(\"id\");
                if (activityName && activityId) {
                    activities.push({ name: activityName, id: activityId });
                }
            });
            return activities;
        }

        // Fonction pour créer la barre de progression
        function createProgressBar() {
            let progressContainer = \$(\"#progress-container\");
            if (progressContainer.length === 0) {
                progressContainer = \$(`
                    <div id=\"progress-container\" class=\"mt-3 mb-3\" style=\"display: none;\">
                        <div class=\"progress\" style=\"height: 25px;\">
                            <div id=\"progress-bar\" class=\"progress-bar progress-bar-striped progress-bar-animated\"
                                 role=\"progressbar\" style=\"width: 0%;\"
                                 aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\">
                                0%
                            </div>
                        </div>
                        <div id=\"progress-text\" class=\"text-center mt-2\">
                            <small class=\"text-muted\">Analyse en cours...</small>
                        </div>
                    </div>
                `);
                \$(\"#notationTable\").before(progressContainer);
            }
            return progressContainer;
        }

        // Fonction pour mettre à jour la barre de progression
        function updateProgressBar(percentage) {
            const progressBar = \$(\"#progress-bar\");
            const progressText = \$(\"#progress-text small\");
            progressBar.css(\"width\", percentage + \"%\");
            progressBar.attr(\"aria-valuenow\", percentage);
            progressBar.text(percentage + \"%\");
            if (percentage < 30) {
                progressText.text(\"Initialisation de l'analyse...\");
            } else if (percentage < 60) {
                progressText.text(\"Traitement des activités...\");
            } else if (percentage < 90) {
                progressText.text(\"Classification en cours...\");
            } else if (percentage < 100) {
                progressText.text(\"Finalisation...\");
            }
        }

        // Fonction pour simuler la progression
        function simulateProgress(duration = 3000) {
            return new Promise((resolve) => {
                let progress = 0;
                const interval = 50;
                const increment = 100 / (duration / interval);
                const timer = setInterval(() => {
                    progress += increment;
                    if (progress >= 95) {
                        progress = 95;
                        clearInterval(timer);
                        resolve();
                    }
                    updateProgressBar(Math.round(progress));
                }, interval);
            });
        }

        // Fonction pour afficher le message de fin
        function showCompletionMessage() {
            let messageContainer = \$(\"#completion-message\");
            if (messageContainer.length === 0) {
                messageContainer = \$(`
                    <div id=\"completion-message\" class=\"alert alert-success mt-3\" style=\"display: none;\">
                        <h5><i class=\"fas fa-check-circle\"></i> Analyse terminée</h5>
                        <p class=\"mb-0\">Veuillez vous rendre dans le menu <strong>Validation</strong> pour valider les propositions de l'IA.</p>
                    </div>
                `);
                \$(\"#progress-container\").after(messageContainer);
            }
            messageContainer.slideDown(500);
        }

       function displayIaResults(response) {
    const \$tbody = \$(\"#iaResultsBody\");
    \$tbody.empty();
    if (!response || !response.results || !Array.isArray(response.results)) {
        console.error(\"La réponse de l'API n'est pas valide :\", response);
        alert(\"La réponse de l'API n'est pas au format attendu.\");
        return;
    }

    response.results.forEach((result, index) => {
        const rowId = `ia_notation_\${index}`;

        // Options pour la nature
        const natureOptions = [
            { value: \"\", label: \"Choisir une nature\" },
            { value: \"1\", label: \"Consommation / Accès\" },
            { value: \"2\", label: \"Production / Offre\" },
            { value: \"3\", label: \"Habilitante / Capacitante\" },
            { value: \"4\", label: \"Soutien\" }
        ].map(opt =>
            `<option value=\"\${opt.value}\" \${opt.value == result.nature?.id ? 'selected' : ''}>\${opt.label}</option>`
        ).join('');

        // Options pour les ODD
        const oddOptions = [
            { value: \"\", label: \"Sélectionnez un ODD\" },
            { value: \"1\", label: \"1 - Pas de pauvreté\" },
            { value: \"2\", label: \"2 - Faim zéro\" },
            { value: \"3\", label: \"3 - Bonne santé et bien-être\" },
            { value: \"4\", label: \"4 - Éducation de qualité\" },
            { value: \"5\", label: \"5 - Égalité entre les sexes\" },
            { value: \"6\", label: \"6 - Eau propre et assainissement\" },
            { value: \"7\", label: \"7 - Énergie propre et d’un coût abordable\" },
            { value: \"8\", label: \"8 - Travail décent et croissance économique\" },
            { value: \"9\", label: \"9 - Industrie, innovation et infrastructure\" },
            { value: \"10\", label: \"10 - Inégalités réduites\" },
            { value: \"11\", label: \"11 - Villes et communautés durables\" },
            { value: \"12\", label: \"12 - Consommation et production responsables\" },
            { value: \"13\", label: \"13 - Mesures relatives à la lutte contre les changements climatiques\" },
            { value: \"14\", label: \"14 - Vie aquatique\" },
            { value: \"15\", label: \"15 - Vie terrestre\" },
            { value: \"16\", label: \"16 - Paix, justice et institutions efficaces\" },
            { value: \"17\", label: \"17 - Partenariats pour la réalisation des objectifs\" }
        ].map(opt =>
            `<option value=\"\${opt.value}\" \${opt.value == result.odd?.id ? 'selected' : ''}>\${opt.label}</option>`
        ).join('');

        // Options pour les cibles (exemple générique, à adapter selon vos données)
        const targetOptions = [
            { value: \"\", label: \"Sélectionnez une cible\" },
            { value: \"1\", label: \"Cible 1\" },
            { value: \"2\", label: \"Cible 2\" }
        ].map(opt =>
            `<option value=\"\${opt.value}\" \${opt.value == result.cible?.id ? 'selected' : ''}>\${opt.label}</option>`
        ).join('');

        const row = `
            <tr id=\"\${rowId}\">
                <!-- Champs cachés pour la logique du contrôleur -->
                <input type=\"hidden\" id=\"\${rowId}_targetRate\" name=\"ia_notation[\${index}][targetRate]\" value=\"\${result.targetRate || ''}\" />
                <input type=\"hidden\" id=\"\${rowId}_locationRate\" name=\"ia_notation[\${index}][locationRate]\" value=\"\${result.locationRate || ''}\" />
                <input type=\"hidden\" id=\"\${rowId}_sensitivity\" name=\"ia_notation[\${index}][sensitivity]\" value=\"\${result.sensitivity || ''}\" />

                <!-- Colonne 1 : Activité -->
                <td class=\"text-center\">
                    <div class=\"activity-col\" data-id=\"\${result.activityId || ''}\">\${result.activity || ''}</div>
                </td>

                <!-- Colonne 2 : Nature -->
                <td class=\"text-center\">
                    <select id=\"\${rowId}_nature\" name=\"ia_notation[\${index}][nature]\" class=\"form-control\" disabled>
                        \${natureOptions}
                    </select>
                </td>

                <!-- Colonne 3 : ODD / Cible -->
                <td>
                    <div class=\"mb-2\">
                        <strong>ODD :</strong>
                        <select id=\"\${rowId}_goal\" name=\"ia_notation[\${index}][goal]\" class=\"form-control\" disabled>
                            \${oddOptions}
                        </select>
                    </div>
                    <div>
                        <strong>Cible :</strong>
                        <select id=\"\${rowId}_target\" name=\"ia_notation[\${index}][target]\" class=\"form-control\" disabled>
                            \${targetOptions}
                        </select>
                    </div>
                </td>

                <!-- Colonne 4 : Indicateur(s) -->
                <td>
                    <select id=\"\${rowId}_indicators\" name=\"ia_notation[\${index}][indicators][]\" class=\"form-control\" multiple disabled>
                        \${result.indicators?.map(i => `<option value=\"\${i.id}\" selected>\${i.name}</option>`).join('') || ''}
                    </select>
                </td>

                <!-- Colonne 5 : Localisation -->
                <td>
                    <div class=\"mb-2\">
                        <select id=\"\${rowId}_locationType\" name=\"ia_notation[\${index}][locationType]\" class=\"form-control\">
                            <option value=\"department\" \${result.locationType === 'department' ? 'selected' : ''}>Département</option>
                        </select>
                    </div>
                    <div>
                        <select id=\"\${rowId}_communes\" name=\"ia_notation[\${index}][communes][]\" class=\"form-control\" multiple disabled>
                            \${result.communes?.map(c => `<option value=\"\${c.id}\" selected>\${c.name}</option>`).join('') || ''}
                        </select>
                    </div>
                </td>

                <!-- Colonne 6 : Mesure -->
                <td class=\"text-center\">
                    <input type=\"text\" id=\"\${rowId}_sensHtml\" name=\"ia_notation[\${index}][sensHtml]\" value=\"\${result.sensitivity || ''}\" disabled class=\"text-right form-control\" />
                    <button type=\"button\" class=\"btn btn-sm btn-success ia-apply-btn mt-2\" data-row-id=\"\${rowId}\">
                        <i class=\"fas fa-check\"></i> Appliquer
                    </button>
                </td>
            </tr>
        `;
        \$tbody.append(row);
    });
    \$(\"#ia-results-container\").show();
}

        // Gestion du clic sur le bouton \"Appliquer\"
       \$(document).on('click', '.ia-apply-btn', function() {
    const rowId = \$(this).data('row-id');
    const index = rowId.split('_')[1];

    // Copier la nature
    const natureValue = \$(`#\${rowId}_nature`).val();
    \$(`#notation_collection_model_notationModels_\${index}_nature`).val(natureValue).trigger('change');

    // Copier l'ODD
    const goalValue = \$(`#\${rowId}_goal`).val();
    \$(`#notation_collection_model_notationModels_\${index}_goal`).val(goalValue).trigger('change');

    // Copier la cible
    const targetValue = \$(`#\${rowId}_target`).val();
    \$(`#notation_collection_model_notationModels_\${index}_target`).val(targetValue).trigger('change');

    // Copier les indicateurs
    \$(`#\${rowId}_indicators option:selected`).each(function() {
        const indicatorValue = \$(this).val();
        \$(`#notation_collection_model_notationModels_\${index}_indicators option[value=\"\${indicatorValue}\"]`).prop('selected', true);
    });
    \$(`#notation_collection_model_notationModels_\${index}_indicators`).trigger('change');

    // Copier les communes
    \$(`#\${rowId}_communes option:selected`).each(function() {
        const communeValue = \$(this).val();
        \$(`#notation_collection_model_notationModels_\${index}_communes option[value=\"\${communeValue}\"]`).prop('selected', true);
    });
    \$(`#notation_collection_model_notationModels_\${index}_communes`).trigger('change');

    // Copier la mesure
    const sensitivityValue = \$(`#\${rowId}_sensitivity`).val();
    \$(`#notation_collection_model_notationModels_\${index}_sensitivity`).val(sensitivityValue);
    \$(`#notation_collection_model_notationModels_\${index}_sensHtml`).val(sensitivityValue);

    // Cocher la case \"traitée\"
    \$(`#notation_collection_model_notationModels_\${index}_treated`).prop('checked', true).trigger('change');

    // Message de confirmation
    alert(`Les résultats de l'IA pour l'activité \${index + 1} ont été appliqués.`);
});

        // Initialisation au chargement de la page
        window.onload = function() {
            \$(\"#notationTable tr.notation\").each(function() {
                let row = this.id;
                if (grouping == 'arrondissement') {
                    \$('#'+row+'_locationType').val('arrondissement');
                } else {
                    \$('#'+row+'_locationType').val('department');
                }
                locationTypeChange(row);
                calculTargetRate(row);
                calculLocationRate(row);
            });
        };

        // Gestion des changements de formulaire
        \$(document).on('change', '#notation_collection_model_type, #notation_collection_model_entite, #notation_collection_model_programm', function() {
            let \$type = \$('#notation_collection_model_type');
            let \$entite = \$('#notation_collection_model_entite');
            let \$form = \$(this).closest('form');
            let data = {};
            data[\$type.attr('name')] = \$type.val();
            data[\$entite.attr('name')] = \$entite.val();
            data[\$(this).attr('name')] = \$(this).val();
            let \$field = \$(this).attr('id');
            \$.ajax({
                url: \$form.attr('action'),
                type: \$form.attr('method'),
                data: data,
                success: function(html) {
                    if (\$field == 'notation_collection_model_type') {
                        \$('#notation_collection_model_entite').replaceWith(
                            \$(html).find('#notation_collection_model_entite')
                        );
                        \$('#notation_collection_model_programm').replaceWith(
                            \$(html).find('#notation_collection_model_programm')
                        );
                        \$('#notation_collection_model_action').replaceWith(
                            \$(html).find('#notation_collection_model_action')
                        );
                    }
                    if (\$field == 'notation_collection_model_entite') {
                        \$('#notation_collection_model_programm').replaceWith(
                            \$(html).find('#notation_collection_model_programm')
                        );
                        \$('#notation_collection_model_action').replaceWith(
                            \$(html).find('#notation_collection_model_action')
                        );
                    }
                    if (\$field == 'notation_collection_model_programm') {
                        \$('#notation_collection_model_action').replaceWith(
                            \$(html).find('#notation_collection_model_action')
                        );
                    }
                }
            });
        });

        // Gestion du clic sur le bouton Analyse IA
\$(\"#analyse-ia-btn\").on(\"click\", function() {
    const button = \$(this);
    button.prop('disabled', true).text('Analyse en cours...');
    
    let activities = collectActivities();
    if (activities.length === 0) {
        alert(\"Aucune activité trouvée pour l'analyse.\");
        button.prop('disabled', false).text('Analyse IA');
        return;
    }
    
    const progressContainer = createProgressBar();
    progressContainer.show();
    
    const progressPromise = simulateProgress(2000);
    const apiPromise = \$.ajax({
        url: \"http://127.0.0.1:5000/analyse-activities\",
        type: \"POST\",
        contentType: \"application/json\",
        data: JSON.stringify({ activities: activities }),
        timeout: 60000
    });
    
    Promise.all([progressPromise, apiPromise])
        .then(([_, response]) => {
            updateProgressBar(100);
            \$(\"#progress-text small\").text(\"Analyse terminée !\");
            displayIaResults(response);
            
            // 🔹 Envoyer les résultats à Symfony
            \$.ajax({
                url: \"";
        // line 663
        yield $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("save_ia_results");
        yield "\",
                type: \"POST\",
                contentType: \"application/json\",
                data: JSON.stringify(response),
                success: function(resp) {
                    console.log(\"Résultats sauvegardés côté Symfony:\", resp);
                    
                    // 🔹 REDIRECTION APRÈS SAUVEGARDE RÉUSSIE
                    setTimeout(() => {
                        progressContainer.fadeOut(500, () => {
                            // Redirection vers la page d'évaluation
                            window.location.href = \"";
        // line 674
        yield $this->env->getRuntime('Twig\Runtime\EscaperRuntime')->escape($this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("app_evaluation", ["id" => ($context["actionId"] ?? null)]), "html", null, true);
        yield "\";
                        });
                    }, 1500); // Délai pour laisser voir le message de succès
                },
                error: function(err) {
                    console.error(\"Erreur lors de l'enregistrement:\", err);
                    alert(\"Erreur lors de l'enregistrement des résultats. Redirection annulée.\");
                    
                    // On reste sur la page en cas d'erreur d'enregistrement
                    setTimeout(() => {
                        progressContainer.fadeOut(500, () => {
                            showCompletionMessage();
                        });
                    }, 1000);
                }
            });
        })
        .catch((error) => {
            console.error(\"Erreur Ajax:\", error);
            let errorMessage = \"Erreur lors de l'analyse IA\";
            if (error.status === 0) {
                errorMessage = \"Impossible de contacter l'API. Vérifiez que l'API est démarrée.\";
            } else if (error.status === 500) {
                errorMessage = \"Erreur serveur dans l'API\";
            } else if (error.status === 404) {
                errorMessage = \"Route non trouvée dans l'API\";
            }
            progressContainer.hide();
            alert(errorMessage + \" (Code: \" + error.status + \")\");
        })
        .finally(() => {
            button.prop('disabled', false).text('Analyse IA');
        });
});

    </script>

    <script src=\"";
        // line 711
        yield $this->env->getRuntime('Twig\Runtime\EscaperRuntime')->escape($this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("plugins/datatables/jquery.dataTables.js"), "html", null, true);
        yield "\"></script>
    <script src=\"";
        // line 712
        yield $this->env->getRuntime('Twig\Runtime\EscaperRuntime')->escape($this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("plugins/datatables-bs4/js/dataTables.bootstrap4.js"), "html", null, true);
        yield "\"></script>
    <script>
        \$(function() {
            \$(\"#notationTable\").DataTable({
                \"pageLength\": 100
            });
        });
    </script>
";
        yield from [];
    }

    /**
     * @codeCoverageIgnore
     */
    public function getTemplateName(): string
    {
        return "plan/notation_form_ia.html.twig";
    }

    /**
     * @codeCoverageIgnore
     */
    public function isTraitable(): bool
    {
        return false;
    }

    /**
     * @codeCoverageIgnore
     */
    public function getDebugInfo(): array
    {
        return array (  782 => 712,  778 => 711,  738 => 674,  724 => 663,  153 => 95,  146 => 90,  139 => 89,  116 => 71,  109 => 70,  101 => 67,  97 => 65,  95 => 64,  92 => 63,  87 => 60,  84 => 26,  82 => 25,  79 => 24,  77 => 6,  72 => 5,  65 => 4,  54 => 2,  43 => 1,);
    }

    public function getSourceContext(): Source
    {
        return new Source("", "plan/notation_form_ia.html.twig", "/var/www/html/templates/plan/notation_form_ia.html.twig");
    }
}


/* plan/notation_form_ia.html.twig */
class __TwigTemplate_2f4b0f4efa317bc9eaad95f64bea61b2___2010894353 extends Template
{
    private Source $source;
    /**
     * @var array<string, Template>
     */
    private array $macros = [];

    public function __construct(Environment $env)
    {
        parent::__construct($env);

        $this->source = $this->getSourceContext();

        $this->blocks = [
            'box_body' => [$this, 'block_box_body'],
        ];
    }

    protected function doGetParent(array $context): bool|string|Template|TemplateWrapper
    {
        // line 6
        return "@AdminLTE/Widgets/box-widget.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        $this->parent = $this->load("@AdminLTE/Widgets/box-widget.html.twig", 6);
        yield from $this->parent->unwrap()->yield($context, array_merge($this->blocks, $blocks));
    }

    // line 7
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_box_body(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        // line 8
        yield "            <div class=\"text-right\">
                <a href=\"";
        // line 9
        yield $this->env->getRuntime('Twig\Runtime\EscaperRuntime')->escape($this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("app_evaluation", ["id" => ($context["actionId"] ?? null)]), "html", null, true);
        yield "\" class=\"btn btn-primary\">
                    ";
        // line 10
        yield $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("basics.appreciation", [], "messages");
        yield "  <i class=\"fas fa-angle-double-right\"></i>
                </a>
            </div><br>
            ";
        // line 13
        if ((($tmp = $this->extensions['Symfony\Bridge\Twig\Extension\SecurityExtension']->isGranted("ROLE_MANAGER")) && $tmp instanceof Markup ? (string) $tmp : $tmp)) {
            // line 14
            yield "                ";
            yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "type", [], "any", false, false, false, 14), 'row');
            yield "
                ";
            // line 15
            yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "entite", [], "any", false, false, false, 15), 'row');
            yield "
            ";
        }
        // line 17
        yield "            ";
        if ((($tmp = $this->extensions['Symfony\Bridge\Twig\Extension\SecurityExtension']->isGranted("ROLE_DDD")) && $tmp instanceof Markup ? (string) $tmp : $tmp)) {
            // line 18
            yield "                ";
            yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "entite", [], "any", false, false, false, 18), 'row');
            yield "
            ";
        }
        // line 20
        yield "            ";
        yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "programm", [], "any", false, false, false, 20), 'row');
        yield "
            ";
        // line 21
        yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "action", [], "any", false, false, false, 21), 'row');
        yield "
        ";
        yield from [];
    }

    /**
     * @codeCoverageIgnore
     */
    public function getTemplateName(): string
    {
        return "plan/notation_form_ia.html.twig";
    }

    /**
     * @codeCoverageIgnore
     */
    public function isTraitable(): bool
    {
        return false;
    }

    /**
     * @codeCoverageIgnore
     */
    public function getDebugInfo(): array
    {
        return array (  906 => 21,  901 => 20,  895 => 18,  892 => 17,  887 => 15,  882 => 14,  880 => 13,  874 => 10,  870 => 9,  867 => 8,  860 => 7,  849 => 6,  782 => 712,  778 => 711,  738 => 674,  724 => 663,  153 => 95,  146 => 90,  139 => 89,  116 => 71,  109 => 70,  101 => 67,  97 => 65,  95 => 64,  92 => 63,  87 => 60,  84 => 26,  82 => 25,  79 => 24,  77 => 6,  72 => 5,  65 => 4,  54 => 2,  43 => 1,);
    }

    public function getSourceContext(): Source
    {
        return new Source("", "plan/notation_form_ia.html.twig", "/var/www/html/templates/plan/notation_form_ia.html.twig");
    }
}


/* plan/notation_form_ia.html.twig */
class __TwigTemplate_2f4b0f4efa317bc9eaad95f64bea61b2___2042409447 extends Template
{
    private Source $source;
    /**
     * @var array<string, Template>
     */
    private array $macros = [];

    public function __construct(Environment $env)
    {
        parent::__construct($env);

        $this->source = $this->getSourceContext();

        $this->blocks = [
            'box_body' => [$this, 'block_box_body'],
        ];
    }

    protected function doGetParent(array $context): bool|string|Template|TemplateWrapper
    {
        // line 26
        return "@AdminLTE/Widgets/box-widget.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        $this->parent = $this->load("@AdminLTE/Widgets/box-widget.html.twig", 26);
        yield from $this->parent->unwrap()->yield($context, array_merge($this->blocks, $blocks));
    }

    // line 27
    /**
     * @return iterable<null|scalar|\Stringable>
     */
    public function block_box_body(array $context, array $blocks = []): iterable
    {
        $macros = $this->macros;
        // line 28
        yield "            ";
        // line 29
        $this->env->getRuntime("Symfony\\Component\\Form\\FormRenderer")->setTheme(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "notationModels", [], "any", false, false, false, 29), ["form/notation.html.twig"], true);
        // line 32
        yield "            ";
        yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(($context["form"] ?? null), 'errors');
        yield "
            <table id=\"notationTable\" class=\"table table-striped notation-collection\">
                <div class=\"text-right\">
                    <button id=\"analyse-ia-btn\" type=\"button\" class=\"btn btn-primary\">
                        ";
        // line 36
        yield $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("basics.analyseia", [], "messages");
        yield " <i class=\"fas fa-angle-double-right\"></i>
                    </button>
                </div><br>
                <thead>
                    <th class=\"row\">
                        <div class=\"col-2 text-center\">Nature</div>
                        <div class=\"col-6 text-center\">ODD / Cible / Indicateur</div>
                        <div class=\"col-3 text-center\">Localisation</div>
                        <div class=\"col-1 text-center\">Mesure</div>
                    </th>
                </thead>
                <tbody>
                    ";
        // line 48
        $context["index"] = 0;
        // line 49
        yield "                    ";
        $context['_parent'] = $context;
        $context['_seq'] = CoreExtension::ensureTraversable(CoreExtension::getAttribute($this->env, $this->source, ($context["form"] ?? null), "notationModels", [], "any", false, false, false, 49));
        foreach ($context['_seq'] as $context["_key"] => $context["notation"]) {
            // line 50
            yield "                        ";
            yield $this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock($context["notation"], 'row', ["activity" => (($_v0 =             // line 51
($context["activities"] ?? null)) && is_array($_v0) || $_v0 instanceof ArrayAccess ? ($_v0[($context["index"] ?? null)] ?? null) : null), "activityId" => (($_v1 =             // line 52
($context["activityIds"] ?? null)) && is_array($_v1) || $_v1 instanceof ArrayAccess ? ($_v1[($context["index"] ?? null)] ?? null) : null)]);
            // line 53
            yield "
                        ";
            // line 54
            $context["index"] = (($context["index"] ?? null) + 1);
            // line 55
            yield "                    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_key'], $context['notation'], $context['_parent']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 56
        yield "                </tbody>
            </table>
        ";
        yield from [];
    }

    /**
     * @codeCoverageIgnore
     */
    public function getTemplateName(): string
    {
        return "plan/notation_form_ia.html.twig";
    }

    /**
     * @codeCoverageIgnore
     */
    public function isTraitable(): bool
    {
        return false;
    }

    /**
     * @codeCoverageIgnore
     */
    public function getDebugInfo(): array
    {
        return array (  1034 => 56,  1028 => 55,  1026 => 54,  1023 => 53,  1021 => 52,  1020 => 51,  1018 => 50,  1013 => 49,  1011 => 48,  996 => 36,  988 => 32,  986 => 29,  984 => 28,  977 => 27,  966 => 26,  906 => 21,  901 => 20,  895 => 18,  892 => 17,  887 => 15,  882 => 14,  880 => 13,  874 => 10,  870 => 9,  867 => 8,  860 => 7,  849 => 6,  782 => 712,  778 => 711,  738 => 674,  724 => 663,  153 => 95,  146 => 90,  139 => 89,  116 => 71,  109 => 70,  101 => 67,  97 => 65,  95 => 64,  92 => 63,  87 => 60,  84 => 26,  82 => 25,  79 => 24,  77 => 6,  72 => 5,  65 => 4,  54 => 2,  43 => 1,);
    }

    public function getSourceContext(): Source
    {
        return new Source("", "plan/notation_form_ia.html.twig", "/var/www/html/templates/plan/notation_form_ia.html.twig");
    }
}
