<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;
use app\components\Utilities;
use kartik\editable\Editable;
use yii\bootstrap\Modal;

$this->title = Yii::t('app', 'Forms');

$script =<<< JS

    $(document).ready(function(){
        $('.create-view-modal-button').click(function(e){
            e.preventDefault();
            $('#create-view-modal').modal('show')
                .find('#create-view-modal-content')
                .load($(this).attr('value'));
        });
    });

JS;

$this->registerJs($script);

?>

<div class="forms-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= Utilities::getSessionAlertContainer('form_saved', 'success') ?>
    <?= Utilities::getSessionAlertContainer('form_status_changed', 'success') ?>

    <?php if(Yii::$app->session->hasFlash('active_campaign_found')): ?>
        <div class="alert alert-danger" style="text-align: center;">
            <?= Yii::$app->session->getFlash('active_campaign_found') ?>
            <div style="margin-top: 10px;">
                <?= Html::a('Display active campaign related to form', [
                    'campaigns/index',
                        'CampaignSearch[formId]' => Yii::$app->session->getFlash('active_campaign_found_form_id'),
                        'CampaignSearch[status]' => 'Active'
                ], ['class' => 'btn btn-default']) ?>
            </div>
        </div>
    <?php endif; ?>

    <p>
        <?php if(Yii::$app->user->can('Admin')): ?>
            <?= Html::a(Yii::t('app', 'Add Form'), ['form-builder'], ['class' => 'btn btn-success btn-expanded']) ?>
        <?php endif; ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            [
                'attribute' => 'name',
                'headerOptions' => ['style' => 'width: 30%;'],
            ],
            [
                'attribute' => 'type',
                'format' => 'raw',
                'headerOptions' => ['style' => 'width: 15%;'],
                'filter' => [
                    'restricted' => 'Restricted',
                    'global'     => 'Global',
                ],
                'value' => function($model){
                    if(! Yii::$app->user->can('Admin')){
                        return ucfirst($model->type);
                    }
                    return Editable::widget([
                        'name' => 'type',
                        'model' => $model,
                        'attribute' => 'type',
                        'asPopover' => true, 
                        'closeOnBlur' => true,
                        'displayValue' => $model->type,
                        'displayValueConfig' => [
                            'restricted' => 'Restricted',
                            'global'     => 'Global',
                        ],
                        'format' => Editable::FORMAT_LINK,
                        'formOptions' => ['action' => Url::base(true) . '/forms/change-type?id=' . $model->_id, 'method' => 'POST'],
                        'preHeader' => 'Edit ',
                        'header' => 'Type',
                        'footer' => '{buttons}' . Html::a('<i class="glyphicon glyphicon-ban-circle"></i>', [''], ['class' => 'btn btn-sm btn-danger close-editable']),
                        'buttonsTemplate' => '{submit}' . (Yii::$app->language == 'ar' ? ' ' : ''),
                        'data' => [
                            'restricted' => 'Restricted',
                            'global'     => 'Global',
                        ],
                        'size'=> 'md',
                        'inputType' => Editable::INPUT_DROPDOWN_LIST,
                        'options' => ['id' => 'form_type_' . $model->_id],
                        'placement' => Yii::$app->language == 'en' ? 'top top-right' : 'top top-left'
                    ]);
                }
            ],
            [
                'attribute' => 'status',
                'format' => 'raw',
                'headerOptions' => ['style' => 'width: 15%;'],
                'visible' => Yii::$app->user->can('Admin'),
                'filter' => [
                    'Active' => 'Active',
                    'Inactive' => 'Inactive',
                ],
                'value' => function($model){
                    $content = '<div style="display: flex; justify-content: space-between;">';
                    $content .= '<span>' . $model->status . '</span>';
                    $style = 'color: ';
                    $icon = '';
                    $message = '';
                    if($model->status == 'Active'){
                        $icon = 'remove';
                        $style .= 'red';
                        $message = 'Are you sure you want to deactivate this form?';
                        $message .= "\n" . 'If you confirm, the users will not be able to submit it or display its data and related views.';
                        $message .= "\n" . 'And the admin will not be able to update it.';
                        $message .= "\n" . 'And if there an active campaign at least, you will have to terminate it firstly before deactivating the form.';
                    }
                    else{
                        $icon = 'ok';
                        $style .= 'green';
                        $message = 'Are you sure you want to activate this form?';
                        $message .= "\n" . 'If you confirm, all operations related to the form will be activated (submit form, display its data and views, create new view)';
                    }
                    $content .= Html::a('<span class="glyphicon glyphicon-' . $icon . '" style="' . $style . '"></span>', 
                        [
                            'change-status', 'id' => (string)$model->_id, 'action' => ($model->status == 'Active' ? 'deactivate' : 'activate')
                        ], [
                            'data' => [
                                'method' => 'POST',
                                'confirm' => $message
                            ]
                        ]);
                    $content .= '</div>';
                    return $content;
                }
            ],
            [
                'attribute' => 'createdAt',
                'headerOptions' => ['style' => 'width: 15%;'],
                'value' => function($model){
                    return date('Y-m-d H:i', strtotime($model->createdAt));
                }
            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'headerOptions' => ['style' => 'width: 12%;'],
                'template' => '{render} {submissions} {create-view} {update} {delete} {manage-children-forms}',
                'visibleButtons' => [
                    'render' => function($model) use ($forms_permissions){
                        if(Yii::$app->user->can('Admin')){
                            return true;
                        }
                        if($forms_permissions){
                            foreach($forms_permissions as $group){
                                foreach($group as $form => $permissions){
                                    if($model->_id == $form){
                                        if($permissions['submit']){
                                            return true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    },
                    'update' => function($model){
                        return Yii::$app->user->can('Admin') && Utilities::canUpdateForm($model->_id);
                    },
                    'submissions' => function($model) use ($forms_permissions){
                        if(Yii::$app->user->can('Admin')){
                            return true;
                        }
                        if($forms_permissions){
                            foreach($forms_permissions as $group){
                                foreach($group as $form => $permissions){
                                    if($model->_id == $form){
                                        if($permissions['read']){
                                            return true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    },
                    'create-view' => function($model) use ($forms_permissions){
                        if(Yii::$app->user->can('Admin')){
                            return true;
                        }
                        if($forms_permissions){
                            foreach($forms_permissions as $group){
                                foreach($group as $form => $permissions){
                                    if($model->_id == $form){
                                        if($permissions['create-view']){
                                            return true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    },
                    'manage-children-forms' => function($model){
                        return Yii::$app->user->can('Admin') && Utilities::checkIfFormHasChildrenForms($model->_id);
                    },
                    'delete' => function($model){
                        return Yii::$app->user->can('Admin');
                    }
                ],
                'buttons' => [
                    'render' => function($url, $model){
                        return Html::a('<span class="glyphicon glyphicon-send"></span>', ['render-form', 'id' => (string)$model->_id], ['title' => 'Render Form', 'style' => 'margin-right: 5px;']);
                    },
                    'update' => function($url, $model){
                        return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['update-form', 'id' => (string)$model->_id], ['style' => 'margin-right: 5px;']);
                    },
                    'submissions' => function($url, $model){
                        return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['submissions', 'id' => (string)$model->_id], ['title' => 'Submissions', 'style' => 'margin-right: 5px;']);
                    },
                    'create-view' => function($url, $model){
                        // The Admin can create default view to allow all normal users access this view if they have permission to read form data
                        $default_view = Yii::$app->user->can('Admin') ? true : false;
                        $domains = Utilities::checkFormAvailableDomains((string)$model->_id);
                        if(count($domains) == 1){
                            return Html::a('<span class="glyphicon glyphicon-sunglasses"></span>', 
                                ['/views/builder', 'form_id' => (string)$model->_id, 'domain' => 'fields', 'default_view' => $default_view], 
                                ['title' => 'Create View', 'style' => 'margin-right: 5px;']);
                        }
                        return Html::a('<span class="glyphicon glyphicon-sunglasses"></span>', [''],
                            [
                                'class' => 'create-view-modal-button',
                                'value' => Url::to(['/forms/show-create-view-modal', 'form_id' => (string)$model->_id])
                            ]);
                    },
                    'manage-children-forms' => function($url, $model){
                        return Html::a('<span class="glyphicon glyphicon-link"></span>', ['manage-children-forms-visible-fields', 'id' => (string)$model->_id], ['title' => 'Manage Fields of Children Forms', 'style' => 'margin-right: 5px;']);
                    },
                ]
            ],
            [
                'label' => '',
                'headerOptions' => ['style' => 'width: 7%;'],
                'format' => 'raw',
                'value' => function($model){
                    $content = '';
                    $content .= Html::a('<i class="fa fa-binoculars"></i>', ['views/index', 'ViewSearch[formId]' => (string)$model->_id]);
                    $content .= ' &nbsp; ';
                    $content .= Html::a('<i class="fa fa-map"></i>', ['campaigns/index', 'CampaignSearch[formId]' => (string)$model->_id]);
                    return $content;
                }
            ],
        ],
    ]); ?>
</div>

<?php 
    Modal::begin([
        'header' => '<h3>' . 'Create View' . '</h3>',
        'id' => 'create-view-modal',
        'size' => 'modal-md',
        'closeButton' => false
    ]);

    echo '<div id="create-view-modal-content"></div>';

    Modal::end();
?>