{% extends 'base.html.twig' %}

{% block pagewrapper %}
{{ form_start(form) }}
    <h1 class="page-title">
    {% if mode=="update" %}
        {% if access=="config" %}
            Modification Utilisateur = {{ user.username}}
        {% else %}
            Profil
        {% endif %}
    {% elseif mode=="submit" %}
    Création Utilisateur
    {% elseif mode=="delete" %}
    Suppression Utilisateur
    {% endif %}
    </h1>

    {{ form_widget(form.submit) }}
    {% if access=="config" %}
        <a class="btn btn-secondary" href={{ path('app_core_config_user') }}>Annuler</a>
    {% endif %}
    <br><br>
    

    {% if app.session.flashbag.has('error') %}
        <div class='alert alert-danger' style='margin: 5px 0px'>
            <strong>Erreur</strong><br>
            {% for flashMessage in app.session.flashbag.get('error') %}
                {{ flashMessage | raw }}<br>
            {% endfor %}
        </div>
        <br>
    {% endif %}

    {% if app.session.flashbag.has('notice') %}
        <div class='alert alert-info' style='margin: 5px 0px'>
            <strong>Information</strong><br>
            {% for flashMessage in app.session.flashbag.get('notice') %}
                {{ flashMessage | raw }}<br>
            {% endfor %}
        </div>
        <br>
    {% endif %}

    {% if info is defined and info %}
        <div class='alert alert-info' style='margin: 5px 0px'>
            <strong>Information</strong><br>
            {{ info | raw }}<br>
        </div>
        <br>
    {% endif %}


    <div class="row">
        <div class="col-md-12 text-center" style="margin:auto;">
            {% set avatar= "noavatar.png" %}
            {% if user.avatar %}
                {% set avatar= user.avatar %}
            {% endif %}
            <img id="user_avatar_img" src="{{ asset('uploads/avatar/' ~ avatar) }}" class="avatar big" >
            {{ form_widget(form.avatar) }}
            <br>
            <a class="btn btn-info" style="max-width:100%; margin-bottom:15px;" data-bs-toggle="modal" data-bs-target="#mymodal" onClick="ModalLoad('mymodal','Avatar','{{ path('app_core_crop01') }}');" title='Ajouter un avatar'>Modifier</a>
        </div>

        {% if access=="config" %}
            <div class="col-md-12 mb-3">
                <div class="card">
                    <div class="card-header">
                        <i class="fa fa-key fa-fw"></i> Notes Administrateur
                    </div>           
                    <div class="card-body">     
                        {{ form_widget(form.note) }}
                    </div>
                </div>
            </div>
        {%endif%}

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fa fa-key fa-fw"></i> Connexion
                </div>

                <div class="card-body">
                    {{ form_row(form.username) }}

                    <div class='alert alert-info' style='font-size: 80%;padding: 5px;margin-top: -10px;'>
                        Formatez votre login sous la forme prenom.nom dans la mesure du possible<br>
                        Taille minimum = 5 caractères<br>
                        Caractères interdits = accent, espace, caractères spéciaux sauf @ . - _<br>
                    </div>

                    {% if form.password is defined %}
                        {{ form_row(form.password) }}
                        <div class='alert alert-info' style='font-size: 80%;padding: 5px;margin-top: -10px;'>
                            Le mot de passe doit comporter au moins {{ minpassword }} caractères, avec obligatoirement des lettres, chiffres et caractères spéciaux.
                        </div>                         
                    {% endif %}

                    {% if form.role is defined %}
                        {{ form_row(form.role) }}
                        <div id='blockpermmodoprofil'>{{ form_row(form.permmodoprofil) }}</div>  
                    {% endif %}                       
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fa fa-pencil-alt fa-fw"></i> Informations
                </div>

                <div class="card-body">
                    {% if form.firstname is defined %} {{ form_row(form.firstname) }} {% endif %}
                    {{ form_row(form.lastname) }}
                    {{ form_row(form.email) }}
                    {% if form.visible is defined %}
                        {{ form_row(form.visible) }}
                        <div class='alert alert-info' style='font-size: 80%;padding: 5px;margin-top: -10px;'>
                            Le champ <b>Visible</b> vous permet d'indiquer que vous ne souhaitez pas que d'autres utilisateurs puissent voir votre profil.<br>
                            Si vous placer ce champ à non :
                            <li>Vous n'apparetrez pas dans l'annuaire</li>
                            <li>Dans les groupes de travail, les autres membres du groupe ne pourront pas voir en détail  votre profil</li>
                        </div>
                    {% endif %}
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fa fa-pencil-alt fa-fw"></i> Motivations
                </div>

                <div class="card-body">
                    {{ form_row(form.motivation) }}
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fa fa-sitemap fa-fw"></i> Organisation
                </div>
                <div class="card-body">
                     {% if form.job is defined %}{{ form_row(form.job) }}{% endif %}
                     {% if form.position is defined %}{{ form_row(form.position) }}{% endif %}
                     {{ form_row(form.niveau01) }}
                     <div id="niveau01other">{{ form_row(form.niveau01other) }}</div>
                     {% if form.niveau02 is defined %}{{ form_row(form.niveau02) }}{% endif %}
                </div>
            </div>

            {% if access=="config" %}
            <div id="cardopenid" class="card">
                <div class="card-header">
                    <i class="fa fa-key fa-fw"></i> OpenID
                </div>

                <div class="card-body">
                    {% if form.authlevel is defined %}{{ form_row(form.authlevel) }}{% endif %}
                    {% if form.belongingpopulation is defined %}{{ form_row(form.belongingpopulation) }}{% endif %}
                </div>
            </div>    
             {% endif %}        
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fa fa-users fa-fw"></i> Groupes
                </div>

                <div class="card-body">
                    <a class="btn btn-success" data-bs-toggle="modal" data-bs-target="#groupmodal" title='Ajouter'>Inscription à un Groupe</a>
                    <br><br>

                    
                    {{ form_widget(form.linkgroups) }}

                    <div class="dataTable_wrapper">
                        <table id="tbllinkgroup" class="table table-striped table-bordered table-hover" style="width:100%">
                            <thead>
                            <tr>
                                <th width="70px">Action</th>
                                <th>Groupe</th>
                            </tr>
                            </thead>

                            <tbody>
                            {% for group in user.groups %}
                                <tr id="linkgroup{{ group.group.id }}">
                                    {% set canleave = true %}
                                    {% if group.group.fgtemplate or group.group.fgall or group.group.owner==user %}
                                        {% set canleave = false %}
                                    {% elseif access!="config" %}
                                        {% if not group.group.fgcanshare and not group.group.fgopen %}
                                            {% set canleave = false %}
                                        {% elseif group.group.fgcanshare and not app.session.get('permunsubscribe') and not group.group.fgopen %}
                                            {% set canleave = false %}
                                        {% endif %}
                                    {% endif %}

                                    {% if canleave  %}
                                        <td><a style="cursor:pointer" title="Se Désinscrire"><i class="fa fa-sign-out-alt fa-fw" onclick="removeLinkGroup({{ group.group.id }})"></i></a></td>
                                    {% else %}
                                        <td></td>                                    
                                    {% endif %}
                                    
                                    <td>
                                        {{ group.group.label }}
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div id="cardmodos" class="card">
                <div class="card-header">
                    <i class="fa fa-users fa-fw"></i> {{ labelsniveau01 }} Modérés
                </div>

                <div class="card-body">
                    {% if is_granted('ROLE_ADMIN') %} 
                    <a class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modomodal" title='Ajouter'>Ajouter</a>
                    <br><br>
                    {% endif %}
                    
                    {{ form_widget(form.linkmodos) }}

                    <div class="dataTable_wrapper">
                        <table id="tbllinkmodo" class="table table-striped table-bordered table-hover" style="width:100%">
                            <thead>
                            <tr>
                                {% if is_granted('ROLE_ADMIN') %} 
                                <th width="70px">Action</th>
                                {% endif %} 
                                <th>{{ labelniveau01 }}</th>
                            </tr>
                            </thead>

                            <tbody>
                            {% for modo in user.modos %}
                                <tr id="linkmodo{{ modo.niveau01.id }}">
                                    {% if is_granted('ROLE_ADMIN') %} 
                                    <td><a style="cursor:pointer"><i class="fa fa-trash fa-fw" onclick="removeLinkModo({{ modo.niveau01.id }})"></i></a></td>                                  
                                    {% endif %} 
                                    <td>
                                        {{ modo.niveau01.label }}
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div id="cardoption" class="card">
                <div class="card-header">
                    <i class="fa fa-user fa-fw"></i> Optionnel
                </div>

                <div class="card-body">
                    {% if form.usualname is defined and form.gender is defined%}
                    <div class="row">
                    
                    <div class="col-xs-8">
                    {{ form_row(form.usualname) }} 
                    </div>
                    <div class="col-xs-4">
                    {{ form_row(form.gender) }}
                    </div>
                    </div>
                    {% elseif form.usualname is defined %} {{ form_row(form.usualname) }} 
                    {% elseif form.gender is defined %} {{ form_row(form.gender) }} 
                    {% endif %}

                    {% if form.givensname is defined %} {{ form_row(form.givensname) }} {% endif %}
                    {% if form.telephonenumber is defined %} {{ form_row(form.telephonenumber) }} {% endif %}
                    {% if form.postaladress is defined %} {{ form_row(form.postaladress) }} {% endif %}

                    {% if form.birthdate is defined and form.birthdate is defined%}
                    <div class="row">
                    <div class="col-xs-4">
                    {{ form_row(form.birthdate) }}
                    </div>
                    <div class="col-xs-8">
                    {{ form_row(form.birthcountry) }}
                    </div>
                    </div>
                    {% elseif form.birthdate is defined %} {{ form_row(form.birthdate) }} 
                    {% elseif form.birthcountry is defined %} {{ form_row(form.birthcountry) }} 
                    {% endif %}

                    <div id="blockcity">
                    {% if form.birthplace is defined %} {{ form_row(form.birthplace) }} {% endif %}
                    </div>
                </div>
            </div>

            {% if form.visitedate is defined %}
            <div id="cardvisite" class="card">
                <div class="card-header">
                    <i class="fa fa-user fa-fw"></i> Visite
                </div>

                <div class="card-body">
                    {{ form_row(form.visitedate) }}
                    {{ form_row(form.visitecpt) }}
                </div>
            </div>
            {% endif %}

        </div>
    </div>


    <div id="groupmodal" class="modal fade bs-item-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">AJOUTER UN GROUPE</h4>
                </div>

                <div class="modal-body">
                    <a class="btn btn-success" onclick="$('#groupmodal').modal('hide');" title='Fermer'>Fermer</a>
                    <br><br>
                    <div class="dataTable_wrapper">
                        <table id="tbllistgroup" class="table table-striped table-bordered table-hover" style="width:100%">
                            <thead>
                            <tr>
                                <th width="70px" class="no-sort">Action</th>
                                <th>Groupe</th>
                            </tr>
                            </thead>

                            <tbody>
                            {% set listidgroup = [] %}
                            {% for group in user.groups %}
                                {% set listidgroup = listidgroup|merge([group.group.id]) %}
                            {% endfor %}

                            {% for group in listgroups %}
                                {% if group.id in listidgroup %}
                                    {% set style = "display:none;" %}
                                {% else %}
                                    {% set style = "" %}
                                {% endif %}

                                <tr id="listgroup{{ group.id }}" style="{{ style }}">
                                    <td width="70px"><a style="cursor:pointer"><i class="fa fa-plus fa-fw" onclick="addLinkGroup({{ group.id }})"></i></a></td>
                                    <td id="listgrouplabel{{ group.id }}">
                                        {{ group.label }}
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="modomodal" class="modal fade bs-item-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">AJOUTER {{ labelniveau01|upper }} A MODERER</h4>
                </div>

                <div class="modal-body">
                    <a class="btn btn-success" onclick="$('#modomodal').modal('hide');" title='Fermer'>Fermer</a>
                    <br><br>
                    <div class="dataTable_wrapper">
                        <table id="tbllistmodo" class="table table-striped table-bordered table-hover" style="width:100%">
                            <thead>
                            <tr>
                                <th width="70px">Action</th>
                                <th>{{ labelniveau01 }}</th>
                            </tr>
                            </thead>

                            <tbody>
                            {% set listidmodo = [] %}
                            {% for modo in user.modos %}
                                {% set listidmodo = listidmodo|merge([modo.niveau01.id]) %}
                            {% endfor %}

                            {% for modo in listmodos %}
                                {% if modo.id in listidmodo %}
                                    {% set style = "display:none;" %}
                                {% else %}
                                    {% set style = "" %}
                                {% endif %}

                                <tr id="listmodo{{ modo.id }}" style="{{ style }}">
                                    <td><a style="cursor:pointer"><i class="fa fa-plus fa-fw" onclick="addLinkModo({{ modo.id }})"></i></a></td>
                                    <td id="listmodolabel{{ modo.id }}">
                                        {{ modo.label }}
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

