<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use \common\modules\blog\models\BlogBids;

$userIsSubscribed = false;
$cacheEmail = Yii::$app->session->get('user_email');
if ($cacheEmail!==false && BlogBids::find()->where(['email' => $cacheEmail])->exists()===true)
    $userIsSubscribed = true;
?>

<?php if ($userIsSubscribed===false): ?>
<div class="subsc_blog">
    <h2 class="subsc_blog_title"><?=\Yii::t('form', 'Liked? Subscribe up for updates!')?></h2>
    <div class="subsc_blog_txt"><?=\Yii::t('form', 'We will try to publish this section only useful and unique content for the market. Subscription allow to be the first to get notification about fresh articles.')?></div>

	<?php
    $model = new BlogBids;

    $form = ActiveForm::begin([
        'action' => '/blog/blog-bid/add',
        'enableClientValidation' => false,
        'options' => [
            'class' => 'subsc_blog_form blog-bid-form',
            'data-title' => $title,
            'data-form' => 'Подпись на обновления в блоге'
        ],
    ]); ?>

        <div class="message-box send_secce">Теперь вы подписаны на обновления блога.</div>

        <div class="message-box send_err" style="color:red; left: 26%; top: 44%;">Теперь вы подписаны на обновления блога.</div>

        <div class="content">

        	<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>

            <?php //echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>

            <?php echo $form->field($model, 'email', [
                'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>',
                'errorOptions' => []
            ])->textInput([
                'placeholder' => 'E-mail*'
            ]); ?>

            <?php echo Html::submitButton(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>

        </div>

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

</div>

<script type='text/javascript'>
    $('form.blog-bid-form').on('beforeSubmit', function(e) {
        var form = $(this), xhr = new XMLHttpRequest, filebool = false, file, data = new FormData();

        form.find('input, textarea').each(function(){
            data.append($(this).attr('name'), $(this).val());
        });

        xhr.open("POST", form.attr('action'), true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

        xhr.send(data);

        xhr.onreadystatechange = function()
        {
            if (xhr.readyState == 4){
                try {
                    var response = JSON.parse(xhr.responseText);
                } catch(e) {
                    var response = xhr.responseText;
                }

                form.find('.has-error').removeClass('has-error');

                if(response.success) {
                    if(form.find('.message-box.send_secce').length > 0) {
                        form.find('.message-box.send_secce').fadeIn('fast');
                        form.find('.content').css('visibility','hidden');

                        setTimeout(function(){
                            form.find('.message-box.send_secce').fadeOut('fast');
                            form.find('.content').css('visibility','visible');
                        }, 2000);
                    }

                    form.find('input:not(.not_clear), textarea').val('');

                    form.find('#files-zone').html('');
                    $('.dz-preview.dz-processing').remove();

                    dataLayer.push({
                        'event': 'UA_event',
                        'Catagory': form.data('tag'),
                        'Action': form.data('title'),
                        'Label': 'Успешно'
                    });

                    setInterval(function() {
                        form.parent('div').fadeOut(500);
                    }, 1600);
                }
                else {
                    var errors = [];
                    $.each(response, function(key, value) {
                        form.find('.field-'+key).addClass('has-error');
                        errors = errors.concat(value);
                    });

                    console.log(errors);

                    if(form.find('.message-box.send_err').length > 0)
                    {
                        form.find('.message-box.send_err').html(errors[0]);
                        form.find('.message-box.send_err').fadeIn('fast');

                        setTimeout(function(){
                            form.find('.message-box.send_err').fadeOut('fast');
                        }, 2000);
                    }

                    dataLayer.push({
                        'event': 'UA_event',
                        'Catagory': 'Ошибки',
                        'Action': form.data('form'),
                        'Label': errors
                    });
                }
            }
        }
    }).on('submit', function(e){
        return false;
    });
</script>
<?php endif; ?>