<?php

namespace App\TelegramBot\Handlers;

use App\Models\ads;
use App\Models\audio_playlists;
use App\Models\audio_search_cache;
use App\Models\comments_cache;
use App\Models\flibusta;
use App\Models\library;
use App\Models\serials;
use App\Models\subscriptions;
use App\TelegramBot\Api;
use App\TelegramBot\Keyboard\Keyboard;
use App\TelegramBot\Keyboard\BRow;
use App\Models\user;
use PhpParser\Node\Expr\Cast\Object_;
use CURLFile;

class MainHandler{


    public function __construct($user,$token)
    {


        $this->groups = [
            "-1001361950663",
            "-1001205903044",
            "-1001408637102",
            "-1001338911760",
            "-1001483902189",

            "-1001434366235",
            "-1001383094530",
            "-1001465697118",
            "-1001463379102",
            "-1001187276689",

            "-1001202532547",
            "-1001286731259",
            "-1001440578314",
            "-1001359574365",
            "-1001410799834",

            "-1001247332959",
            "-1001195485059",
            "-1001484982783",
            "-1001437025869",
            "-1001492414282",



        ];

        $this->user = $user;
        $this->api = new Api($user->chat_id,$token);
        $this->defaultMedia = "https://telegra.ph/file/a80b2d6e1955b177fb8dc.mp4";
    }

    public function main(){
        $kb = new Keyboard();
        $kb = $kb->addRow(BRow::createRow()->addButton("📖 Поиск книги",['action'=>'search@book'])->addButton("🎵 Поиск аудиокниги",['action'=>'search@abook'])->get());
        $kb = $kb->addRow(BRow::createRow()->addButton("👥 Чат",['action'=>'main@chat'])->get());
        $kb = $kb->get($this->user);
        $this->api->execute("sendMessage",[
            "text" => "Привет 😊\n\nЯ найду для тебя любую книгу в библиотеке Флибусты, а так же аудиокниги из большой базы.\n\nИспользуй кнопки ниже, для выбора режима поиска.",
            "keyboard" => $kb
        ]);
    }

    public function chat(){
        $this->api->execute("sendMessage",[
            "text" => "Наш чат: [Book BOARD ЧАТ](https://t.me/book_board_chat)",
            "inline_keyboard"=> [
                [['text'=> "Перейти в чат","url"=>"https://t.me/book_board_chat"]]
            ]
        ]);
    }

    public function search($data){
        $this->api->execute("sendMessage",[
            "text" => "Введите поисковый запрос:"
        ]);
    }

    public function comments(){
        $this->api->execute("sendMessage",[
            "text" => "Раздел комментариев в разработке."
        ]);
    }

