<?php

namespace App\TelegramBot\Handlers;

use App\Models\audio_search_cache;
use App\Models\flibusta;
use App\Models\search_cache;
use App\TelegramBot\Api;
use App\TelegramBot\Keyboard\Keyboard;
use App\TelegramBot\Keyboard\BRow;
use PhpParser\Node\Expr\Cast\Object_;

class SearchHandler
{


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

    public function book(){
        $this->user->action =  json_encode(['action'=>"search@searchBook"]);
        $this->user->save();

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

    public function abook(){
        $this->user->action =  json_encode(['action'=>"search@searchABook"]);
        $this->user->save();

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

    public function searchABook($query){

        if($query=="🎵 Поиск аудиокниги"){
            return $this->abook();
        }
        if($query=="📖 Поиск книги"){
            return $this->book();
        }

        $this->user->action = 0;
        $this->user->save();

        $message_id = $this->api->execute("sendVideo",[
            "video" => $this->default_media,
            "caption" => "Начинаем поиск.. Пожалуйста, подождите.."
        ])->result->message_id;


        $query = urlencode($query);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_PROXY, "185.147.128.48:8000");
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, "NYSBYF:bxfHvM");
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
        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, "https://knigavuhe.org/search/?q={$query}&page=1");
        $result = curl_exec($ch);

        curl_close($ch);

        $books = $this->getElementValue($result,'<div id="books_list">','<div class="pn" id="books_list__pn">');
        $items = array_slice(explode('<div class="bookkitem">',$result),1);

        $count_pages = $this->getElementValue($result,'<div class="pn_page_buttons">','</div>');

        if(!empty($count_pages)){
            $pages = explode("a class",$count_pages);
            $count_pages = trim($this->getElementValue($pages[count($pages)-1],'false">','</a>'));
        }else{
            $count_pages = 0;
        }

        echo $count_pages;
        $books_arr = [];

        foreach ($items as $item) {
            if(strpos($item,'bookkitem_litres_icon')===false){


                $books_arr[] = [
                    "title" => trim(strip_tags($this->getElementValue($item,'class="bookkitem_name">','</a>'))),
                    "author" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_author_label">автор</span>','</span>'))),
                    "genre" => trim(strip_tags($this->getElementValue($item,'<div class="bookkitem_genre">','</div>'))),
                    "duration" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_meta_time">','</span>'))),
                    "likes" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_icon -likes"></span> <span class="bookkitem_meta_label -not_last">','</span>'))),
                    "link" => "https://knigavuhe.org".trim(strip_tags($this->getElementValue($item,'<a href="','"'))),
                ];
            }
        }


