{extends file="admin-layout.tpl"}

{block name="no-return-functions"}
    {$admin_current_location = 'configuration'}
{/block}

{block name="page-title"}{intl l='Country migration'}{/block}

{block name="check-resource"}admin.configuration.country{/block}
{block name="check-access"}update{/block}

{block name="main-content"}
    <div class="countries migrate-country">

        <div id="wrapper" class="container">

            <ul class="breadcrumb">
                <li><a href="{url path='/admin/home'}">{intl l="Home"}</a></li>
                <li><a href="{url path='/admin/configuration'}">{intl l="Configuration"}</a></li>
                <li><a href="{url path='/admin/configuration/countries'}">{intl l="Countries"}</a></li>
                <li>{intl l='Migrate countries'}</li>
            </ul>

            <div class="row">
                <div class="col-md-12 general-block-decorator">
                    <div class="row">

                        <div class="col-md-12 title title-without-tabs">
                           {intl l='Migrate countries'}
                        </div>

                        <div class="col-md-12">
                            <div class="alert alert-info">
                                {intl l='In version 2.3 of Thelia, the system of country has changed.'}
                                {intl l='Now, countries has been split in countries and states.'}<br>
                                {intl l="The migration process is tricky and couldn't be automated."}<br><br>
                                {intl l="The update process has created new countries (even if it exists) and associated states."}<br>
                                {intl l="The migration will change the address, tax rules and shipping zones to match with the new system."}<br>
                                {intl l="After the migration the old country will be hide and the new one shown"}<br><br>
                                {intl l="For USA and Canada the states already exists as countries, so you have to select the right state."}<br>
                                {intl l="For other countries, you should decide to use state or not. "}
                                {intl l="If you want to use the new country with its states, you have to check the migrate checkbox and select a state."}
                                {intl l="We added a 'default' state with a blank name as a fallback. Customer will have the possibility to change it later."}
                            </div>
                        </div>

                        {if $showForm}
                        <div class="form-container">
                            <div class="col-md-12">

                                {form name="thelia.admin.country.state.migration"}
                                    <form method="POST" action="{url path="/admin/configuration/countries/do-migrate"}" {form_enctype} class="clearfix">
                                        {include
                                            file = "includes/inner-form-toolbar.html"
                                            hide_submit_buttons = false

                                            page_url  = {url path="/admin/configuration/countries/migrate"}
                                            close_url = {url path="/admin/configuration/countries"}
                                        }

                                        {form_hidden_fields exclude="locale"}

                                        {render_form_field field='success_url' value={url path="/admin/configuration/countries/migrate"}}

                                        {if $form_error}<div class="alert alert-danger">{$form_error_message}</div>{/if}

                                        {if {hasflash type="migrate"}}
                                        <div class="alert alert-success">
                                            {flash type="migrate"}
                                                <div>{$MESSAGE}</div>
                                            {/flash}
                                        </div>
                                        {/if}

                                        <div class="table-responsive table-migration">
                                            <table class="table table-striped table-condensed">
                                                <caption class="clearfix">
                                                    {intl l='Countries to migrate'}
                                                </caption>
                                                <thead>
                                                    <tr>
                                                        <th><a href="#" id="toggle-migrate">{intl l="Migrate ?"}</a></th>
                                                        <th>{intl l="Old country"}</th>
                                                        <th>{intl l="New country"}</th>
                                                        <th>{intl l="State"}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                        {form_collection form=$form collection="migrations"}
                                            {$newCountryId=0}
                                            {$countryId=0}
                                                <tr>
                                                    <td>
                                                        {form_collection_field form=$form row=$row field="migrate"}
                                                            <input type="checkbox" name="{$name}" id="migrate_{$collection_current}" value="{$value}" />
                                                        {/form_collection_field}
                                                    </td>
                                                    <td>
                                                        {form_collection_field form=$form row=$row field="country"}
                                                        {$countryId={$value}}
                                                            <input type="hidden" name="{$name}" id="country_{$collection_current}" value="{$value}" />
                                                            <span data-country="{$value}"></span>
                                                        {/form_collection_field}
                                                    </td>
                                                    <td>
                                                        {form_collection_field form=$form row=$row field="new_country"}
                                                        {$newCountryId={$value}}
                                                            <input type="hidden" name="{$name}" id="new_country_{$collection_current}" value="{$value}" />
                                                            <span data-country="{$value}"></span>
                                                        {/form_collection_field}
                                                    </td>
                                                    <td>
                                                        {form_collection_field form=$form row=$row field="new_state"}
                                                        {$ref[]={$label_attr.for}}
                                                            <input type="hidden" name="{$name}" id="new_state_{$collection_current}" value="{$value}" />
                                                            <select class="form-control states-select" data-new-country="{$newCountryId}" data-country="{$countryId}" data-rel="#new_state_{$collection_current}"></select>
                                                        {/form_collection_field}
                                                    </td>
                                                </tr>
                                        {/form_collection}
                                                </tbody>
                                            </table>
                                        </div>

                                    </form>
                                {/form}

                            </div>
                        </div>
                        {else}
                            <div class="col-md-12">
                                {intl l="All countries have been migrated"}
                            </div>
                        {/if}

                    </div>
                </div>

                {if count($countriesMigrated) > 0 }
                <div class="col-md-12 general-block-decorator countries-migrated">
                    <div class="row">
                        <div class="col-md-12 title title-without-tabs">
                            {intl l='Countries migrated'}
                        </div>
                    </div>

                    {foreach $countriesMigrated as $country => $new}
                    <div class="row">
                        <div class="col-md-12">
                            {intl l='Country '} <strong><span class="text-info" data-country="{$country}"></span></strong>
                            {intl l=' migrated to '}
                            {intl l=' country '}
                            <strong><span class="text-success" data-country="{$new.country}"></span></strong>
                            {intl l=' state '}
                            <strong><span class="text-success" data-state="{$new.state}"></span></strong>
                        </div>
                    </div>
                    {/foreach}
                </div>
                {/if}

            </div>

        </div>
    </div>
{/block}

