<?php

namespace App\Console\Commands;

use App\Log;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use PDO;
use AsyncRequest\AsyncRequest;
use AsyncRequest\Request;
use AsyncRequest\Response;

class broadcast extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'broadcast:start {bot} {post}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $redis = Redis::connection();
        $bot = $this->argument('bot');

        $settings = [
            'vksound' => [
                'db' => [
                    'name' => 'vksound',
                    'table' => 'users'
                ],
                'token' => "547355372:AAEnjZhqEoW3tyFUxL3klwVNWznwZ01Asew"
            ],
            'ivksound' => [
                'db' => [
                    'name' => 'vksound',
                    'table' => 'i_users'
                ],
                'token' => "743001682:AAE_g3fvaBImyAxLRDhhfX-rZntK4Qr-jkk"
            ],
            'stormbot' => [
                'db' => [
                    'name' => 'stormbot',
                    'table' => 'users'
                ],
                'token' => "1348182895:AAEqKgRLtb9Eyf1wanX_lrvtVlL2rDtaY3Q"
            ],
            'booksbot' => [
                'db' => [
                    'name' => 'booksbot',
                    'table' => 'users'
                ],
                'token' => "1342416920:AAFUOJ5MkAC_31PdEpKUB0qYI34rfGFvbAY"
            ],
            'goodlib' => [
                'db' => [
                    'name' => 'goodlib',
                    'table' => 'users'
                ],
                'token' => "1287759048:AAEDiTPrgKYzNKguK6y6hXwV3-tWO2cpK6I"
            ],
            'smotrikino' => [
                'db' => [
                    'name' => 'smotrikino',
                    'table' => 'users'
                ],
                'token' => "1180904155:AAFqU0597L_7ckXX0FOF5i3DhiyU4QTEyVA"
            ],
            'music_telebot' => [
                'db' => [
                    'name' => 'deezer',
                    'table' => 'm_users'
                ],
                'token' => "1483208632:AAGQjY69u7pYP59yRUHY94vYAGy10kwt7_Q"
            ],
            'knigavsluh' => [
                'db' => [
                    'name' => 'knigavsluh',
                    'table' => 'users'
                ],
                'token' => "1634226596:AAGS5cBHczuhOdJEkPpq7WgKKwhGl4aUK_8"
            ],
            'volume_robot' => [
                'db' => [
                    'name' => 'deezer',
                    'table' => 'v_users'
                ],
                'token' => "1076599625:AAF1hpjPDkYEc5Mf8YbXeSLYMXx422mUrhQ"
            ],
            'player_robot' => [
                'db' => [
                    'name' => 'deezer',
                    'table' => 'p_users'
                ],
                'token' => "1070970931:AAF_2Zyu3xMKaD1yVBM-fulRdfHCyyyRbwQ"
            ],
            'fuck_dmca_bot' => [
                'db' => [
                    'name' => 'deezer',
                    'table' => 'd_users'
                ],
                'token' => "1483792523:AAFGpyHaBluuvKrazBX99LU-hX9vRJbWX64"
            ],
            'filmsbot' => [
                'db' => [
                    'name' => 'filmsbot',
                    'table' => 'users'
                ],
                'token' => "1308657528:AAEMlKdM8_Tk7HALvOYkIbcpAweuE4LvoOk"
            ],
            'lokkkatorbot' => [
                'db' => [
                    'name' => 'lokkkatorbot',
                    'table' => 'users'
                ],
                'token' => "1666782758:AAEySPI9tHSUkrkvErcKikNRsAY4WHpPpSw"
            ],
            'lovebot' => [
                'db' => [
                    'name' => 'lokkkatorbot',
                    'table' => 'l_users'
                ],
                'token' => "1644807262:AAHQiPVvI51dBS1dbgCrh7If-j0evkYAdk4"
            ],

            'gdedrug' => [
                'db' => [
                    'name' => 'lokkkatorbot',
                    'table' => 'a_users'
                ],
                'token' => "1787326959:AAGu2lUUmO5qcjG2RAjy5t9hmRKlvWMgIbI"
            ],

            "flibusta" => [
                'db' => [
                    'name' => 'flibusta',
                    'table' => 'users'
                ],
                'token' => "1767119934:AAFx43RY6z8erUtyfSUR8UkqjZIPoDaMrJE"
            ],
            "placemeet" => [
                'db' => [
                    'name' => 'placemeet',
                    'table' => 'users'
                ],
                'token' => "1608638571:AAHt3_6uAkMXa1O5eqsveO2AR0TL8dVe67U"
            ]



        ];




        /* * * * * * */
        /* * * * * * */
        /* * * * * * */
        /* MAKE POST */

        $post = json_decode($this->argument('post'));
        $params = [];
        if ($post->with_keyboard == "true") {
            $keyboard = json_encode(['inline_keyboard' => $post->buttons]);
            $params['reply_markup'] = $keyboard;
        }
        if ($post->with_image == "true") {
            $params['photo'] = $post->file;
            $params['caption'] = $post->text;
        } else if ($post->with_video == "true") {
            $params['video'] = $post->file;
            $params['caption'] = $post->text;
        } else if ($post->with_animation == "true") {
            $params['animation'] = $post->file;
            $params['caption'] = $post->text;
        } else if ($post->check_members == "true") {
            $params['action'] = "typing";
        } else {
            $params['text'] = $post->text;
        }
        if ($post->disable_web_page_preview == "true") {
            $params['disable_web_page_preview'] = true;
        }
        $params['parse_mode'] = "markdown";

        $speed = $post->speed;
        /* MAKE POST */
        /* * * * * * */
        /* * * * * * */
        /* * * * * * */


        if ($bot != "test") {
            $db_user = 'dev';
            $db_pass = 'abcde4815162342';
            $db_dsn = "mysql:host=127.0.0.1;dbname={$settings[$bot]['db']['name']};charset=utf8mb4";
            $db_opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false,];
            $pdo = new PDO($db_dsn, $db_user, $db_pass, $db_opt);

            if($bot == "vksound" or $bot == "ivksound"){
                $stmt = $pdo->prepare("SELECT * FROM {$settings[$bot]['db']['table']} WHERE adblock=0");
            }else{
                $stmt = $pdo->prepare("SELECT * FROM {$settings[$bot]['db']['table']}");
            }
            $stmt->execute();
            $users = $stmt->fetchAll();


            $count_users = count($users);
            $i = 0;
            $percents = 0;
            $this->success = 0;
            $start_time = time();
            $queue = 0;
            $asyncRequest = new  AsyncRequest();
            $asyncRequest->setParallelLimit(20);

            $this->sendMessageAdmins($bot);

            $redis->set("{$bot}_all_count", $count_users);
            foreach ($users as $user) {

                $i = $i + 1;
                if (round($i / $count_users * 100) > $percents) {
                    $percents = round($i / $count_users * 100);
                    $redis->publish("update", json_encode(['bot' => $bot, 'progress' => $percents]));
                    $redis->set($bot, $percents);
                }


                if($i>=$post->offset){
                    $params['chat_id'] = $user['chat_id'];
                    if ($post->with_image == "true") {
                        $url = "https://api.telegram.org/bot{$settings[$bot]['token']}/sendPhoto";
                    } else if ($post->with_video == "true") {
                        $url = "https://api.telegram.org/bot{$settings[$bot]['token']}/sendVideo";
                    } else if ($post->with_animation == "true") {
                        $url = "https://api.telegram.org/bot{$settings[$bot]['token']}/sendAnimation";
                    } else if ($post->check_members  == "true") {
                        $url = "https://api.telegram.org/bot{$settings[$bot]['token']}/sendChatAction";
                    } else {
                        $url = "https://api.telegram.org/bot{$settings[$bot]['token']}/sendMessage";
                    }

                    $request = new Request($url);
                    $asyncRequest->enqueue($request, function (Response $response) {
                        $res = $response->getBody();
                        echo $res."\n";
                        $res = json_decode($res);
                        if (isset($res->ok) and $res->ok == true) {
                            $this->success++;
                        }
                    });
                    $request->setOption(CURLOPT_POSTFIELDS, $params);
                    $queue++;
                    if($queue >= $speed) {
                        $asyncRequest->run();
                        $queue = 0;
                        $redis->set("{$bot}_last_id", $i);
                        $asyncRequest = new AsyncRequest();
                    }
                }
            }

            if($queue > 0) {
                $asyncRequest->run();
                $queue = 0;
                $redis->set("{$bot}_last_id", $i);
                $asyncRequest = new AsyncRequest();
            }

            $broadcast_time = round((time() - $start_time) / 60);

            $text = "Рассылка {$bot}:" . PHP_EOL;
            $text .= "Дата: " . date('d.m.Y') . PHP_EOL;
            $text .= "Время выполнения: {$broadcast_time} мин." . PHP_EOL;
            $text .= "Успешно: {$this->success}/{$count_users}" . PHP_EOL;

            if($bot=="vksound" or $bot=="ivksound"){
                $this->sendMessageAdmins($text);
            }else{
                $this->sendMessageAdmins($text,false);
            }

            $log_json = ["bot" => $bot,"date" => date('d.m.Y'),"time" => $broadcast_time,"success" => $this->success,"all" => $count_users];
            $log = new Log();
            $log->text = json_encode($log_json);
            $log->save();

        }else{
            $token =  "1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A";

            $users = [
                1250349080,
                271592734,
                1257621018,
                1237730106,
                794317585,
                1062003496
            ];

            foreach ($users as $user){
                $params['chat_id'] = $user;
                if($post->with_image == "true"){
                    $this->api("sendPhoto",$params,$token);
                }else if($post->with_video == "true"){
                    $this->api("sendVideo",$params,$token);
                }else if($post->with_animation == "true"){
                    $this->api("sendAnimation",$params,$token);
                }else{
                    $this->api("sendMessage",$params,$token);
                }
            }
        }
    }


    private function sendMessageAdmins($text,$guest=true){
        $text = str_replace("_","*_*",$text);
        $this->api("sendMessage",[
            'text'=>$text,
            'chat_id'=> 1250349080
        ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");
        $this->api("sendMessage",[
            'text'=>$text,
            'chat_id'=> 271592734
        ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");


        $this->api("sendMessage",[
            'text'=>$text,
            'chat_id'=> 794317585
        ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");


        $this->api("sendMessage",[
            'text'=>$text,
            'chat_id'=> 1062003496
        ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");




        if($guest==false){
            $this->api("sendMessage",[
                'text'=>$text,
                'chat_id'=> 1257621018
            ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");

            $this->api("sendMessage",[
                'text'=>$text,
                'chat_id'=> 1237730106
            ],"1307017460:AAF_DfPVihMEE22UzxVCFi2yh3kzBDrLe8A");
        }
    }

    public function api($method,$params,$token){
        if(!isset($params['parse_mode'])) {
            $params['parse_mode'] = "markdown";
        }
        if(isset($params['inline_keyboard'])) {
            $params['reply_markup'] = json_encode(['resize_keyboard' => true, 'inline_keyboard' => $params['inline_keyboard']]);
            unset($params['inline_keyboard']);
        }
        if(isset($params['keyboard'])) {
            $params['reply_markup'] = json_encode(['resize_keyboard' => true, 'keyboard' => $params['keyboard']]);
            unset($params['keyboard']);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,  CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$token}/{$method}");
        $data = curl_exec($ch);
        $data = json_decode($data);
        curl_close($ch);
        return $data;
    }
}