    public function getBook($data){
        $id = $data->data[0];
        $type = $data->data[1];
        $pdf = $data->data[2];

        $types = [
            "1" => "fb2",
            "2" => "epub",
            "3" => "mobi"
        ];


        if($pdf==0){


            $search_local = library::where('fb_id',$id)->first();
            if($search_local){
                $file_id = $search_local->{$types[$type]};

                $res = $this->api->execute("sendDocument",[
                    "chat_id" => $this->groups[rand(0,19)],
                    "document" => $file_id,
                    "token" => "1342416920:AAFUOJ5MkAC_31PdEpKUB0qYI34rfGFvbAY"
                ]);

                $this->api->execute("sendDocument",[
                    "document" => $file_id,
                    "caption" => "Подключайтесь к нашему резервному боту - 📚 [@Knigavsluh_bot](http://t.me/Knigavsluh_bot?start=Reder)"
                ]);

                $ads = ads::where('count','>',0)->get();

                foreach ($ads as $ad){
                    $check = subscriptions::where('chat_id',$this->user->chat_id)->where('ad_id',$ad->id)->first();
                    if(!$check){
                        $subscription = new subscriptions();
                        $subscription->chat_id = $this->user->chat_id;
                        $subscription->ad_id = $ad->id;
                        $subscription->save();
                        $ad->count-=1;
                        $ad->save();
                        return $this->api->execute("sendMessage",[
                            "text" => $ad->text
                        ]);
                    }
                }
                return true;
            }


            $url = "http://flibusta.site/b/{$id}/fb2";
            $res = $this->api->execute("sendMessage",[
                "text" => "Пожалуйста, подождите, мы подготавливаем книгу."
            ]);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
            curl_setopt($ch, CURLOPT_URL, $url);
            $data = curl_exec($ch);
            curl_close($ch);
            $dir_name = "/var/www/html/booksbot/storage/tmp_files/".$this->generateRandomString();
            if(mkdir($dir_name, 0777, true)) {
                file_put_contents("{$dir_name}/{$id}.zip",$data);
                exec("unzip {$dir_name}/{$id}.zip -d {$dir_name}");
                if($type!="1"){
                    exec("ebook-convert '{$dir_name}/{$id}.fb2' '{$dir_name}/{$id}.{$types[$type]}'");
                }
                $this->api->execute("deleteMessage",[
                    "message_id" => $res->result->message_id
                ]);
                $this->api->execute("sendDocument",[
                    "document" => new CURLFile("{$dir_name}/{$id}.{$types[$type]}"),
                    "caption" => "Подключайтесь к нашему резервному боту - 📚 [@Knigavsluh_bot](http://t.me/Knigavsluh_bot?start=Reder)"
                ]);
                if(strpos($dir_name,'tmp_files')!==false){
                    exec("rm -r '$dir_name'");
                }
            }
        }else{
            $url = "http://flibusta.site/b/{$id}/download";
            $res = $this->api->execute("sendMessage",[
                "text" => "Пожалуйста, подождите, мы подготавливаем книгу."
            ]);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
            curl_setopt($ch, CURLOPT_URL, $url);
            $data = curl_exec($ch);
            curl_close($ch);
            $dir_name = "/var/www/html/booksbot/storage/tmp_files/".$this->generateRandomString();
            if(mkdir($dir_name, 0777, true)) {
                file_put_contents("{$dir_name}/{$id}.pdf",$data);

                exec("ebook-convert '{$dir_name}/{$id}.pdf' '{$dir_name}/{$id}.{$types[$type]}'");


                $this->api->execute("deleteMessage",[
                    "message_id" => $res->result->message_id
                ]);
                $this->api->execute("sendDocument",[
                    "document" => new CURLFile("{$dir_name}/{$id}.{$types[$type]}")
                ]);
                if(strpos($dir_name,'tmp_files')!==false){
                    exec("rm -r '$dir_name'");
                }
            }
        }
        $ads = ads::where('count','>',0)->get();

        foreach ($ads as $ad){
            $check = subscriptions::where('chat_id',$this->user->chat_id)->where('ad_id',$ad->id)->first();
            if(!$check){
                $subscription = new subscriptions();
                $subscription->chat_id = $this->user->chat_id;
                $subscription->ad_id = $ad->id;
                $subscription->save();
                $ad->count-=1;
                $ad->save();
                return $this->api->execute("sendMessage",[
                    "text" => $ad->text
                ]);
            }
        }

    }