{block name="javascript-initialization"}
    {javascripts file='assets/js/bootstrap-select/bootstrap-select.js'}
        <script src="{$asset_url}"></script>
    {/javascripts}

    {javascripts file='assets/js/libs/underscore-min.js'}
        <script src="{$asset_url}"></script>
    {/javascripts}

    <script id="tpl-select-states" type="text/html">
        <option value="">&nbsp;</option>
        <% _.each(items, function(item) { %>
        <option value="<%= item.id %>" <% if (selected == item.id) { %>selected<% } %>><%- item.title %></option>
        <% }) %>
    </script>

    <script type="text/javascript">
        (function($) {

            var countries = {render action='Thelia\Controller\Admin\CountryController::getDataAction' visible=0 lang='en_US'};
            var countriesById = {};
            var statesById = {};
            var migrate = false;

            var i18n = {
                'configuration': '{intl l="Configuration"}'
                , 'states_all': '{intl l='All States'}'
                , 'countries': '{intl l="Countries"}'
            };

            {literal}
            var tpl = {
                'select-states': _.template($("#tpl-select-states").html())
            };


            var initialize = function initialize() {
                var addList = [],
                    addedList = [];

                countriesById = _.indexBy(countries, 'id');
                _.each(
                    countries,
                    function (country) {
                        if (country.hasStates) {
                            _.extend(statesById, _.indexBy(country.states, 'id'));
                        }
                    }
                );

                // Display countries title
                $('span[data-country]').each(function(){
                    $(this).html(countriesById[$(this).data('country')].title);
                });

                $('span[data-state]').each(function(){
                    $(this).html(statesById[$(this).data('state')].title);
                });

                // Build state select
                $('.states-select').each(function(){
                    var $select = $(this),
                        $rel = $($select.data("rel")),
                        country,
                        newCountry,
                        stateId;

                    country = countriesById[$select.data('country')];
                    newCountry = countriesById[$select.data('new-country')];

                    // fill the select
                    stateId = $rel.val();
                    if (!stateId) {
                        stateId = findState(newCountry.states, country.title);
                        if (stateId != null) {
                            $rel.val(stateId);
                        }
                    }

                    $select.html(render('select-states', {'selected': stateId, 'items': newCountry.states}));
                    $select.on("change", function() {
                        $($select.data("rel")).val($select.val());
                    });
                });

                $('#toggle-migrate').on('click', function(ev) {
                    ev.preventDefault();
                    migrate = !migrate;
                    $('.table-migration').find('input[type=checkbox]').prop("checked", migrate);
                });
            };

            var sanitize = function sanitize(value) {
                return ('' + value).toLowerCase().replace(/[a-z0-9]/, '');
            };

            var findState = function findState(states, countryTitle) {
                var state;

                countryTitle = sanitize(countryTitle);

                state = _.find(states, function(item) {
                    return (sanitize(countryTitle).indexOf(sanitize(item.title)) !== -1);
                });

                if (state === undefined) {
                    state = _.find(states, function(item) {
                        return ('default'.indexOf(sanitize(item.title)) !== -1);
                    });
                }

                return (state === undefined) ? 0 : state.id;
            };

            // Utils
            var render = function render(tplName, obj) {
                var data = $.extend({}, obj, {'i18n': i18n});
                return tpl[tplName](data);
            };

            $(document).ready(function(){
                initialize();
            });

            {/literal}
        })(jQuery);
    </script>
{/block}

{block name="javascript-last-call"}
    {hook name="wysiwyg.js" location="wysiwyg-country-edit-js" }
{/block}