@extends('layouts.auth')

@section('content')

<h4>Рассылка в ботах</h4>
<hr>

<textarea cols="30" rows="10" class="broadcast-text form-control" placeholder="Текст рассылки">{{$post->text}}</textarea>

<form class="mt-3">
    <div class="form-group-sm">
        <label for="exampleFormControlFile1">Загрузка файла</label>
        <input type="file" class="form-control-file form-control-sm" id="upload-file">
    </div>
    <div class="upload-progress-wrp progress mt-2" style="display: none">
        <div class="upload-progress progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
            <span class="upload-progress-percentage"></span>
        </div>
    </div>
</form>
<input type="text" class="broadcast-file form-control form-control-sm mt-3" placeholder="Ссылка на медиа или file_id" value="{{isset($post->file)?$post->file:''}}">
<input type="text" class="broadcast-speed form-control form-control-sm mt-3" placeholder="Скорость (мин: 1, макс: 30)" value="{{isset($post->speed)?$post->speed:''}}">
<input type="text" class="broadcast-offset form-control form-control-sm mt-3" placeholder="Смещение" value="{{isset($post->offset)?$post->offset:''}}">



<div class="buttons">
    @if(count($post->buttons)>0)
        @foreach($post->buttons as $key => $row)
            <div data-id="{{$key}}" class="button-row d-flex justify-content-around mt-3">


                <input type="text" data-id="{{$key}}" data-col-id="1" class="button_text form-control form-control-sm mr-1" placeholder="текст кнопки" value="{{$row[0]['text']}}">
                <input type="text" data-id="{{$key}}" data-col-id="1"  class="button_link form-control form-control-sm mr-1" placeholder="ссылка" value="{{$row[0]['url']}}">

                @if(!isset($row[1]))
                    <input type="text" data-id="{{$key}}" data-col-id="2"  class="button_text form-control form-control-sm mr-1" placeholder="текст кнопки" value="">
                    <input type="text" data-id="{{$key}}" data-col-id="2"  class="button_link form-control form-control-sm mr-1" placeholder="ссылка" value="">
                @else
                    <input type="text" data-id="{{$key}}" data-col-id="2"  class="button_text form-control form-control-sm mr-1" placeholder="текст кнопки" value="{{$row[1]['text']}}">
                    <input type="text" data-id="{{$key}}" data-col-id="2"  class="button_link form-control form-control-sm mr-1" placeholder="ссылка" value="{{$row[1]['url']}}">
                @endif

                <button data-id="{{$key}}" class="button_rm btn btn-secondary btn-sm"><i class="fas fa-minus-square"></i></button>
            </div>

        @endforeach
    @endif
</div>



<div class="add-button w-100 text-center mt-2">
    <i class=" fas fa-plus"></i>
</div>