    public function book($data){


        $res = $this->api->execute("getChatMember",[
            'chat_id'=>"-1001265138340",
            'user_id'=>$this->user->chat_id
        ]);

        if($res->ok == true and ($res->result->status == "member" or $res->result->status == "administrator" or $res->result->status == "creator" or $res->result->status == "restricted" or $res->result->status == "kicked")) {

        }else{
            return $this->api->execute("sendMessage",[
                "text" => "🎓 *Лучший образовательный канал с бесплатными курсами* [Study BOARD](https://t.me/joinchat/AAAAAEtoeqQQKANVj9pnhA)\n\n👆 Подпишитесь на канал, чтобы продолжить использование бота. После подписки повторите выбор книги."
            ]);
        }

        $identifier = $data->data[1];

        $res = file_get_contents("http://flibusta.site/b/{$identifier}");

        $image = $this->api->getElementValue($res,'Добавлена','Аннотация');
        $image = $this->api->getElementValue($image,'<img src="','" alt="');

        if(empty($image)){
            $image = false;
        }else{
            $image = "http://flibusta.site{$image}";
        }

        $description = $this->api->getElementValue($res,'<h2>Аннотация</h2>','<hr/>');
        $description = strip_tags($description);
        $description = trim($description);
        $description = str_replace("  "," ",$description);
        $book = flibusta::where('flibusta_id',$identifier)->first();

        $comments = $this->api->getElementValue($res,'</form>','Оценки');

        $rate = trim($this->api->getElementValue($res,'среднее','</p>'));
        if(empty($rate)){
            $rate = "❔";
        }

        $comments_arr = [];
        $comments = explode('<span class="container_',$comments);
        $count_comments = count($comments);



        if($count_comments>0){
            /*
            foreach ($comments as $comment) {
                $comment = $this->api->getElementValue($comment,'</a>','<hr>');
                $comment = $this->api->getElementValue($comment,'<br>','</div>');
                $comments_arr[] = strip_tags($comment);
            }
            $comments_cache = new comments_cache();
            $comments_cache->flibusta_id = $identifier;
            $comments_cache->comments = json_encode($comments_arr,JSON_UNESCAPED_UNICODE);
            $comments_cache->time = time();
            $comments_cache->save();
            */
        }


        $text = "*Название: {$book->title}*\n*Автор: {$book->first_name} {$book->middle_name} {$book->last_name}*\n*Оценка:* {$rate}\n*Описание:*\n\n{$description}";

        if(mb_strlen($text)>1020){
            $text = mb_substr($text,0,1020)."...";
        }


        $buttons = [];

        if(strpos($res,'(скачать pdf)')!==false){
            $buttons[] = [
                ['text' => "▽ fb2","callback_data" => "main:getBook:{$identifier}:1:1"],
                ['text' => "▽ epub","callback_data" => "main:getBook:{$identifier}:2:1"],
                ['text' => "▽ mobi","callback_data" => "main:getBook:{$identifier}:3:1"]
            ];
        }else{
            $buttons[] = [
                ['text' => "▽ fb2","callback_data" => "main:getBook:{$identifier}:1:0"],
                ['text' => "▽ epub","callback_data" => "main:getBook:{$identifier}:2:0"],
                ['text' => "▽ mobi","callback_data" => "main:getBook:{$identifier}:3:0"]
            ];
        }



        $buttons[] = [['text' => "❮ Назад","callback_data" => "search:bookList:{$data->data[0]}:0"]];


        if(!$image){
            $this->api->execute("editMessageCaption", [
                "caption" => $text,
                "message_id" => $data->message_id,
                "inline_keyboard" => $buttons
            ]);
        }else{
            if(empty($book->image)){
                file_put_contents("/var/www/html/booksbot/storage/tmp_files/{$identifier}.jpg",file_get_contents($image));

                if(file_exists("/var/www/html/booksbot/storage/tmp_files/{$identifier}.jpg")){
                    try{


                        $res = $this->api->execute("sendPhoto", [
                            "photo" => new CURLFile("/var/www/html/booksbot/storage/tmp_files/{$identifier}.jpg"),
                            "chat_id" => "-362935649"
                        ]);

                        unlink("/var/www/html/booksbot/storage/tmp_files/{$identifier}.jpg");
                        $file_id = $res->result->photo[count($res->result->photo)-1]->file_id;
                        if(isset($file_id)){
                            $book->image = $file_id;
                            $book->save();
                        }
                    }catch (\Exception $e){
                        $image = false;
                    }
                }
            }

            if($image == false or empty($book->image)){
                $this->api->execute("editMessageCaption", [
                    "caption" => $text,
                    "message_id" => $data->message_id,
                    "inline_keyboard" => $buttons
                ]);
            }else{
                $res = $this->api->execute("editMessageMedia", [
                    "media" => json_encode([
                        "type" => "photo",
                        "parse_mode" => "markdown",
                        "caption" => $text,
                        "media" => $book->image
                    ]),
                    "message_id" => $data->message_id,
                    "inline_keyboard" => $buttons
                ]);
            }

            file_put_contents("/var/www/html/booksbot/storage/tmp_files/poster.jpg",file_get_contents($image));
        }
    }

