{% extends 'Admin/layout.html.twig' %}
{%- import 'Admin/Form/macros.html.twig' as m -%}

{% trans_default_domain 'form' %}

{% set userTypeTeacher = constant('AppBundle\\Enum\\UserType::TEACHER') %}
{% set userTypeEngineer = constant('AppBundle\\Enum\\UserType::ENGINEER') %}

{% block javascripts %}
    <!-- Google Maps JavaScript API v3 key -->
    <script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_id }}"></script>
    <script>
        //<![CDATA[
        $(function() {
            var geocoder = new google.maps.Geocoder();
            var fieldPrefix = '#user_form_';

            $('.geocode').on('click', function(event){
                event.preventDefault();
                switch($(this).data('name'))
                {
                    case "int_perso":
                        console.log('geocode perso');
                        initAddressGeocoding(
                            ['personalZipcode', 'personalCity'],
                            'personalLatitude',
                            'personalLongitude'
                        );
                        break;

                    case "int_comp":
                        initAddressGeocoding(
                            ['establishmentAddress', 'establishmentZipcode', 'establishmentCity'],
                            'latitude',
                            'longitude'
                        );
                        break;

                    case "teach_perso":

                        break;

                    case "teach_est":

                        break;
                }
            });

            function isZipcodeFR(x) {
                return /^([0-9]{5})$/.test(x);
            }
    
            function getCountryByZipcode(x) {
                
                var country;
    
                switch (x.substr(0, 3)) {
                    case "971" : 
                                country = "Guadeloupe"; break; 	
                    case "973" : 
                                country = "Guyane"; break; 	
                    case "975" : 
                                country = "St-Pierre-et-Miquelon"; break;
                    case "972" : 
                                country = "Martinique"; break; 	
                    case "974" : 
                                country = "La Réunion"; break; 	
                    case "976" : 
                                country = "Mayotte"; break;
                    case "984" : 
                                country = "Terres-Australes et Antarctiques"; break; 	
                    case "987" : 
                                country = "Polynésie Française"; break;
                    case "986" : 
                                country = "Wallis-et-Futuna"; break; 	
                    case "988" : 
                                country = "Nouvelle-Calédonie"; break;
                    default :
                                country = "France"; break;
                }
                
                return country;
            }

            /**
            * Build an addresse from form fields.
            * Field's name are deduced from the given properties.
            */
            function buildAddress(properties) {
                var address = [];
                var country = '';

                for (var i = 0; i < properties.length; i++) {
                    address.push($(fieldPrefix + properties[i]).val());

                    if (isZipcodeFR($(fieldPrefix + properties[i]).val())) {
                        country = getCountryByZipcode($(fieldPrefix + properties[i]).val());
                    }
                }

                if (country !== '') {
                    address.push(country);
                }

                return address;
            }

            /**
            * Geocode an address, and update the form fields if the geocoding was successful
            */
            function geocode(address, latPropertyName, lngPropertyName) {
                var lat, lng;

                geocoder.geocode({'address': address.join(' ')}, function (results, status) {
                    console.log('Start geocoding');
                    if (status == google.maps.GeocoderStatus.OK) {
                        console.log('API OK');
                        lat = results[0].geometry.location.lat();
                        lng = results[0].geometry.location.lng();

                        // Update hidden fields with coordinates found
                        $(fieldPrefix + latPropertyName).val(lat);
                        $(fieldPrefix + lngPropertyName).val(lng);
                    }
                    else{
                        console.log('geocoding falied');
                    }
                });
            }

            /**
            * Initialize the address geocoding:
            * 1. React on the 'blur' form event of the fields
            * 2. Validate the adress
            * 3. Geocode the address
            * 4. Fill the appropriate fields with the coordinates
            */
            function initAddressGeocoding(properties, latPropertyName, lngPropertyName) {
                console.log('init address');
                // Build form field names from the property names
                var fields = properties.map(function(property) {
                    return fieldPrefix + property;
                });

                // 1. React on the 'change' (legacy of blur : cause limit API quota) form event of the fields
                // $(fields.join(',')).on('change', function() {
                    var address = buildAddress(properties);

                    // 2. Validate the adress: every part of the address must be at least 1 character long
                    var triggerGeocoding = address.every(function(adr) { return adr.length > 0});

                    if (triggerGeocoding) {
                        // 3. Geocode the address
                        // 4. Fill the appropriate fields with the coordinates
                        geocode(address, latPropertyName, lngPropertyName);
                    };
                // });
            }

            

            
        });
        //]]>
    </script>
    <script>
        //<![CDATA[
        $(function() {
            var establishmentNameField = $('#user_form_establishmentName'),
                establishmentNameLbl = establishmentNameField.closest('.form-row').find('.form-row-label label'),
                establishmentNameOtherField = $('#user_form_establishmentNameOther'),
                establishmentNameOtherLbl = establishmentNameOtherField.closest('.form-row').find('.form-row-label label');

            function toggleNameFieldsRequired(name_required)
            {
                if (name_required) {
                    establishmentNameField.focus();
                    establishmentNameField.attr('required', 'required');
                    establishmentNameLbl.addClass('required');

                    establishmentNameOtherField.val('');
                    establishmentNameOtherField.removeAttr('required');
                    establishmentNameOtherLbl.removeClass('required');
                } else {
                    establishmentNameOtherField.focus();
                    establishmentNameOtherField.attr('required', 'required');
                    establishmentNameOtherLbl.addClass('required');

                    establishmentNameField.val('');
                    establishmentNameField.removeAttr('required');
                    establishmentNameLbl.removeClass('required');
                }
            }

            toggleNameFieldsRequired(true);

            establishmentNameField.on('change', function () {
                toggleNameFieldsRequired(
                    ($(this).val().length > 0)
                );
            });

            establishmentNameOtherField.on('change', function () {
                toggleNameFieldsRequired(
                    !($(this).val().length > 0)
                );
            });
        });
        //]]>
    </script>
{% endblock javascripts %}

