<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;

$this->title = 'Add redirect between campaigns';

$script =<<< JS
    $(document).ready(function(){
        $('body').on('beforeSubmit', 'form', function(){
            var sourceCampaign = $('#source-campaign').val();
            var destinationCampaign = $('#destination-campaign').val();
            if(sourceCampaign == '' || destinationCampaign == ''){
                alert('You have to select the source and the destination campaigns');
                return false;
            }
            return true;
        });
    });
JS;

$this->registerJs($script);

?>

<div class="manage-redirects">

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

    <div class="alert alert-warning">
        <span class='glyphicon glyphicon-warning-sign'></span> <?= "When redirecting from 'Active' or 'Paused' campaign, it will be terminated automatically" ?>
    </div>

    <?php $form = ActiveForm::begin(); ?>

    <div class="form-group">
        <label for="source-campaign"><?= 'Source Campaign' ?></label>

        <?= Select2::widget([
            'name' => 'source-campaign',
            'data' => $source_campaigns,
            'options' => [
                'placeholder' => 'Select campaign',
                'id' => 'source-campaign',
            ],
            'pluginEvents' => [
                'change' => 'function(){
                    $.ajax({
                        url: "' . Url::base(true) . '/campaigns/get-active-campaigns?selected_campaign_id=" + $(this).val() ,
                        method: "GET",
                        success: function(response){
                            console.log(response);
                            $("#destination-campaign").empty();
                            $.each(response["data"], function(index, item){
                                $("#destination-campaign").append("<option></option>");
                                $("#destination-campaign").append("<option value=" + item["_id"] + ">" + item["name"] + "</option>");
                            });
                        }
                    }); 
                }'
            ]
        ]) ?>
    </div>

    <div class="form-group">
        <label for="destination-campaign"><?= 'Destination Campaign' ?></label>

        <?= Select2::widget([
            'name' => 'destination-campaign',
            'data' => [],
            'options' => [
                'placeholder' => 'Select campaign',
                'id' => 'destination-campaign'
            ],
        ]) ?>
    </div>

    <div class="center-elements">
        <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success btn-expanded', 'id' => 'submit-button']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
