<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\components\Utilities;
use app\models\Node;
use yii\bootstrap\Modal;
use yii\mongodb\Query;

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

$this->registerCssFile('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css');

$script =<<< JS

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

        $('.campaign-generated-link-modal-button').click(function(e){
            e.preventDefault();
            $('#campaign-generated-link-modal').modal('show')
                .find('#campaign-generated-link-modal-content')
                .load($(this).attr('value'));
        });
    });

JS;

$this->registerJs($script);

?>

<div class="campaigns-index">

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

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

    <p>
        <?php if(Yii::$app->user->can('Admin')): ?>
            <?= Html::a('Create Campaign', [''],
                    [
                        'class' => 'create-campaign-modal-button btn btn-success btn-expanded',
                        'value' => Url::base(true) . '/campaigns/show-create-campaign-modal'
                    ])
                ?>

            <?= Html::a('Redirections', ['campaigns-redirections'], ['class' => 'btn btn-primary btn-expanded']) ?>
        <?php endif; ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            [
                'attribute' => 'name',
                'headerOptions' => ['style' => 'width: 18%;'],
            ],
            [
                'attribute' => 'formId',
                'label' => 'Form',
                'headerOptions' => ['style' => 'width: 12%;'],
                'filter' => ArrayHelper::map(Yii::$app->user->identity->is_admin ? Utilities::getAllForms() : Utilities::getFormsByUserPermissions(), 'id', 'name'),
                'value' => function($model){
                    return Utilities::getFormName($model->formId);
                }
            ],
            [
                'attribute' => 'destinationNodeId',
                'label' => 'Node',
                'headerOptions' => ['style' => 'width: 10%;'],
                'filter' => Yii::$app->user->identity->is_admin ? Utilities::getAllNodes() : Utilities::getNodeAndItsChildrenIDsAndNames(),
                'value' => function($model){
                    return Node::findOne($model->destinationNodeId)->name;
                }
            ],
            [
                'attribute' => 'status',
                'format' => 'raw',
                'headerOptions' => ['style' => 'width: 10%;'],
                'filter' => [
                    'Active'     => 'Active',
                    'Paused'     => 'Paused',
                    'Completed'  => 'Completed',
                    'Terminated' => 'Terminated',
                ],
                'value' => function($model){
                    if($model->status && $model->mustRedirectTo){
                        $redirect_to_campaign_id = explode('campaign_id=', $model->mustRedirectTo);
                        $campaign = \app\models\Campaign::findOne($redirect_to_campaign_id);
                        if($campaign){
                            $content = $model->status;
                            $content .= '<br><i class="not-set">(Redirected)</i>';
                            $content .= ' <span class="glyphicon glyphicon-info-sign" title="Redirected to ' . $campaign->name . '"></span>';
                            return $content;
                        }
                    }
                    return $model->status;
                }
            ],
            [
                'attribute' => 'startDate',
                'headerOptions' => ['style' => 'width: 10%;'],
                'value' => function($model){
                    return date('Y-m-d', strtotime($model->startDate));
                }
            ],
            [
                'attribute' => 'endDate',
                'format' => 'raw',
                'headerOptions' => ['style' => 'width: 10%;'],
                'value' => function($model){
                    return '<span dir="ltr">' . date('Y-m-d', strtotime($model->endDate)) . '</span>' . ($model->hasExtended ? '<br><i class="not-set">(Extended)</i>' : '');
                }
            ],
            [
                'label' => '<span title="All Records"><i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i></span>',
                'encodeLabel' => false,
                'headerOptions' => ['style' => 'width: 4%;'],
                'visible' => Yii::$app->user->can('Admin'),
                'format' => 'raw',
                'value' => function($model){
                    $res = (new Query())
                        ->from('forms_' . (string)$model->formId)
                        ->where([
                            'campaignId' => $model->_id
                        ])
                        ->count();
                    if($res == 0){
                        return $res;
                    }
                    return Html::a($res, ['collected-data', 'campaign_id' => (string)$model->_id]);
                }
            ],
            [
                'label' => '<span title="Uncompleted Records"><i class="fas fa-star-half-alt"></i></span>',
                'encodeLabel' => false,
                'headerOptions' => ['style' => 'width: 4%;'],
                'format' => 'raw',
                'value' => function($model){
                    $res = (new Query())
                        ->from('forms_' . (string)$model->formId)
                        ->where([
                            'campaignId' => $model->_id,
                            'isCompleted' => false,
                            'ownerNodeId' => [
                                '$in' => Utilities::getNodeAndItsChildrenIDs()
                            ]
                        ])
                        ->count();
                    if($res == 0){
                        return $res;
                    }
                    return Html::a($res, ['uncompleted-data', 'campaign_id' => (string)$model->_id]);
                }
            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'headerOptions' => ['style' => 'width: 7%;'],
                'template' => '{view} {update} {delete} {link}',
                'visibleButtons' => [
                    'view' => Yii::$app->user->can('Admin'),
                    'update' => function($model){
                        return Yii::$app->user->identity->is_admin && $model->status != 'Terminated' && ! Utilities::checkIfCampaignHasSubmittedData($model->_id);
                    },
                    'delete' => function($model){
                        return Yii::$app->user->identity->is_admin && $model->status != 'Terminated' && ! Utilities::checkIfCampaignHasSubmittedData($model->_id);
                    },
                ],
                'buttons' => [
                    'link' => function($url, $model){
                        return Html::a('<span class="glyphicon glyphicon-link"></span>', [''],
                        [
                            'class' => 'campaign-generated-link-modal-button',
                            'value' => Url::to(['campaigns/get-generated-link', 'id' => (string)$model->_id])
                        ]);
                    }
                ]
            ],
        ],
    ]); ?>
</div>

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

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

    Modal::end();
?>

<?php 
    Modal::begin([
        'header' => '<h3>' . 'Campaign Generated Link' . '</h3>',
        'id' => 'campaign-generated-link-modal',
        'size' => 'modal-md',
        'closeButton' => false
    ]);

    echo '<div id="campaign-generated-link-modal-content"></div>';

    Modal::end();
?>