{% block body %}
    <header>
        <ul class="btns">
            <li class="btns-back">
                {{ m.step_back() }}
            </li>
            <li>
                <button class="btn btn-save" form="form-useradd">
                    {{ 'action.save'|trans({}, 'action') }}
                </button>
            </li>
        </ul>
    </header>
    
    {{ form_start(form, {'attr':{'id':'form-useradd'}}) }}
        <div class="blockTop">
            <h2>{{ 'form.admin.editUser.fieldset.personalinfos.legend'|trans }}</h2>
            {% if user.photo is not null %}
                <p><img alt="Photo" src="{{ user.getWebPhoto|imagine_filter('48Lx48H') }}"/></p>
            {% endif %}
            <p><strong>Type :</strong> {{ ('word.type.user.' ~ user.type ~ '.label')|trans({}, 'word') }}</p>
            {% if user.getEstablishment().getPartnerGroup() != '' %}
                <p><strong>Groupement: </strong>{{ user.getEstablishment().getPartnerGroup() }}</p>
            {% endif %}
            <p><strong>{{ 'form.profile.honorific.label'|trans }}&nbsp;:</strong> {{ user.honorific|transconst('AppBundle\\Enum\\UserHonorific') }}</p>
            <p><strong>{{ 'form.profile.firstname.label'|trans }}&nbsp;:</strong> {{ user.firstname }}</p>
            <p><strong>{{ 'form.profile.lastname.label'|trans }}&nbsp;:</strong> {{ user.lastname }}</p>
            <p><strong>{{ 'form.profile.username.label'|trans }}&nbsp;:</strong> {{ user.username }}</p>

            {# <p><strong>{{ 'form.date.birth.label'|trans }}&nbsp;:</strong> {{ user.birthday|date('d/m/Y') }}</p> #}
            <br/>
            {{ form_row(form.email, {label_attr: {class:'bold'}}) }}
            {{ form_row(form.phone, {label_attr: {class:'bold'}}) }}
            {{ form_row(form.mobile, {label_attr: {class:'bold'}}) }}

            {% if userTypeTeacher != user.type %}
                <h3>{{ 'form.address.label'|trans }}&nbsp;</h3>
                {#{ form_row(form.personalAddress) }#}
                {{ form_row(form.personalCity) }}
                {{ form_row(form.personalZipcode) }}

                {{ form_row(form.personalLatitude) }}
                {{ form_row(form.personalLongitude) }}
                <a href="#" data-name="int_perso"class="geocode btn btn-small btn-info" >Géocode</a>
            {% endif %}
        </div>

        {% if userTypeTeacher == user.type %}
            <div class="blockTop">
                <h2>{{ 'form.admin.editUser.fieldset.professionalinfos.legend'|trans }}</h2>
                {# <p><strong>{{ 'form.profile.teacher.classroom.label'|trans }}&nbsp;:</strong> {{ user.classroom|join(' / ') }}</p> #}
                <p><strong>{{ 'form.profile.teacher.jobcategory.label'|trans }}&nbsp;:</strong> 
                    {{ user.categoryJob|transconst('AppBundle\\Enum\\UserJobTeacherCategory') }}
                </p>
                <p><strong>{{ 'form.profile.teacher.job.label'|trans }}&nbsp;:</strong> 
                {% if user.jobOther is not empty %}
                    {{ user.jobOther }}
                {% else %}
                    {{ user.job|transconst('AppBundle\\Enum\\UserJobTeacher') }}
                {% endif %}</p>
                {# <p><strong>{{ 'form.profile.teacher.professionalDiscover.label'|trans }}&nbsp;:</strong> {% if user.professionalDiscover == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}</p> #}
                {#{ form_row(form.is_available, {'label_attr': {'class':'bold'}}) }#}

                <h3>{{ 'form.admin.editUser.fieldset.establishment.legend'|trans }}</h3>
                {{ form_row(form.establishmentName) }}
                {{ form_row(form.establishmentAddress) }}
                {{ form_row(form.establishmentZipcode) }}
                {{ form_row(form.establishmentCity) }}
                {{ form_row(form.latitude) }}
                {{ form_row(form.longitude) }}
                <p><strong>{{ 'form.profile.teacher.establishment.academy.label'|trans }}&nbsp;:</strong> {{ user.academy }}</p>
                <p><strong>{{ 'form.profile.teacher.establishment.rep.label'|trans }}&nbsp;:</strong> {{ ('word.rep.user.' ~ user.rep ~ '.label')|trans({}, 'word') }}</p>
                <p><strong>{{ 'form.profile.teacher.establishment.bossEmail.label'|trans }}&nbsp;:</strong> {{ user.bossEmail }}</p>
                {# <p><strong>{{ 'form.profile.teacher.establishment.email.label'|trans }}&nbsp;:</strong> {{ user.establishmentEmail }}</p> #}
            </div>
            <div class="blockTop">
                <h2>{{ 'form.admin.editUser.fieldset.otherinfos.legend'|trans }}</h2>
                <p><strong>{{ 'form.profile.shoeSize.label'|trans }}&nbsp;:</strong> {{ user.shoesize }}</p>
                <p><strong>La carte d'identité est valide ?&nbsp;:</strong> {% if user.isvalideinfo == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}</p>
                <p><strong>Carte d'identité :</strong><br/>
                {% if user.identityCard1 is not null %}
                    <a href="{{ url('secure_user_file', {filename:user.identityCard1, ownerId:user.id}) }}" target="_blank">
                        <img src="{{ url('secure_user_file', {filename:user.identityCard1, ownerId:user.id}) }}" width="200"/>
                    </a><br/>
                {% endif %}
                {% if user.identityCard2 is not null %}
                    <a href="{{ url('secure_user_file', {filename:user.identityCard2, ownerId:user.id}) }}" target="_blank">
                        <img src="{{ url('secure_user_file', {filename:user.identityCard2, ownerId:user.id}) }}" width="200"/>
                    </a>
                {% endif %}
                </p>
                <p><strong>{{ 'form.profile.teacher.photograph.label'|trans }}&nbsp;:</strong> {% if user.photograph == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}</p>
        {% else %}
            <div class="blockTop">
                <h2>{{ 'form.admin.editUser.fieldset.professionalinfos.legend'|trans }}</h2>
                <p><strong>{{ 'form.profile.engineer.formationType.label'|trans }}&nbsp;:</strong> 
                    {{ user.formationType }}
                </p>
                {#
                <p><strong>{{ 'form.profile.engineer.jobcategory.label'|trans }}&nbsp;:</strong> 
                    {{ user.categoryJob|transconst('AppBundle\\Enum\\UserJobEngineerCategory') }}
                </p>
                #}
                <p><strong>{{ 'form.profile.engineer.job.label'|trans }}&nbsp;:</strong> 
                    {{ user.job|transconst('AppBundle\\Enum\\UserJobEngineer') }}
                </p>
                <p><strong>{{ 'form.profile.engineer.jobother.label'|trans }}&nbsp;:</strong> 
                    {{ user.jobOther }}
                </p>
                <p><strong>{{ 'form.profile.engineer.aboutme.label'|trans }}&nbsp;:</strong><br/> {{ user.aboutMe }}</p>
                <p><strong>{{ 'form.profile.is_available.label'|trans }}&nbsp;:</strong> {% if user.isAvailable == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}</p>

                <h3>{{ 'form.admin.editUser.fieldset.company.legend'|trans }}</h3>
                {{ form_row(form.establishment) }}
                {{ form_row(form.establishmentNameOther) }}
                {{ form_row(form.establishmentAddress) }}
                {{ form_row(form.establishmentZipcode) }}
                {{ form_row(form.establishmentCity) }}
                {{ form_row(form.latitude) }}
                {{ form_row(form.longitude) }}
                {{ form_row(form.establishmentSector) }}
                {{ form_row(form.establishmentSectorOther) }}
            </div>
            <div class="blockTop">
                <h3>{{ 'form.admin.editUser.fieldset.otherinfos.legend'|trans }}</h3>
                <strong>{{ 'form.profile.engineer.nbcontribution.label'|trans }}&nbsp;:</strong> {{ user.nbcontribution }}<br/>
                <strong>Niveaux des classes souhaités pour ITDLC :</strong> {{ user.classroom|join(' / ') }}<br/>
                <strong>Objectifs :</strong> {{ user.briefing }}<br/>
                <strong>Transport public :</strong> {% if user.publictransport == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}<br/>
                <strong>Distance :</strong> {{ user.transportkm }}<br/>
                <strong>Temps de transport :</strong> {{ user.transporttime }}<br/>
        {% endif %}

            {{ form_row(form.is_active, {'label_attr': {'class':'bold'}}) }}
            <p><strong>Inscription à la newsletter&nbsp;:</strong> {% if user.newsletter == 't' %}{{ 'word.yes'|trans({}, 'word') }}{% else %}{{ 'word.no'|trans({}, 'word') }}{% endif %}</p>
            <strong>{{ 'form.date.registration.label'|trans }}&nbsp;:</strong> {{ user.created|date('d/m/Y') }}<br/>
            <strong>Dernière connexion :</strong> {% if user.lastlogin != '' %}{{ user.lastlogin|date('d/m/Y H:i') }}{% endif %}<br/>
            {{ form_row(form.latitude, {'label_attr': {'class':'bold'}}) }}
            {{ form_row(form.longitude, {'label_attr': {'class':'bold'}}) }}
            {{ form_row(form.note, {'label_attr': {'class':'bold'}}) }}

            {{ form_rest(form) }}
        </div>
    {{ form_end(form) }}

    <div class="clear"></div>

    {% if userTypeTeacher == user.type %}
        <h3>Demandes PEE</h3>
        <table class="tableBo">
            <thead>
                <tr>
                    <td>Date, ville, entreprise</td>
                    <td>Date de dépôt</td>
                    <td>Statut</td>
                </tr>
            </thead>
            <tbody>
            {% for demande in demandespee %}
                <tr>
                    <td>{{ demande.operationpee.dateVisite|date('d/m/Y') }}, {{ demande.operationpee.city }}, {{ demande.operationpee.company }}</td>
                    <td>{{ demande.created|date('d/m/Y') }}</td>
                    <td>{{ demande.state }}</td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
        <div class="clear"></div>

        <h3>Demandes ITDLC</h3>
        <table class="tableBo">
            <thead>
                <tr>
                    <td>Date de dépôt</td>
                    <td>Statut</td>
                </tr>
            </thead>
            <tbody>
            {% for demande in demandesitdlc %}
                <tr>
                    <td>
                        <a href="{{ path('admin_demande_itdlc_professeur_edit', {id:demande.id }) }}">
                            {{ demande.created|date('d/m/Y') }}
                        </a>
                    </td>
                    <td>{{ ('word.state.operationITDLC.' ~ demande.state ~ '.label')|trans({}, 'word') }}</td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
        <div class="clear"></div>
    {% else %}
        <h3>Demandes ITDLC</h3>
        <table class="tableBo">
            <thead>
                <tr>
                    <td>Date de dépôt</td>
                    <td>Nbr de contributions acceptées</td>
                    <td colspan="2">{{ 'word.actions'|trans({}, 'word') }}</td>
                </tr>
            </thead>
            <tbody>
                {% for demande in demandesitdlc %}
                    <tr>
                        <td>
                            <a href="{{ path('admin_demande_itdlc_inge_edit', {id:demande.id}) }}">
                                {{ demande.created|date('d/m/Y') }}
                            </a>
                        </td>
                        <td>
                            <a href="{{ path('admin_demande_itdlc_inge_edit', {id:demande.id}) }}">
                                {% if demande.nbContribution %}{{ demande.nbContribution }}{% else %}0{% endif %} contributions acceptées
                            </a>
                        </td>
                        <td class="action">
                            {% if (demande.latitude is not null) or (demande.longitude is not null) %}
                                <a class="search" href="{{ path('admin_demande_itdlc_ingenieur_search', {'user':demande.id}) }}">
                                    <span>{{ 'action.search'|trans({}, 'action') }}</span>
                                </a>
                            {% endif %}
                        </td>
                        <td class="action">
                            <a class="edit" href="{{ path('admin_demande_itdlc_inge_edit', {id:demande.id}) }}">
                                <span>{{ 'action.edit.label'|trans({}, 'action') }}</span>
                            </a>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% endif %}

    <h3>Opération ITDLC</h3>
    <table class="tableBo">
        <thead>
            <tr>
                <td>Date de rencontre</td>
                <td>{{ ('word.type.user.' ~ userTypeTeacher ~ '.label')|trans({}, 'word') }}</td>
                <td>{{ ('word.type.user.' ~ userTypeEngineer ~ '.label')|trans({}, 'word') }}</td>
                <td>Statut</td>
            </tr>
        </thead>
        <tbody>
            {% for o in operationsitlc %}
                <tr>
                    <td>
                        <a href="{{ path('admin_operation_itdlc_edit', {id:o.id}) }}">
                            {{- include('Admin/Ope/ITDLC/_component/availability.html.twig', {availabilities: o.availability}) -}}
                        </a>
                    </td>
                    <td>
                        {% if o.prof != '' %}
                            <a href="{{ path('admin_user_edit', {'user':o.prof.id}) }}">
                                {{ o.prof.firstname }} {{ o.prof.lastname }}
                            </a>
                        {% endif %}
                    </td>
                    <td>
                        {% if o.inge != '' %}
                            <a href="{{ path('admin_user_edit', {'user':o.inge.id}) }}">
                                {{ o.inge.firstname }} {{ o.inge.lastname }}
                            </a>
                        {% endif %}
                    </td>
                    <td>{{ o.state }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    
    <ul class="btns">
        <li>
            <button class="btn btn-save" form="form-useradd">
                {{ 'action.save'|trans({}, 'action') }}
            </button>
        </li>
    </ul>
{% endblock %}