    public function aBook($data){
        $search_id = $data->data[0];
        $num = $data->data[1];

        $books_list = audio_search_cache::where('id',$search_id)->first();
        $books_list = json_decode($books_list->books);

        $l=1;
        foreach ($books_list as $key => $item){
            if($l == $num){

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
                    "referer: https://knigavuhe.org/",
                    'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,nl;q=0.6,pl;q=0.5',
                    'authority: knigavuhe.org',
                ]);
                curl_setopt($ch, CURLOPT_URL, $item->link);
                $result = curl_exec($ch);
                curl_close($ch);

                $image = $this->api->getElementValue($this->api->getElementValue($result,'<div class="book_cover">','</div>'),'<img src="','"');

                $description = $this->api->getElementValue($result,'<div class="book_description" itemprop="description">','</div>');
                $description = trim(strip_tags($description));


                $text = "*Название: {$item->title}*\n*Автор: {$item->author}*\n*Описание:*\n\n{$description}";

                if(mb_strlen($text)>1020){
                    $text = mb_substr($text,0,1020)."...";
                }

                $buttons = [];

                $buttons[] = [['text' => "❮ Назад","callback_data" => "search:aBookList:{$data->data[0]}:0"],['text' => "▽ Слушать","callback_data" => "main:getABook:{$search_id}:{$num}"]];


                if(!$image){
                    $this->api->execute("editMessageCaption", [
                        "caption" => $text,
                        "message_id" => $data->message_id,
                        "inline_keyboard" => $buttons
                    ]);
                }else{

                    file_put_contents("/var/www/html/booksbot/storage/tmp_files/{$search_id}{$num}.jpg",file_get_contents($image));



                    $res = $this->api->execute("sendPhoto", [
                        "photo" => new CURLFile("/var/www/html/booksbot/storage/tmp_files/{$search_id}{$num}.jpg"),
                        "chat_id" => "-362935649"
                    ]);
                    $file_id = $res->result->photo[count($res->result->photo)-1]->file_id;

                    unlink("/var/www/html/booksbot/storage/tmp_files/{$search_id}{$num}.jpg");

                    $res = $this->api->execute("editMessageMedia", [
                        "media" => json_encode([
                            "type" => "photo",
                            "parse_mode" => "markdown",
                            "caption" => $text,
                            "media" => $file_id
                        ]),
                        "message_id" => $data->message_id,
                        "inline_keyboard" => $buttons
                    ]);

                }
            }
            $l++;
        }
    }

    public function getABook($data){
        $search_id = $data->data[0];
        $num = $data->data[1];

        $books_list = audio_search_cache::where('id',$search_id)->first();
        $books_list = json_decode($books_list->books);

        $l=1;
        foreach ($books_list as $key => $item){
            if($l == $num) {
                $link = $item->link;
                $book_data = $item;
                $message_id = $this->api->execute("sendMessage", [
                    "text" => "Подключение к архиву.."
                ])->result->message_id;


                /*
                return $this->api->execute("sendMessage",[
                    "text" => "В данный момент раздел аудиокниг находится в доработке."
                ])->result->message_id;
                */

                sleep(1);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
                ));
                curl_setopt($ch, CURLOPT_URL, $link);
                $result = curl_exec($ch);
                curl_close($ch);


                $json = $this->api->getElementValue($result, '*/
  var player = new BookPlayer(', ');');

                $json = $this->api->getElementValue($json, ', ', ', [{"label"');

                $identifier = $this->user->chat_id.rand(0,99999999).time();
                $identifier = md5($identifier);

                $audio_playlist = new audio_playlists();
                $audio_playlist->playlist = json_encode(json_decode($json),JSON_UNESCAPED_UNICODE);
                $audio_playlist->time = time();
                $audio_playlist->identifier = $identifier;
                $audio_playlist->title = $item->title;
                $audio_playlist->save();


                $this->api->execute("sendMessage", [
                    "text" => "Слушайте эту книгу в нашем плеере:",
                    "inline_keyboard" => [
                        [["text" => "Слушать", "url" => "https://reader-robot.space/play/{$identifier}"]]
                    ]
                ]);

                /*
                        $dir_name = "/var/www/html/booksbot/storage/audio_books/".$this->generateRandomString();
                        if(mkdir($dir_name, 0777, true)) {

                            $this->api->execute("editMessageText",[
                                "message_id" => $message_id,
                                "text" => "Подготовка файлов.."
                            ]);
                            $count = count($audio_list);

                            $i=0;
                            $progress_txt = "";
                            $prev_percent = 0;
                            foreach ($audio_list as $item) {
                                file_put_contents("{$dir_name}/{$item->id}.mp3",file_get_contents($item->url));
                                $filesize = filesize("{$dir_name}/{$item->id}.mp3");
                                if($filesize>41943040){
                                    echo "\n\n{$dir_name}/{$item->id}.mp3\n\n";
                                    exec("ffmpeg -i {$dir_name}/{$item->id}.mp3 -f segment -segment_time 900 -c copy {$dir_name}/{$item->id}%03d.mp3");
                                    unlink("{$dir_name}/{$item->id}.mp3");
                                }

                                $i ++;
                                $progress_txt .= "█";
                                $percent = round(100/$count*$i);
                                if($percent-$prev_percent>20){
                                    $prev_percent = $percent;
                                    $this->api->execute("editMessageText",[
                                        "message_id" => $message_id,
                                        "text" => "Подготовка файлов..\n\n`{$progress_txt} {$percent}%`"
                                    ]);
                                }

                            }
                        }

                        $files = array_slice(scandir($dir_name),2);

                        $this->api->execute("deleteMessage",[
                            "message_id" => $message_id,
                        ]);

                        $a = 0;
                        $channel_ids = [
                            1 => "-1001439188834",
                            2 => "-1001382594692",
                            3 => "-1001269668780",
                            4 => "-1001401531832",
                            5 => "-1001285126021",
                            6 => "-1001228893337",
                            7 => "-1001150107468",
                            8 => "-1001303025877",
                            9 => "-1001354482747",
                            10 => "-1001476037688",
                        ];

                        foreach ($files as $file) {
                            $a++;
                            rename("{$dir_name}/{$file}", "{$dir_name}/{$a}.mp3");


                            $res = $this->api->execute("sendAudio",[
                                "audio" => new \CURLFile("{$dir_name}/{$a}.mp3"),
                                "chat_id" => $channel_ids[rand(1,10)]
                            ]);

                            $audio_file_id = $res->result->audio->file_id;

                            $res = $this->api->execute("sendAudio",[
                                "audio" => $audio_file_id
                            ]);
                        }
                        if(strpos($dir_name,'audio_books')!==false){
                            exec("rm -r '$dir_name'");
                        }
                    }else{
                        echo $num;
                    }



                */
            }
            $l++;
        }
    }

    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }


    private function resize_image($source, $out, $width, $height){
        $size    = getimagesize($source);
        $format  = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1));
        $icfunc  = "imagecreatefrom" . $format;

        $rgb     = 0x000000;
        $x_ratio     = $width / $size[0];
        $y_ratio     = $height / $size[1];
        $ratio       = max($x_ratio, $y_ratio);
        $use_x_ratio = ($x_ratio == $ratio);
        $new_width   = $use_x_ratio ? $width : floor($size[0] * $ratio);
        $new_height  = !$use_x_ratio ? $height : floor($size[1] * $ratio);
        $new_left    = $use_x_ratio ? 0 : floor(($width - $new_width) / 2);
        $new_top     = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);
        $img     = imagecreatefromjpeg("/var/www/html/booksbot/storage/tmp_files/posterbg.jpg");
        imagefill($img, 0, 0, $rgb);
        $photo   = $icfunc($source);
        imagecopyresampled($img, $photo, 291, $new_top, 0, 0, $new_width,$new_height, $size[0], $size[1]);
        imagepng($img, $out);
    }

    private function resize_image_png($source, $out, $width, $height){
        $size    = getimagesize($source);
        $icfunc  = "imagecreatefrompng";

        $rgb     = 0x000000;
        $x_ratio     = $width / $size[0];
        $y_ratio     = $height / $size[1];
        $ratio       = max($x_ratio, $y_ratio);
        $use_x_ratio = ($x_ratio == $ratio);
        $new_width   = $use_x_ratio ? $width : floor($size[0] * $ratio);
        $new_height  = !$use_x_ratio ? $height : floor($size[1] * $ratio);
        $new_left    = $use_x_ratio ? 0 : floor(($width - $new_width) / 2);
        $new_top     = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);
        $img     = imagecreatefromjpeg("/var/www/html/booksbot/storage/tmp_files/posterbg.jpg");
        imagefill($img, 0, 0, $rgb);
        $photo   = $icfunc($source);
        imagecopyresampled($img, $photo, 291, $new_top, 0, 0, $new_width,$new_height, $size[0], $size[1]);
        imagepng($img, $out);
    }


}
