<?php

namespace App\Http\Controllers;

use App\Models\Chapter;
use App\Models\Fa_aye;
use App\Models\Khatm;
use App\Models\Khatm_pack;
use App\Models\Quran;
use App\Models\Send_everyday;
use App\Models\User;
use App\Models\User_khatm;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function index()
    {
        $send_everyday = Send_everyday::where('status' , 'on')->get();
       // dd($send_everyday);
        //->get();
        if(count($send_everyday) > 0){
            foreach ($send_everyday as $item){
                $user = User::where('id' , $item->user_id)->first();
                $user_khatm = User_khatm::where('user_id' , $user->id)->where('status' , 'reading')->latest()->first();

                if($user){
                    if(!$user_khatm){
                        $this->khatm_packagesSwich($item->number_vars, $user);
                    }
                }
            }
        }
    }

   /* private function save_user_khatm($rows , User $user , $khatm_pack){
        $start_chapter = Chapter::whereId($rows[0]->Chapter)->first();
        if(empty($start_chapter)){
            return false;
        }
        $end_chapter = Chapter::whereId($rows[count($rows)-1]->Chapter)->first();
        if(empty($end_chapter)){
            return false;
        }
        if(isset($khatm_id)){
            $user_khatm = User_khatm::create([
                'user_id'               => $user->id,
                'khatm_id'              => $khatm_id,
                'khatm_pack_id'         => $khatm_pack->id,
                'start_quran_id'        => $rows[0]->id,
                'start_quran_chapter'   => $start_chapter->Name,
                'start_quran_verse'     => $rows[0]->Verse,
                'end_quran_id'          => $rows[count($rows)-1]->id,
                'end_quran_chapter'     => $end_chapter->Name,
                'end_quran_Verse'       => $rows[count($rows)-1]->Verse,
                'number_verses'         => $khatm_pack->value,
            ]);
            return $user_khatm;
        }else{
            $khatm = Khatm::first();
            $user_khatm = User_khatm::create([
                'user_id'               => $user->id,
                'khatm_id'              => $khatm->id,
                'khatm_pack_id'         => $khatm_pack->id,
                'start_quran_id'        => $rows[0]->id,
                'start_quran_chapter'   => $start_chapter->Name,
                'start_quran_verse'     =>  $rows[0]->Verse,
                'end_quran_id'          => $rows[count($rows)-1]->id,
                'end_quran_chapter'     => $end_chapter->Name,
                'end_quran_Verse'       => $rows[count($rows)-1]->Verse,
                'number_verses'         => $khatm_pack->value,
            ]);
            return $user_khatm;
        }
    }

    private function startNewKhatm($chat_id , $user){

        $send_every_day = Send_everyday::where('user_id' , $user->id)->where('status' , 'on')->first();

        $this->array[0] = array(
            array("text" => 'شروع قرائت جدید'),
            array("text" => 'مشاهده ختم های پیشین'),
        );
        if($send_every_day){
            $this->array[1] = array(
                array("text" => 'لغو ارسال خودکار'),
            );
        }else{
            $this->array[1] = array(
                array("text" => 'هر روز به من ارسال کن'),
            );
        }


        $keyboard = array(
            "keyboard" => $this->array,
            "one_time_keyboard" => true, // Can be FALSE (hide keyboard after click)
            "resize_keyboard" => true // Can be FALSE (vertical resize)
        );
        $bot_key = config('TelegramSettings.bot_api');

        $decode = json_encode($keyboard);
        Http::get('https://tapi.bale.ai/bot' . $bot_key . '/sendMessage', [
            'chat_id' => $chat_id,
            'text' => 'گزینه مورد نظر را انتخاب نمایید',
            'reply_markup' => $decode
        ]);
    }

    private function khatm_user_info($user_khatm_info){
        $info = '';
        $info .= 'قرائت قرآن برای شما ثبت شد . ';
        $info .= ' لطفا از آیه ی ';
        $info .= $user_khatm_info->start_quran_verse;
        $info .= ' سوره ی  ';
        $info .= $user_khatm_info->start_quran_chapter;
        $info .= 'قرائت را شروع کنید و تا   ';
        $info .= ' آیه ی ';
        $info .= $user_khatm_info->end_quran_Verse;
        $info .= ' سوره ی  ';
        $info .= $user_khatm_info->end_quran_chapter;
        $info .= ' ادامه دهید .';
        $info .= '

';
        $info .= 'زمان تخمینی قرائت حداقل ';
        $takhmin = (int)(($user_khatm_info->number_verses * 6) / 60) ;
        $info .= $takhmin > 0 ? $takhmin : 1;
        $info .= 'دقیقه محاسبه شده است . لطفا پس از اتمام قرائت بر روی دکمه تمام کردم کلیک نمایید. ';
        return $info;
    }

    private function connect_ayats_together($rows , $chat_id){
        $ayyet = '';
        foreach ($rows as $key => $row){
            $row_str = '';
            if($row->Verse == 1 && $key != 0){
                $ayyet .= config('TelegramSettings.bot_username');
                $this->send_message($chat_id , $ayyet , 'HTML');
                sleep(1);
                $ayyet = '';
            }
            $row_str .= '<b>'.$row->Arabic.'('.$row->Verse.')'.'</b>

';
            $fa_aye = Fa_aye::where('ID',$row->id)->first();
            $row_str .= '<i>*' .$fa_aye->tr.'*

</i>';
            if(mb_strlen($ayyet) + mb_strlen($row_str) + mb_strlen(config('TelegramSettings.bot_username'))  > 4090){
                $ayyet .= config('TelegramSettings.bot_username');
                $this->send_message($chat_id , $ayyet , 'HTML');
                $ayyet = '';
            }
            $ayyet .= $row_str;
        }
        $ayyet .= config('TelegramSettings.bot_username');
        $this->send_message($chat_id , $ayyet , 'HTML');
        sleep(1);
        return true;
    }

    public function sendKhatmButtons($response){
        Cache::set('khatm_strted' . $response->message->chat->id,'true');
        $user = User::where('chat_id' , $response->message->chat->id)->first();
        if($user){
            $send_every_day = Send_everyday::where('user_id' , $user->id)->where('status' , 'on')->first();
            if(is_array(config('TelegramSettings.admin_usernames'))
                && in_array($response->message->from->username ?? 'default' , config('TelegramSettings.admin_usernames'))){
                $this->array[0] = array(
                    array("text" => 'قرائت را تمام کردم'),
                    array("text" => 'انصراف از ختم'),
                );
                if($send_every_day){
                    $this->array[1] = array(
                        array("text" => 'لغو ارسال خودکار'),
                    );
                }else{
                    $this->array[1] = array(
                        array("text" => 'هر روز به من ارسال کن'),
                    );
                }

                $this->array[2] = array(
                    array("text" => 'بازگشت به پنل ادمین'),
                );


            }else{
                $this->array[0] = array(
                    array("text" => 'قرائت را تمام کردم'),
                    array("text" => 'انصراف از ختم'),
                );

                if($send_every_day){
                    $this->array[1] = array(
                        array("text" => 'لغو ارسال خودکار'),
                    );
                }else{
                    $this->array[1] = array(
                        array("text" => 'هر روز به من ارسال کن'),
                    );
                }
            }


            $keyboard = array(
                "keyboard" => $this->array,
                "one_time_keyboard" => false, // Can be FALSE (hide keyboard after click)
                "resize_keyboard" => true // Can be FALSE (vertical resize)
            );

            $decode = json_encode($keyboard);
            Http::get('https://tapi.bale.ai/bot' . $this->bot_key . '/sendMessage', [
                'chat_id' => $response->message->chat->id,
                'text' => 'لطفا بعد از قرائت آیات دکمه اتمام قرائت را بزنید',
                'reply_markup' => $decode
            ]);
        }

    }

    private function manage_sending_khatm($rows , $user , $khatm_pack , $chat_id){
        $user_khatm = $this->save_user_khatm($rows , $user , $khatm_pack);

        if(!$user_khatm){
            $this->send_message($user->chat_id , 'قرائت شما ثبت نشد از اول امتحان کنید  ');
            $this->startNewKhatm($chat_id , $user);
        }else{
            $khatm_info = $this->khatm_user_info($user_khatm);
            $this->send_message($chat_id , $khatm_info);
            sleep(5);
            $sended = $this->connect_ayats_together($rows , $chat_id);
            if($sended){
                $this->sendKhatmButtons($chat_id);
            }else{
                $this->send_message($chat_id , 'اگر متن آیه ها را دریافت نکردید . لطفا از روی قرآن دیگر قرائت کنید سپس روی دکمه قرائت را تمام کردم کلیک نمایید' );
                $this->sendKhatmButtons($chat_id);
            }
        }
    }

    private function send_message($chat_id , $message , $parse_mode = null){
        $bot_key = config('TelegramSettings.bot_api');
        if($parse_mode != null){
            Http::get('https://tapi.bale.ai/bot' . $bot_key . '/sendMessage', [
                'chat_id' => $chat_id,
                'text' => $message,
                'parse_mode'    => $parse_mode
            ]);
        }else{
            Http::get('https://tapi.bale.ai/bot' . $bot_key . '/sendMessage', [
                'chat_id' => $chat_id,
                'text' => $message,
            ]);
        }

    }*/
}
