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

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

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

{block name="main-content"}
<div class="hooks">

    <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/hooks'}">{intl l="Hooks"}</a></li>
        </ul>

        {hook name="hooks.top" location="hooks_top" }

        {loop type="auth" name="can_create" role="ADMIN" resource="admin.hook" access="UPDATE"}
        <div class="row">
            <div class="col-md-12">
                <div class="general-block-decorator">
                    <h3>
                        {intl l="Check the support of hooks."}
                    </h3>
                    {assign template_type {$smarty.get.type|default:"1"}}
                    <form id="discover-hook" class="form-inline" role="form">
                        <div class="form-group">
                            <label class="sr-only" for="discover-template">{intl l="Template type"}</label>
                            <select class="form-control" id="discover-template">
                                <option value="1" {if $template_type eq "1"}selected {/if}>{intl l="Front Office"}</option>
                                <option value="2" {if $template_type eq "2"}selected {/if}>{intl l="Back Office"}</option>
                                <option value="3" {if $template_type eq "3"}selected {/if}>{intl l="pdf"}</option>
                                <option value="4" {if $template_type eq "4"}selected {/if}>{intl l="email"}</option>
                            </select>
                        </div>
                        <button type="button" id="discover-parse" class="btn btn-primary">{intl l="Parse template"}</button>
                        <div>&nbsp;</div>
                        <div id="discover-content"></div>
                    </form>
                </div>
            </div>
        </div>
        {/loop}

        <div class="row">
            <div class="col-md-12">
                <form action="" method="post">
                    <div class="general-block-decorator">
                        <div class="table-responsive">
                            <table class="table table-striped table-condensed">
                                <caption class="clearfix">
                                    {intl l='Hooks'}
                                    {include file='renderer/buttons.html' btn_group=false buttons=[
                                        [
                                            'type' => 'create',
                                            'class' => 'action-btn',
                                            'title' => {intl l='Add a new hook'},
                                            'href' => '#add_hook_dialog',
                                            'auth' => ['resource' => 'admin.hook'],
                                            'data' => [
                                                'toggle' => 'modal'
                                            ]
                                        ]
                                    ]}
                                    <select class="form-control action-select" id="filter-template">
                                        <option value="1" {if $template_type eq "1"}selected {/if}>{intl l="Front Office"}</option>
                                        <option value="2" {if $template_type eq "2"}selected {/if}>{intl l="Back Office"}</option>
                                        <option value="3" {if $template_type eq "3"}selected {/if}>{intl l="pdf"}</option>
                                        <option value="4" {if $template_type eq "4"}selected {/if}>{intl l="email"}</option>
                                    </select>
                                </caption>
                                <thead>
                                    <tr>
                                        <th>
                                            {admin_sortable_header
                                            current_order=$order
                                            order='id'
                                            reverse_order='id_reverse'
                                            path='/admin/hooks'
                                            label={intl l='ID'}
                                            }
                                        </th>
                                        <th>
                                            {admin_sortable_header
                                            current_order=$order
                                            order='code'
                                            reverse_order='code_reverse'
                                            path='/admin/hooks'
                                            label={intl l='Code'}
                                            }
                                        </th>
                                        <th>
                                            {admin_sortable_header
                                            current_order=$order
                                            order='alpha'
                                            reverse_order='alpha_reverse'
                                            path='/admin/hooks'
                                            label={intl l="Title"}
                                            }
                                            </th>
                                        <th>
                                            {admin_sortable_header
                                            current_order=$order
                                            order='native'
                                            reverse_order='native_reverse'
                                            path='/admin/hooks'
                                            label={intl l="Official"}
                                            }
                                        </th>
                                        <th>
                                            {admin_sortable_header
                                            current_order=$order
                                            order='enabled'
                                            reverse_order='enabled_reverse'
                                            path='/admin/hooks'
                                            label={intl l="Active"}
                                            }
                                        </th>

                                        {hook name="hooks.table-header" location="hooks_table_header" }

                                        <th class="actions">{intl l='Actions'}</th>
                                    </tr>
                                </thead>

                                <tbody>
                                {loop name="hooks" type="hook" backend_context="1" hook_type=$template_type lang=$lang_id order=$order}
                                <tr>
                                    <td>{$ID}</td>
                                    <td><a href="{url path="/admin/hook/update/%id" id=$ID}">{$CODE}</a></td>
                                    <td><a href="{url path="/admin/hook/update/%id" id=$ID}">{$TITLE}</a></td>
                                    <td>
                                        {if $NATIVE}
                                        <span class="label label-md label-success"><i class='glyphicon glyphicon-ok-circle'></i></span>
                                        {else}
                                        <span class="label label-md label-warning"><i class='glyphicon glyphicon-remove-circle'></i></span>
                                        {/if}
                                    </td>
                                    <td>
                                        <div class="make-switch switch-small hook-activation u-toggle-state" data-id="{$ID}" data-on="success" data-off="danger" data-on-label="<i class='glyphicon glyphicon-ok-circle'></i>" data-off-label="<i class='glyphicon glyphicon-remove-circle'></i>">
                                            <input type="checkbox" {if $ACTIVE}checked="checked"{/if} />
                                        </div>
                                    </td>

                                    {hook name="hooks.table-row" location="hooks_table_row" hook_id={$ID} }

                                    <td class="actions">
                                        {include file='renderer/buttons.html' buttons=[
                                            [
                                                'type' => 'edit',
                                                'class' => 'hook-change',
                                                'title' => {intl l='Change this hook'},
                                                'href' => {url path="/admin/hook/update/%id" id=$ID},
                                                'auth' => ['resource' => 'admin.hook']
                                            ],
                                            [
                                                'type' => 'delete',
                                                'class' => 'hook-delete',
                                                'title' => {intl l='Delete this hook'},
                                                'href' => '#delete_dialog',
                                                'data' => [
                                                    'id' => $ID,
                                                    'toggle' => 'modal'
                                                ],
                                                'auth' => ['resource' => 'admin.hook']
                                            ]
                                        ]}
                                    </td>
                                </tr>
                                {/loop}
                                {elseloop rel="hooks"}
                                <tr>
                                    <td colspan="8">
                                        <div class="alert alert-info">
                                            {intl l="No hooks has been created yet. Click the + button to create one."}
                                        </div>
                                    </td>
                                </tr>
                                {/elseloop}
                                </tbody>
                            </table>
                        </div>
                    </div>

                </form>

            </div>

            <div class="col-md-12">
                <div class="text-right">
                    <a href="{url path='/admin/modules'}" class="btn btn-primary">{intl l="Manage modules"} <span class="glyphicon glyphicon-chevron-right"></span></a>
                    <a href="{url path='/admin/module-hooks'}" class="btn btn-primary">{intl l="Manage modules attachements"}  <span class="glyphicon glyphicon-chevron-right"></span></a>
                </div>
            </div>
        </div>

        {hook name="hooks.bottom" location="hooks_bottom" }

    </div>