<div class="custom-control custom-switch mt-3">
    <input type="checkbox" class="custom-control-input" id="switch1" {{$post->with_image=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch1">Рассылка с картинкой</label>
</div>

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switch4" {{$post->with_video=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch4">Рассылка с видео</label>
</div>

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switch5" {{$post->with_animation=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch5">Рассылка с анимацией</label>
</div>

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switch2" {{$post->with_keyboard=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch2">Рассылка с клавиатурой</label>
</div>

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switch3" {{$post->disable_web_page_preview=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch3">Выключить предпросмотр ссылки</label>
</div>


<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switch6" {{$post->check_members=="true"? "checked":""}}>
    <label class="custom-control-label" for="switch6">Тест аудитории</label>
</div>



<div class="d-flex flex-wrap">
    <button class="save-btn btn btn-sm flex-fill btn-primary mt-3 m-1">Сохранить+Тест</button>
    @if(Auth::id()!=4)

    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('vksound');">Рассылка vksound</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('ivksound');">Рассылка ivksound</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('filmsbot');">Рассылка good_serial_bot</button>
</div>

<div class="d-flex flex-wrap">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('stormbot');">Рассылка stormbot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('goodlib');">Рассылка goodlib</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('smotrikino');">Рассылка smotrikino</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('booksbot');">Рассылка booksbot</button>
</div>

<div class="d-flex flex-wrap">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('volume_robot');">Рассылка volume_robot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('music_telebot');">Рассылка music_telebot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('player_robot');">Рассылка player_robot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('fuck_dmca_bot');">Рассылка fuck_dmca_bot</button>
</div>

<div class="d-flex flex-wrap">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('knigavsluh');">Рассылка knigavsluh</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('flibusta');">Рассылка flibusta</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('placemeet');">Рассылка placemeet</button>
    @endif
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('lokkkatorbot');">Рассылка lokkkatorbot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('lovebot');">Рассылка lovebot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="startBroadcast('gdedrug');">Рассылка gdedrug</button>
</div>

<hr>
<div class="row">

@foreach($posts as $post)

    <div class="col-md-4 mb-3" style="font-size: 10px;">



            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">
                        <div class="d-flex justify-content-between">
                            <b>{{$post['date']}}: {{$post['bot']}}</b>
                            <a href="javascript:void(0)" style="color: red" onclick="deletePending({{$post['id']}})"><i class="fas fa-times"></i></a>
                        </div>
                    </h5>
                    <div class="card-text">
                        <i>{{$post['post']->text}}</i>
                    </div>
                </div>
            </div>


    </div>

@endforeach
</div>

<hr>


<input type="text" id="datetimepicker" class="form-control form-control-sm" placeholder="Отложенная рассылка">

<div class="d-flex flex-wrap">
    @if(Auth::id()!=4)

    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('vksound');">vksound</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('ivksound');">ivksound</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('stormbot');">stormbot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('filmsbot');">good_serial_bot</button>
</div>


<div class="d-flex flex-wrap">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('booksbot');">booksbot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('goodlib');">goodlib</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('smotrikino');">smotrikino</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('volume_robot');">volume_robot</button>
</div>

<div class="d-flex flex-wrap">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('music_telebot');">music_telebot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('player_robot');">player_robot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('fuck_dmca_bot');">fuck_dmca_bot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('filmsbot');">good_serial_bot</button>
</div>

<div class="d-flex flex-wrap" style="padding-bottom: 400px;">
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('knigavsluh');">knigavsluh</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('flibusta');">flibusta</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('placemeet');">placemeet</button>

    @endif
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('lokkkatorbot');">lokkkatorbot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('lovebot');">lovebot</button>
    <button class="btn btn-sm flex-fill btn-secondary mt-3 m-1" onclick="savePendingBroadcast('gdedrug');">gdedrug</button>
</div>

<script>


    var Upload = function (file) {
        this.file = file;
    };

    Upload.prototype.getType = function() {
        return this.file.type;
    };
    Upload.prototype.getSize = function() {
        return this.file.size;
    };
    Upload.prototype.getName = function() {
        return this.file.name;
    };
    Upload.prototype.doUpload = function () {
        var that = this;
        var formData = new FormData();
        var method = "";
        // add assoc key values, this will be posts values
        formData.append("chat_id", "-1001124395264");

        if(this.getType() == "image/gif"){
            formData.append("animation", this.file, this.getName());
            method = "sendAnimation";
        }
        if(this.getType() == "video/mp4"){
            formData.append("video", this.file, this.getName());
            method = "sendVideo";
        }
        if(this.getType() == "image/jpeg" || this.getType() == "image/jpg" || this.getType() == "image/png"){
            formData.append("photo", this.file, this.getName());
            method = "sendPhoto";
        }

        $('.upload-progress-wrp').show();

        $.ajax({
            type: "POST",
            url: "https://api.telegram.org/bot1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A/"+method,
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', that.progressHandling, false);
                }
                return myXhr;
            },
            success: function (data) {
                if(data.ok==false){
                    return alert("Загрузка файла не удалась!")
                }


                if(this.getType() == "image/gif"){
                    var file_id = data.result.animation.file_id;
                }
                if(this.getType() == "video/mp4"){
                    var file_id = data.result.video.file_id;
                }
                if(this.getType() == "image/jpeg" || this.getType() == "image/jpg" || this.getType() == "image/png"){
                    var file_id = data.result.photo[data.result.photo.length-1].file_id;
                }
                $('.broadcast-file').val(file_id);
            }.bind(this),
            error: function (error) {
                // handle error
            },
            async: true,
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            timeout: 60000
        });
    };

    Upload.prototype.progressHandling = function (event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
            percent = Math.ceil(position / total * 100);
        }
        // update progressbars classes so it fits your code
        $(".upload-progress").css("width", +percent + "%");
        $(".upload-progress-percentage").text(percent + "%");
    };
</script>

<script>
    function deletePending(id){
        $.post('/admin/deletePending',{
            id: id,
            _token:$('meta[name="csrf-token"]').attr('content')
        },function () {
            location.reload()
        })
    }

    $(document).ready(function() {
        $("#upload-file").on("change", function (e) {
            var file = $(this)[0].files[0];
            var upload = new Upload(file);
            upload.doUpload();
        });

        $.datetimepicker.setLocale('ru-RU');
        $('#datetimepicker').datetimepicker({
            format:'d.m.Y H:00',
        });
        function getFormattedDate(date) {
            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear().toString().slice(2);
            return day + '-' + month + '-' + year;
        }
    });