        if($count_pages>1){
            for($i=2;$i<=$count_pages;$i++){
                if($i>=6){
                    break;
                }

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_PROXY, "185.147.128.48:8000");
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, "NYSBYF:bxfHvM");
                curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
                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, "https://knigavuhe.org/search/?q={$query}&page=1");
                $result = curl_exec($ch);
                curl_close($ch);

                $books = $this->getElementValue($result,'<div id="books_list">','<div class="pn" id="books_list__pn">');
                $items = array_slice(explode('<div class="bookkitem">',$result),1);

                foreach ($items as $item) {
                    if(strpos($item,'bookkitem_litres_icon')===false){
                        $books_arr[] = [
                            "title" => trim(strip_tags($this->getElementValue($item,'class="bookkitem_name">','</a>'))),
                            "author" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_author_label">автор</span>','</span>'))),
                            "genre" => trim(strip_tags($this->getElementValue($item,'<div class="bookkitem_genre">','</div>'))),
                            "duration" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_meta_time">','</span>'))),
                            "likes" => trim(strip_tags($this->getElementValue($item,'<span class="bookkitem_icon -likes"></span> <span class="bookkitem_meta_label -not_last">','</span>'))),
                            "link" => "https://knigavuhe.org".trim(strip_tags($this->getElementValue($item,'<a href="','"'))),
                        ];
                    }
                }
            }
        }


        $search_cache = new audio_search_cache();
        $search_cache->query = urldecode($query);
        $search_cache->books = json_encode($books_arr,JSON_UNESCAPED_UNICODE);
        $search_cache->time = time();
        $search_cache->save();


        $this->aBookList((Object)[
            'data' => [
                $search_cache->id,
                0
            ],
            'message_id' => $message_id
        ]);
    }

    public function searchBook($query){

        if($query=="🎵 Поиск аудиокниги"){
            return $this->abook();
        }
        if($query=="📖 Поиск книги"){
            return $this->book();
        }



        $this->user->action = 0;
        $this->user->save();
        $query = mb_strtolower($query);
        $message_id = $this->api->execute("sendVideo",[
            "video" => $this->default_media,
            "caption" => "Начинаем поиск.. Пожалуйста, подождите.."
        ])->result->message_id;

        $q = $query;
        $result_arr = [];

        if(strpos($q," ")!==false){
            $q_arr = explode(" ",$q);
        }else{
            $q_arr = [$q];
        }

        $results = flibusta::where('query',"like","%{$q_arr[0]}%")->get();

        foreach ($results as $result) {
            $found = true;
            $result->query = mb_strtolower($result->query);
            foreach ($q_arr as $word) {
                if(strpos($result->query,$word)!==false){
                    $found = true;
                }else{
                    $found = false;
                }
            }

            if($found == true){
                $result_arr[] = $result;
            }
        }

        $exact_math = [];
        $not_exact_math = [];


        $exact_math_count = 0;
        foreach ($result_arr as $item) {
            if(strpos(mb_strtolower($item->title),mb_strtolower($query))!==false){
                $item->title_length = mb_strlen($item->title);
                $exact_math[] = $item;
                $exact_math_count++;
            }else{
                $not_exact_math[] = $item;
            }
        }



        usort($exact_math, function ($a, $b) {
            return $a->title_length - $b->title_length;
        });
        $result_arr = array_merge($exact_math,$not_exact_math);

        $search_cache = new search_cache();
        $search_cache->query = $query;
        $search_cache->books = json_encode($result_arr,JSON_UNESCAPED_UNICODE);
        $search_cache->time = time();
        $search_cache->save();


        $this->bookList((Object)[
           'data' => [
               $search_cache->id,
               0
           ],
            'message_id' => $message_id
        ]);
    }
    public function aBookList($data){
        $search_id = $data->data[0];
        $page = $data->data[1];

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

        $l=1;
        foreach ($books_list as $key => $item){
            $books_list[$key]['num'] = $l;
            $l++;
        }
        $books_list = array_slice($books_list,$page*5,5);

        $prev = $page -1;
        $next = $page +1;
        $button_rows = [];
        $navigate_buttons = [];

        $count_pages = floor($books_count/5);

        $page_str = $page+1;

        if($books_count - $count_pages*5>0){
            $count_pages_str = $count_pages+1;
        }else{
            $count_pages_str = $count_pages;
        }

        $text = "📖 Поиск по запросу: {$query}\n\n";
        $text .= "Страница: {$page_str} из {$count_pages_str}\n\n";

        $i = 0;

        $numbers = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣"];
        $select_buttons = [];

        foreach ($books_list as $book) {
            $text .= "*{$numbers[$i]} {$book['title']} - {$book['author']}*\n`{$book['genre']} • {$book['duration']} 👍 {$book['likes']}`\n\n";
            $select_buttons[] = ["text" => $numbers[$i],"callback_data" => "main:aBook:{$search_id}:{$book['num']}"];
            $i ++;
        }
        $text .= "Подписывайтесь на наши ресурсы:\n🔘 [@workbro_bot](https://t.me/WorkBro_BOT?start=48962) - этот бот мониторит все популярные биржи фриланса и присылает подходящие задания, даже для людей без опыта!\n\n[📚 Книжник - авторский канал с подборками книг](https://t.me/knizhnikc)\n\n📖 @elonglist - агрегатор лучших статей рунета про маркетинг, контент, медиа и бизнес\n\n⚡ [@Study_Board_bot](https://t.me/Study_BOARD_Bot?start=Bookbots) — лучшие бесплатные курсы со всего интернета!";

        if($page>0){
            $navigate_buttons[] = ['text' => "❮ назад","callback_data" => "search:aBookList:{$search_id}:{$prev}"];
        }
        if($page_str < $count_pages_str){
            $navigate_buttons[] = ['text' => "вперёд ❯","callback_data" => "search:aBookList:{$search_id}:{$next}"];
        }

        $button_rows[] = $select_buttons;
        $button_rows[] = $navigate_buttons;

        $this->api->execute("editMessageMedia", [
            "media" => json_encode([
                "type" => "video",
                "parse_mode" => "markdown",
                "caption" => $text,
                "media" => $this->default_media
            ]),
            "message_id" => $data->message_id,
            "inline_keyboard" => $button_rows
        ]);
    }


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

        $books_list = search_cache::where('id',$search_id)->first();
        $query = $books_list->query;
        $books_list = json_decode($books_list->books,true);
        $books_count = count($books_list);

        $books_list = array_slice($books_list,$page*5,5);

        $prev = $page -1;
        $next = $page +1;
        $button_rows = [];
        $navigate_buttons = [];

        $count_pages = floor($books_count/5);

        $page_str = $page+1;

        if($books_count - $count_pages*5>0){
            $count_pages_str = $count_pages+1;
        }else{
            $count_pages_str = $count_pages;
        }

        $text = "📖 Поиск по запросу: {$query}\n\n";
        $text .= "Страница: {$page_str} из {$count_pages_str}\n\n";

        $i = 0;

        $numbers = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣"];
        $select_buttons = [];

        foreach ($books_list as $book) {
            $book['title'] = strip_tags($book['title']);
            $book['title'] = trim(str_replace(["&#039;"],"",$book['title']));
            $book['middle_name'] = trim($book['middle_name']);
            $book['actor'] = trim("{$book['first_name']} {$book['middle_name']} {$book['last_name']}");
            $text .= str_replace("  "," ","{$numbers[$i]} *{$book['title']}* \n`{$book['actor']}`\n\n");
            $select_buttons[] = ["text" => $numbers[$i],"callback_data" => "main:book:{$search_id}:{$book['flibusta_id']}"];
            $i ++;
        }
        $text .= "🔘 [@workbro_bot](https://t.me/WorkBro_BOT?start=48962) - этот бот мониторит все популярные биржи фриланса и присылает подходящие задания, даже для людей без опыта!\n\n📚 [Книжник](https://t.me/knizhnikc)* - наш авторский канал с подборками книг*\n\n📖 @elonglist - агрегатор лучших статей рунета про маркетинг, контент, медиа и бизнес\n\n⚡ [@Study_Board_bot](https://t.me/Study_BOARD_Bot?start=Bookbots) — лучшие бесплатные курсы со всего интернета!";

        if($page>0){
            $navigate_buttons[] = ['text' => "❮ назад","callback_data" => "search:bookList:{$search_id}:{$prev}"];
        }
        if($page_str < $count_pages_str){
            $navigate_buttons[] = ['text' => "вперёд ❯","callback_data" => "search:bookList:{$search_id}:{$next}"];
        }

        $button_rows[] = $select_buttons;
        $button_rows[] = $navigate_buttons;

        $this->api->execute("editMessageMedia", [
            "media" => json_encode([
                "type" => "video",
                "parse_mode" => "markdown",
                "caption" => $text,
                "media" => $this->default_media
            ]),
            "message_id" => $data->message_id,
            "inline_keyboard" => $button_rows
        ]);
    }



    public function getElementValue($string,$strStart,$strEnd){
        $str_search = strpos($string,$strStart);
        if($str_search===false){
            return false;
        }
        $str_1 = substr($string,$str_search+strlen($strStart));
        $str_search = strpos($str_1,$strEnd);
        $res = substr($str_1,0,$str_search);
        return $res;
    }
}