</div>


{* Adding a new Hook *}

{form name="thelia.admin.hook.creation"}

    {* Capture the dialog body, to pass it to the generic dialog *}
    {capture "hook_creation_dialog"}

        {form_hidden_fields exclude="locale,native"}

        {* on success, redirect to the edition page, _ID_ is replaced with the created object ID, see controller  *}
        {render_form_field field="success_url" value={url path="/admin/hook/update/_ID_"}}

        {custom_render_form_field field="title"}
            {loop type="lang" name="default-lang" default_only="1"}
                {* Switch edition to the current locale *}
                <input type="hidden" name="edit_language_id" value="{$ID}" />

                {render_form_field field="locale" value=$LOCALE}

                <div class="input-group">
                    <input type="text" {form_field_attributes field="title"}>
                    <span class="input-group-addon"><img src="{image file="assets/img/flags/`$CODE`.png"}" alt="{$TITLE}" /></span>
                </div>
                <div class="help-block">{intl l="Enter here the value in the default language (%title)" title={$TITLE}}</div>
            {/loop}
        {/custom_render_form_field}

        {render_form_field field='code'}
        {render_form_field field='type'}
        {render_form_field field='native' value="0"}
        {render_form_field field='active'}

        {hook name="hook.create-form" location="hook_create_form" }

    {/capture}

    {include
    file = "includes/generic-create-dialog.html"

    dialog_id    = "add_hook_dialog"
    dialog_title = {intl l="Create a new Hook"}
    dialog_body  = {$smarty.capture.hook_creation_dialog nofilter}

    dialog_ok_label     = {intl l="Create this hook"}
    dialog_cancel_label = {intl l="Cancel"}

    form_action        = {url path='/admin/hooks/create'}
    form_enctype       = {form_enctype}
    form_error_message = $form_error_message
    }
{/form}


{* Delete confirmation dialog *}
{capture "delete_dialog"}
    <input type="hidden" name="hook_id" id="hook_delete_id" value="" />
    {hook name="hook.delete-form" location="hook_delete_form" }
{/capture}