</script>
<script>

    function savePendingBroadcast(bot){
        $.post('/admin/savePendingBroadcast',{
            bot:bot,
            date: $('#datetimepicker').val(),
            _token:$('meta[name="csrf-token"]').attr('content')
        },function (data) {
            if(data.error){
                return $.notify({
                    message: data.error
                });
            }
            $.notify({
                message: "Отложенная рассылка сохранена"
            });
            location.reload()
        });
    }

    $('.button_rm').click(function(){
        var id = $(this).data('id');
        $('.button-row[data-id='+id+']').remove();
    });

    function getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min; //Максимум и минимум включаются
    }


    $('.add-button').click(function () {
        var row_id = getRandomIntInclusive(1,9999999999);
        $('.buttons').append(`<div data-id="${row_id}" class="button-row d-flex justify-content-around mt-3"> <input type="text" data-id="${row_id}" data-col-id="1" class="button_text form-control form-control-sm mr-1" placeholder="текст кнопки"> <input type="text" data-id="${row_id}" data-col-id="1" class="button_link form-control form-control-sm mr-1" placeholder="ссылка" > <input type="text" data-id="${row_id}" data-col-id="2" class="button_text form-control form-control-sm mr-1" placeholder="текст кнопки"> <input type="text" data-id="${row_id}" data-col-id="2"  class="button_link form-control form-control-sm mr-1" placeholder="ссылка" > <button data-id="${row_id}" class="button_rm btn btn-secondary btn-sm"><i class="fas fa-minus-square"></i></button> </div>`);
        $('.button_rm').click(function(){
            var id = $(this).data('id');
            $('.button[data-id='+row_id+']').remove();
        });
    });




    function getKeyboard(){


        var inline_keyboard = [];



        $('.button-row').each(function(){
            var row_id = $(this).data('id');

            var row = [];

            var text_one = $(`.button_text[data-id="${row_id}"][data-col-id="1"]`).val();
            var link_one = $(`.button_link[data-id="${row_id}"][data-col-id="1"]`).val();


            if(text_one.length>=1 && link_one.length>=1){
                row.push({
                    text: text_one,
                    url: link_one,
                })
            }

            var text_two = $(`.button_text[data-id="${row_id}"][data-col-id="2"]`).val();
            var link_two = $(`.button_link[data-id="${row_id}"][data-col-id="2"]`).val();

            if(text_two.length>=1 && link_two.length>=1){
                row.push({
                    text: text_two,
                    url: link_two,
                })
            }

            if(row.length>0){
                inline_keyboard.push(row)
            }

            //var name = $(this).val();
            //var link = $('.button_link[data-id='+id+']').val();
            //buttons.push({name:name,link:link})
        });

        return JSON.stringify(inline_keyboard);
    }



    $('.save-btn').click(function () {
        /*
        var buttons = [];
        $('.button_text').each(function(){
            var id = $(this).data('id');
            var name = $(this).val();
            var link = $('.button_link[data-id='+id+']').val();
            buttons.push({name:name,link:link})
        });

         */

        var text = $('.broadcast-text').val();
        var file = $('.broadcast-file').val();
        var speed = $('.broadcast-speed').val();
        var offset = $('.broadcast-offset').val();

        var with_image = $('#switch1').prop("checked");
        var with_keyboard = $('#switch2').prop("checked");
        var with_video = $('#switch4').prop("checked");
        var with_animation = $('#switch5').prop("checked");
        var check_members = $('#switch6').prop("checked");
        var disable_web_page_preview = $('#switch3').prop("checked");
        $.post('/admin/savePost',{
            text:text,
            file:file,
            buttons:getKeyboard(),
            with_image:with_image,
            with_animation:with_animation,
            with_image:with_image,
            with_video:with_video,
            check_members:check_members,
            speed: speed,
            offset:offset,
            with_keyboard:with_keyboard,
            disable_web_page_preview:disable_web_page_preview,
            _token:$('meta[name="csrf-token"]').attr('content')
        },function () {
            $.notify({
                message: "Пост сохранён."
            });
        });
    });


    function startBroadcast(bot) {
        $.post('/admin/startBroadcast',{
            bot:bot,
            _token:$('meta[name="csrf-token"]').attr('content')
        },function () {
            $.notify({
                message: "Запрос на рассылку отправлен."
            });
        });
    }


</script>

@endsection
