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

{% 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 = '#operation_pee_';

            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) {
                    if (status == google.maps.GeocoderStatus.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);
                    }
                });
            }

            /**
            * 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) {
                // 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);
console.log(address);
                    // 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);
                    };
                });
            }

            initAddressGeocoding(
                ['address', 'zipCode', 'city'],
                'latitude',
                'longitude'
            );
        });
        //]]>
    </script>
    <script>
        $(function() {
            $('.fancybox').fancybox({
                autoSize: false,
                width: 800,
                height: 500,
                maxHeight: '90%',
                padding: 0,
                afterClose: function() {
                    window.location.reload();
                }
            });
        });
    </script>
{% endblock %}

{% block body %}
    <header>
        <ul class="btns">
            <li class="btns-back">
                {{ m.step_back() }}
            </li>
            <li>
                <a
                    class="btn btn-export fancybox fancybox.iframe"
                    href="{{ path('admin_sms_campaign_pee_add', {'ope':ope.id, 'iframe':true }) }}"
                >
                    {{ 'action.add.sms.campaign'|trans({}, 'action') }}
                </a>
            </li>
            {% if edit_mode %}
                <li>
                    <a class="btn btn-pdf" href="{{ path('admin_operation_pee_download', {id: ope.id}) }}">
                        {{ 'action.download.pdf'|trans({}, 'action') }}
                    </a>
                </li>
            {% endif %}
            <li>
                <button class="btn btn-save" form="form-operationpeeedit">
                    {{ ('action.' ~ (edit_mode ? 'save' : 'duplicate'))|trans({}, 'action') }}
                </button>
            </li>
        </ul>

        <h1>
            {{ edit_mode ? 'O' : 'Dupliquer lʼo' -}}
            pération PEE <em>{{ ope.company }} {{ ope.site }}</em>
            {{
                ope.dateVisite is not null
                    ? 'du ' ~ ope.dateVisite|date('d/m/Y')
                    : 'sentence.date.operationPEE.missing'|trans({}, 'sentence')|lower
            }}
        </h1>
    </header>
  
    <a class="btn btn-add" href="{{ path('admin_operation_pee_add_participant', {id: ope.id}) }}">
        {{ 'action.add.participantPee.label'|trans({}, 'action') }}
    </a>

    {{ form_start(form, {'attr':{'id':'form-operationpeeedit'}}) }}
        {% if edit_mode %}
            {% macro generateList(opeId, applications, state, stateTranslation) %}
                {% for a in applications %}
                    {% if loop.first %}
                        <h3>
                            <a href="{{ path('admin_operation_pee_export', {operationPEE:opeId, state:state}) }}" target="_blank" title="Exporter la liste des {{ stateTranslation }}">{{ stateTranslation }} ({{ applications|length }})</a>
                        </h3>



                        <table class="tableBo">
                            <thead>
                                <tr>
                                    <td>{{ ('word.type.user.' ~ constant('AppBundle\\Enum\\UserType::TEACHER') ~ '.label')|trans({}, 'word') }}</td>
                                    <td>{{ 'form.email.label'|trans({}, 'form') }}</td>
                                    <td>Matière enseignée</td>
                                    <td>Nom établissement</td>
                                    <td>Ville établissement</td>
                                    <td>{{ 'form.academy.label'|trans({}, 'form') }}</td>
                                    <td>{{ 'form.phone.landline.label'|trans({}, 'form') }}</td>
                                    <td>Pointure</td>
                                    <td>{{ 'word.actions'|trans({}, 'word') }}</td>
                                </tr>
                            </thead>
                            <tbody>
                    {% endif %}

                    <tr>
                        <td>
                            <a href="{{ path('admin_demande_pee_edit', {id:a.id}) }}" title="Modifier la demande de: {{ a.cuser.firstname }} {{ a.cuser.lastname }}">
                                {{ a.cuser.firstname|capitalize }} {{ a.cuser.lastname|capitalize }}
                            </a>
                        </td>
                        <td>{{ a.cuser.email }}</td>
                        <td>{% if a.cuser.categoryJob is not empty %}{{ a.cuser.categoryJob|transconst('AppBundle\\Enum\\UserJobTeacherCategory') }} / {% endif %}{% if a.cuser.jobOther is not empty %}{{ a.cuser.jobOther }}{% else %}{{ a.cuser.job|transconst('AppBundle\\Enum\\UserJobTeacher') }}{% endif %}</td>
                        <td>{{ a.cuser.establishmentName }}</td>
                        <td>{{ a.cuser.establishmentCity }}</td>
                        <td>{{ a.cuser.academy }}</td>
                        <td>{% if a.cuser.mobile is not empty %}{{ a.cuser.mobile }}{% else %}{{ a.cuser.phone }}{% endif %}</td>
                        <td>{{ a.cuser.shoeSize }}</td>
                        <td class="center">
                            <a class="edit" href="{{ path('admin_demande_pee_edit', {id:a.id}) }}" title="Modifier la demande de: {{ a.cuser.firstname }} {{ a.cuser.lastname }}">
                                <span>Modifier la demande</span>
                            </a>
                        </td>
                    </tr>

                    {% if loop.last %}
                            </tbody>
                        </table>
                        <br/>
                    {% endif %}
                {% else %}{# There no applications for this state #}
                    <h3>{{ stateTranslation }} (0)</h3>
                {% endfor %}
            {% endmacro %}

            {% import _self as macro %}

            {% for key, a in applications %}
                {{ macro.generateList(ope.id, a.list, key, a.trans) }}
            {% endfor %}
        {% endif %}

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

        <div class="left" style="width:50%;">
            <h2>Inscription</h2>
            {{ form_row(form.state) }}
            {{ form_row(form.nbPeople) }}
            {{ form_row(form.publish) }}
            {{ form_row(form.unpublish) }}
            {{ form_row(form.is_identity_mandatory) }}
            {{ form_row(form.urlExternalRegistration) }}

            <h2>Date</h2>
            {{ form_row(form.dateVisite) }}
            {{ form_row(form.startTime) }}
            {{ form_row(form.endTime) }}

            <h2>Description</h2>
            {{ form_row(form.title) }}
            {{ form_row(form.presentation) }}
            {{ form_row(form.visit) }}
            {{ form_row(form.category) }}
        </div>

        <div class="left">
            <h2>Lieu</h2>
            {{ form_row(form.new) }}
            {{ form_row(form.company) }}
            {{ form_row(form.site) }}
            {{ form_row(form.address) }}
            {{ form_row(form.zipCode) }}
            {{ form_row(form.city) }}
            {{ form_row(form.latitude) }}
            {{ form_row(form.longitude) }}
            {{ form_row(form.academy) }}
            {{ form_row(form.siteImage1File) }}
            {{ form_row(form.siteImage2File) }}
            {{ form_row(form.siteImage3File) }}
        </div>

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

        <div class="left" style="width:50%;">
            <h2>Verbatim</h2>
            {{ form_row(form.quoteContent) }}
            {{ form_row(form.quoteAuthor) }}
            {{ form_row(form.quoteAuthorJob) }}
            {{ form_row(form.category) }}
        </div>

        <div class="left">
            <h2>Informations additionelles</h2>
            {{ form_row(form.namely) }}
            {{ form_row(form.audience) }}
            {{ form_row(form.partner) }}
            {{ form_row(form.note) }}
        </div>

        <div class="clear"></div>
    {{ form_end(form) }}
    
    {#% if sms_campaigns is not empty %}
    
    {% set state_in_progress = constant('AppBundle\\Entity\\SMSCampaign::STATE_IN_PROGRESS') %}
    {% set state_sended = constant('AppBundle\\Entity\\SMSCampaign::STATE_SENDED') %}
    {% set state_error = constant('AppBundle\\Entity\\SMSCampaign::STATE_ERROR') %}
    
    <div class="page-content" id="sms-history">
        <h4 class="page-content-title">{{ 'form.sms.campaign.history_block.title'|trans({}, 'form') }}</h4>
        <table class="tableBo">
            <thead>
                <tr> 
                    <th>{{ 'form.sms.campaign.created.label'|trans({}, 'form') }}</th>
                    <th>{{ 'form.sms.campaign.content.label'|trans({}, 'form') }}</th>
                    <th>{{ 'form.sms.campaign.nb_recipient.label'|trans({}, 'form') }}</th>
                    <th>{{ 'form.sms.campaign.nb_sms.label'|trans({}, 'form') }}</th>
                    <th>{{ 'form.sms.campaign.credit_used.label'|trans({}, 'form') }}</th>
                    <th>{{ 'form.sms.campaign.sended.label'|trans({}, 'form') }}</th>
                </tr>
            </thead>
            <tbody>
                {% for campaign in sms_campaigns %}
                    {% if campaign.sended == state_sended %}
                        {% set campaign_status = 'form.sms.campaign.sended.success'|trans({}, 'form') %}
                        {% set class_tr = 'success' %}
                    {% elseif campaign.sended == state_error %}
                        {% set campaign_status = 'form.sms.campaign.sended.error'|trans({}, 'form') %}
                        {% set class_tr = 'error' %}
                    {% else %}
                        {% set campaign_status = 'form.sms.campaign.sended.in_progress'|trans({}, 'form') %}
                        {% set class_tr = 'in_progress' %}
                    {% endif %}
                    <tr class="{{ class_tr }}">
                        <td>{{ campaign.created|date("d/m/Y H:i") }}</td>
                        <td>{{ campaign.content|length > 70 ? campaign.content|slice(0, 70) ~ '...' : campaign.content }}</td>
                        <td>{{ campaign.countChildren }}{% if campaign.countChildren %} : {{ campaign.listChildren }}{% endif %}</td>
                        <td>{{ campaign.getNbSMSSended }}</td>
                        <td>{{ campaign.getCreditUsed }}</td>
                        <td>{{ campaign_status }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% endif %#}

    <ul class="btns">
        <li>
            <button class="btn btn-save" form="form-operationpeeedit">
                {{ ('action.' ~ (edit_mode ? 'save' : 'duplicate'))|trans({}, 'action') }}
            </button>
        </li>
    </ul>
{% endblock %}