{{ form_end(form) }}
{% endblock %}

{% block localjavascript %}
    $(document).ready(function() {
        {% if access=="user" %}
            {% set color = app.session.get('color') %}
            $(".sidebar").remove();
            $("body").removeClass("body");
            $("body").addClass("simple");
            $("body").attr('style', 'background-color: #{{ color['colorbody'] }} !important');
            $("#page-wrapper").css("margin","auto");
            $("#page-wrapper").css("border-left","none");
            
        {% endif %}

        // Vider le password
        $("#user_password_first").val("");

        if(!$("#cardopenid").find(".card-body").find("label").length) $("#cardopenid").hide();
        if(!$("#cardoption").find(".card-body").find("label").length) $("#cardoption").hide();

        // Afficher / Masquer
        hideshow();
    });

    $("#user_avatar_img").on("error",function(){
        var imgSrc = $(this).attr('src');
        if(imgSrc!="{{ asset("uploads/avatar/") }}")
            $(this).attr('src',imgSrc);
    });

    $(document.body).on("change","#user_birthcountry",function(){
        hideshow();
    });

    $(document.body).on("change","#user_role",function(){
        hideshow();
    });

    $(document.body).on("change","#user_niveau01",function(){
        hideshow();
    });

    $(document.body).on("change","#user_niveau02",function(){
        $.ajax({
            method: "POST",
            url: "{{ path('app_core_ajax_niveau02_read') }}",
            data: "id="+$("#user_niveau02").val(),
            success: function(data, dataType)
            {
                $("#user_postaladress").val(data[0]);
            },

            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                
            }
        });        
    });

    function hideshow() {
        if($("#user_birthcountry").val()==269)
            $("#blockcity").show();
        else {
            $("#blockcity").hide();
            $("#user_birthplace").val([]).trigger('change');
        }

        if($("#user_role").val()=="ROLE_MODO" ) {
            $("#cardmodos").show();
            $("#blockpermmodoprofil").show();
        }
        else {
            $("#cardmodos").hide();
            $("#blockpermmodoprofil").hide();
        }        

        niveau01=$("#user_niveau01 option:selected").text().toLowerCase();
        if(niveau01.startsWith("autre")) {
            $("#niveau01other").show();
        }
        else {
            $("#user_niveau01other").val("");
            $("#niveau01other").hide();
        }        
    }


    $(document).ready(function() {
        // Init Group
        var linkgroups="";
        {% for group in user.groups %}
            linkgroups+={{ group.group.id }}+",";
        {% endfor %}
        $("#user_linkgroups").val(linkgroups); 

        // Init Modo
        var linkmodos="";
        {% for modo in user.modos %}
            linkmodos+={{ modo.niveau01.id }}+",";
        {% endfor %}
        $("#user_linkmodos").val(linkmodos);         

        $('#tbllistgroup').DataTable({
            columnDefs: [ { "targets": 'no-sort', "orderable": false },{ "targets": 'no-visible', "visible": false } ],
            responsive: true,
            iDisplayLength: 100,
            processing: true,
            order: [[ 1, "asc" ]],
        });
    });

    function removeLinkGroup(id) {
        if (confirm("Désirez vous vraiment vous désinscrire de ce groupe ?")) {
            // On supprime la ligne du tableau
            $("#linkgroup"+id).remove();

            // On supprime l'id de la liste
            $("#user_linkgroups").val($("#user_linkgroups").val().replace(id+",",""));

            // On rend visible la ligne de liste complète
            $("#listgroup"+id).show();

            {% if mode=="update" and access!="config" %}
                if (typeof window.triggerSonde === 'function') {
                    window.triggerSonde({
                        rubrique: 'Mes Groupes',
                        page: 'SUPPRESSION_Groupe-Travail',
                    })
                }            
            {% endif %}
        }
    }

    function addLinkGroup(id) {
        // On cache la ligne du tableau
        $("#listgroup"+id).hide();

        // On ajoute l'id de la liste
        $("#user_linkgroups").val($("#user_linkgroups").val()+id+",");

        // On ajoute la ligne de liste des liens
        html ="<tr id='linkgroup"+id+"'>";
        html+="<td><a style='cursor:pointer' title='Se Désinscrire'><i class='fa fa-sign-out-alt fa-fw' onclick='removeLinkGroup("+id+")'></i></a></td>";
        html+="<td>"+$("#listgrouplabel"+id).html()+"</td>";
        html+="</tr>";

        $('#tbllinkgroup .dataTables_empty').remove();
        $('#tbllinkgroup > tbody').append(html);

        {% if mode=="update" and access!="config" %}
            if (typeof window.triggerSonde === 'function') {
                window.triggerSonde({
                    rubrique: 'Mes Groupes',
                    page: 'CREATION_Groupe-Travail',
                })
            }            
        {% endif %}

        // On ferme automatiquement la modal s'il n'y a plus de ligne dans le tableau
        if($("#tbllistgroup tr:visible").length==1) {
            $("#groupmodal").modal('hide');
        }
    }

    function removeLinkModo(id) {
        // On supprime la ligne du tableau
        $("#linkmodo"+id).remove();

        // On supprime l'id de la liste
        $("#user_linkmodos").val($("#user_linkmodos").val().replace(id+",",""));

        // On rend visible la ligne de liste complète
        $("#listmodo"+id).show();
    }

    function addLinkModo(id) {
        // On cache la ligne du tableau
        $("#listmodo"+id).hide();

        // On ajoute l'id de la liste
        $("#user_linkmodos").val($("#user_linkmodos").val()+id+",");

        // On ajoute la ligne de liste des liens
        html ="<tr id='linkmodo"+id+"'>";
        html+="<td><a style='cursor:pointer'><i class='fa fa-trash fa-fw' onclick='removeLinkModo("+id+")'></i></a></td>";
        html+="<td>"+$("#listmodolabel"+id).html()+"</td>";
        html+="</tr>";

        $('#tbllinkmodo .dataTables_empty').remove();
        $('#tbllinkmodo > tbody').append(html);

        // On ferme automatiquement la modal s'il n'y a plus de ligne dans le tableau
        if($("#tbllistmodo tr:visible").length==1) {
            $("#modomodal").modal('hide');
        }
    }    

    {% if mode=="update" and access!="config" %}
        $('form[name="user"]').on('submit', function (e) {
            var $form = $(this);
            var $submitBtn = $('#user_submit'); // On cible ton bouton par son ID
            
            // Si on a déjà validé la sonde, on laisse passer l'envoi normal
            if ($form.data('sonde-done')) {
                return true; 
            }

            e.preventDefault();
            console.log("Interception sonde...");

            if (typeof window.triggerSonde === 'function') {
                window.triggerSonde({
                    rubrique: 'Mon profil',
                    page: 'MODIFICATION_Mon-profil',
                }).finally(function() {
                    console.log("Sonde terminée, relance de l'envoi...");
                    
                    // 1. On marque le formulaire comme "prêt"
                    $form.data('sonde-done', true);
                    
                    // 2. On désactive l'interception actuelle pour éviter la boucle
                    $form.off('submit');
                    
                    // 3. On simule un clic réel sur le bouton de soumission
                    // Cela garantit que name="user[submit]" est bien envoyé au contrôleur
                    $submitBtn.click();
                });
            } else {
                $form.off('submit');
                $submitBtn.click();
            }
        });    
    {% endif %}
{% endblock %}
