
	{* Подключаем Tiny MCE *}
	{include file='tinymce_init.tpl'}

	<!-- Page header -->
	{capture name="buttons"}

	{/capture}

	{capture name="breadcrumb"}
		<a href="{$adminUrl}/subsctibe" class="breadcrumb-item">{$title}</a>
	{/capture}

	{capture name="showBy"}
	{/capture}

	{include file="components/page-header.tpl" buttons=$smarty.capture.buttons breadcrumb=$smarty.capture.breadcrumb showBy=$smarty.capture.showBy}
	<!-- /page header -->

    <div class="content">
	    <div class="row">
		    <div class="col-md-12">

	            <div class="card border shadow-sm">
		            <div class="card-header d-flex flex-wrap">
			            <h6 class="mb-0">{$title}</h6>
			            <div class="d-inline-flex ms-auto">
				            <span id="status"></span>
				            <a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
			            </div>
		            </div>
		            <div class="collapse show">
			            <div class="card-body">

				            <div class="row">
					            <div class="col-md-12">
						            <div class="progress mb-3">
							            <div class="progress-bar bg-success" style="width: 0%">
								            <span >0% Complete</span>
							            </div>
						            </div>
					            </div>
					            <div class="col-md-4">
						            <div class="form-group mb-3">
							            <label class="form-label is-visible">Начать рассылку с: <span id="gesendet"></span></label>
							            <input type="text" class="form-control" id="startFrom" autocomplete="off" name="startFrom" value="0">
							            <i>пользователя (введите 0, если хотите начать рассылку с самого начала)</i>
						            </div>
					            </div>
					            <div class="col-md-4">
						            <div class="form-group mb-3">
							            <label class="form-label is-visible">Количество писем за один проход:</label>
							            <input  type="text" class="form-control" id="limit" autocomplete="off" name="limit" value="1" />
						            </div>
					            </div>
					            <div class="col-md-4">
						            <div class="form-group mb-3">
							            <label class="form-label is-visible">Интервал в секундах между отправкой писем:</label>
							            <input  type="text" class="form-control" id="interval" autocomplete="off" name="interval" value="3"/>
						            </div>
					            </div>

					            <div class="col-md-12">
					                <div class="form-group mb-3">
					                    <label class="form-label is-visible {if isset($errors.title)}text-danger{/if}">Тема письма</label>
					                    <input type="text" class="form-control" name="subject" id="subscribe_subject"/>
					                </div>
						            <div class="form-group m-0">
							            <textarea id="subscribe_message" name="message" class="description"></textarea>
						            </div>
					            </div>

				            </div>
			            </div>
		            </div>
			    </div>
		    </div>
        </div>

        <div class="col-md-12 main main_buttons text-center">
            <button class="btn btn-sm btn-primary" id="subscribe_send" onclick="subscribe_send(); return false;">Разослать</button>
        </div>
    </div>

	<script>

        var total = {$total};

        $(function() {

            var subscribeButton = $('#subscribe_send');

	        $("#status").ajaxError(function(event, request, settings) {

	            $(this).html('<font color=\"red\">ошибка отправки</font>');
	            subscribeButton.attr("disabled", false);
	            var limit = $('#limit').val(), startAgain = parseInt($('#startFrom').val());
                startAgain = startAgain + limit;

	            $('#startFrom').val( startAgain );

	        });
            // subscribeButton.on('click', function() {
	        // subscribeButton.click(function() {
            //     console.log('qwe')
            //     $('#status').html('отправка ...');
            //     subscribeButton.attr("disabled", true);
            //     subscribeButton.text("Продолжить отправку");
			//
            //     senden( $('#startFrom').val() );
            //     return false;
            // });

        });

        function subscribe_send() {
            $('#status').html('отправка ...');
            $('#subscribe_send').attr("disabled", true);
            $('#subscribe_send').text("Продолжить отправку");

            senden( $('#startFrom').val() );
            return false;
        }

        function senden(startFrom) {

            var limit = $('#limit').val();
            var interval = $('#interval').val();
            var subject = $('#subscribe_subject').val();
            var message =  tinymce.get('subscribe_message').getContent();

            $.post("{$adminUrl}/subscribe", { action: 'send', subject: subject, message: message, startFrom: startFrom, interval: interval, limit: limit  }, function(data){
	            if (data) {
		            if (data.status === 200) {
			            $('#gesendet').text(data.count);
			            $('#startFrom').val(data.count);

			            var proc = Math.round( (100 * data.count) / total );
			            if ( proc > 100 ) proc = 100;

			            $('.progress-bar').width( proc + '%');
                        $('.progress-bar span').text( proc + '% Complete');

			            if (data.count >= total) {
				            $('#status').html('<font color=\"green\">отправка завершена</font>');
                            $('#subscribe_send').attr("disabled", false);
                            $('#subscribe_send').text("Отправка завершена");
                            new Noty({ text: 'Письма отправлены!', type: 'success', timeout: 1500 }).show();
			            } else {
				            setTimeout(" senden(" + data.count + ")", interval );
			            }
		            } else {
                        new Noty({ text: 'Ошибка отправки писем!', type: 'error', timeout: 1500 }).show();
                    }
	            }
            }, "json");

            return false;
        }
    </script>