{include
file = "includes/generic-confirm-dialog.html"

dialog_id       = "delete_dialog"
dialog_title    = {intl l="Delete hook"}
dialog_message  = {intl l="Do you really want to delete this hook ?"}

form_action         = {token_url path='/admin/hooks/delete'}
form_content        = {$smarty.capture.delete_dialog nofilter}
}


<div class="modal fade" id="toggle-native-failed" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content alert alert-block alert-danger ">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h2>{intl l="Error"}</h2>
            </div>
            <div class="modal-body">
                <strong>{intl l="Impossible to change official hook. Please contact your administrator or try later"}</strong>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="toggle-active-failed" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content alert alert-block alert-danger ">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h2>{intl l="Error"}</h2>
            </div>
            <div class="modal-body">
                <strong>{intl l="Impossible to change active flag. Please contact your administrator or try later"}</strong>
            </div>
        </div>
    </div>
</div>

{/block}

{block name="javascript-initialization"}

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

<script>
    $(document).ready(function(){

        var urls = {
            "index": "{url path='/admin/hooks'}",
            "native": "{url path='/admin/hook/toggle-native'}",
            "activation": "{url path='/admin/hook/toggle-activation'}",
            "discover": "{url path='/admin/hooks/discover'}",
            "discoverSave": "{url path='/admin/hooks/discover/save'}",
        };

        {literal}
        // Toogle switch on input radio
        $('.switch-radio').on('switch-change', function () {
            $('.switch-radio').bootstrapSwitch('toggleRadioState');
        });

        $('.hook-delete').click(function(ev){
            $('#hook_delete_id').val($(this).data('id'));
        });

        $('.hook-native').on('switch-change', function(e, data){
            $.ajax({
                url : urls['native'],
                data : {
                    hook_id: $(this).data('id')
                }
            }).fail(function(){
                $('#toggle-native-failed').modal('show');
            });
        });

        var newTpl = _.template($("#discover-new").html())
            ,missingTpl = _.template($("#discover-missing").html())
            ,newHooks = []
            ,missingHooks = []
            ,templateType
            ;

        $('.hook-activation').on('switch-change', function(e, data){
            $.ajax({
                url : urls['activation'],
                data : {
                    hook_id: $(this).data('id')
                }
            }).fail(function(){
                $('#toggle-active-failed').modal('show');
            });
        });

        $('#filter-template').on('change', function(e){
            document.location = urls['index'] + "?type=" + $(this).val();
        });

        $('#discover-hook').on('click', '#discover-parse', function(e, data){

            e.preventDefault();

            templateType = $("#discover-template").val();

            $('body').append('<div class="modal-backdrop fade in" id="loading-event"><div class="loading"></div></div>');

            $.ajax({
                url: urls['discover'],
                data: {
                    "template_type": $("#discover-template").val()
                }
            }).done(function(data){
                $("#loading-event").remove();
                if (data.success){
                    var content = "",
                        index,
                        it;
                    $("#discover-content").removeClass("alert alert-danger");
                    if (data.new.length !== 0){
                        newHooks = data.new,
                        content += newTpl({hooks: data.new});
                    }
                    if (data.missing.length !== 0){
                        missingHooks = data.missing,
                        content += missingTpl({hooks: data.missing});
                    }
                    if (content != ""){
                        content += $("#discover-action").html();
                    } else {
                        content = $("#discover-uptodate").html();
                    }

                    $("#discover-content").html(content);
                } else {
                    $("#discover-content").html(data.message).addClass("alert alert-danger");
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown){
                $("#loading-event").remove();
                $("#discover-content").html(textStatus).addClass("alert alert-danger");
            });
        });

        $('#discover-hook').on('click', '#discover-save', function(e){

            e.preventDefault();
            var data = {
                'new': [],
                'missing': [],
                'templateType': templateType
            };
            $('.discover-new:checked').each(function(){
                data["new"].push( newHooks[ $(this).val() ] );
            });
            $('.discover-missing:checked').each(function(){
                data["missing"].push( $(this).val() );
            });

            $('body').append('<div class="modal-backdrop fade in" id="loading-event"><div class="loading"></div></div>');

            $.ajax({
                url: urls['discoverSave'],
                data: data,
                type: "POST",
                dataType: "json"
            }).done(function(data){
                var messages = '',
                    i = 0
                $("#loading-event").remove();
                if (data.success){
                    $("#discover-parse").trigger('click');
                } else {
                    messages = "";
                    for ( ; i < data.messages.length ; i++ ){
                        messages += data.messages[i] + '<br/>';
                    }
                    $("#discover-content").addClass("alert alert-danger").html(messages);
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown){
                $("#loading-event").remove();
                $("#discover-content").html(textStatus).addClass("alert alert-danger");
            });

        });

        $('#discover-hook').on('change', '#discover-new-toggle, #discover-missing-toggle', function(e){
            $( $(this).data("target")).filter(':not([disabled])').prop( "checked", $(this).prop( "checked") );
        });

        {/literal}
    });

</script>


<script id="discover-uptodate" type="text/html">
    <div class="alert alert-success">
        <p>{intl l="Your template is clean. No missing hooks and no new hooks." }</p>
    </div>
</script>


<script id="discover-action" type="text/html">
<div>
    <button type="button" name="save" value="save" id="discover-save" class="form-submit-button btn btn-sm btn-default btn-success" title=" Enregistrer"> {intl l="Update"} <span class="glyphicon glyphicon-ok"></span></button>
</div>
</script>


<script id="discover-updated" type="text/html">
    <div class="alert alert-success">
        <p>{intl l="The hooks have been updated successfuly !" }</p>
        <p><a href="javascript:location.reload();"></a></p>
    </div>
</script>


<script id="discover-new" type="text/html">
<table class="table table-striped table-condensed">
    <caption class="clearfix">
        {intl l='Your template define new hooks'}
    </caption>
    <thead>
        <tr>
            <th><input id="discover-new-toggle" data-target=".discover-new" type="checkbox" alt="{intl l="Toggle select all"}"/></th>
            <th>{intl l="Code"}</th>
            <th>{intl l="Title"}</th>
            <th>{intl l="Block"}</th>
            <th>{intl l="Module"}</th>
        </tr>
    </thead>
    <tbody>
        <% _.each(hooks, function(hook, index) { %>
        <tr>
            <td><input name="discover-new" value="<%- index %>" class="discover-new" type="checkbox" alt="" data-index="<%- index %>" /></td>
            <td><%- hook.code %></td>
            <td><%- hook.title ? hook.title : "-" %></td>
            <td><% if (hook.block) { %><span class="label label-md label-success"><i class='glyphicon glyphicon-ok-circle'></i></span><% } else { %><span class="label label-md label-warning"><i class='glyphicon glyphicon-remove-circle'></i></span><% } %></td>
            <td><% if (hook.module) { %><span class="label label-md label-success"><i class='glyphicon glyphicon-ok-circle'></i></span><% } else { %><span class="label label-md label-warning"><i class='glyphicon glyphicon-remove-circle'></i></span><% } %></td>
        </tr>
        <% }); %>
        <tr>
            <td colspan="5"><i class='glyphicon glyphicon-arrow-up'></i> {intl l="Create this hooks"}</td>
        </tr>
    </tbody>
</table>
</script>

<script id="discover-missing" type="text/html">
    <table class="table table-striped table-condensed">
        <caption class="clearfix">
            {intl l='Your template does not support this hooks'}
        </caption>
        <thead>
        <tr>
            <th><input id="discover-missing-toggle" data-target=".discover-missing" type="checkbox" alt="{intl l="Toggle select all"}"/></th>
            <th>{intl l="Code"}</th>
            <th>{intl l="Title"}</th>
            <th>{intl l="Official"}</th>
        </tr>
        </thead>
        <tbody>
        <% _.each(hooks, function(hook, index) { %>
        <tr>
            <td><input name="discover-missing" value="<%- hook.id %>" class="discover-missing" type="checkbox" data-code="<%- hook.code %>" <% if (!hook.activate){ %>disabled<% }%>  /></td>
            <td><%- hook.code %></td>
            <td><%- hook.title %></td>
            <td><% if (hook.native) { %><span class="label label-md label-success"><i class='glyphicon glyphicon-ok-circle'></i></span><%
                } else { %><span class="label label-md label-warning"><i class='glyphicon glyphicon-remove-circle'></i></span><% } %></td>
        </tr>
        <% }); %>
        <tr>
            <td colspan="5"><i class='glyphicon glyphicon-arrow-up'></i> {intl l="Deactivate this hooks"}</td>
        </tr>
        </tbody>
    </table>
</script>

{/block}

{block name="javascript-last-call"}
{hook name="hooks.js" location="hooks-js" }
{/block}
