<?php

namespace App\Console;

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 Carbon\Carbon;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        try{
            //send first alert to read and confirm khatm
            $schedule->call(function (){
                try{
                    $user_khatms = User_khatm::whereStatus('reading')
                        ->where('alert' , 0)
                        ->where('created_at','<', Carbon::now()->subHours(12))->get();
                    //->get();

                    if(count($user_khatms) > 0){
                        $bot_key = config('TelegramSettings.bot_api');
                        foreach ($user_khatms as $khatm){
                            $user = User::whereId($khatm->user_id)->first();
                            if(!$user){
                                Log::alert('user not found');
                                continue;
                            }
                            $send_every_day = Send_everyday::where('user_id' , $user->id)->where('status' , 'on')->first();

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

                            $keyboard = array(
                                "keyboard" => $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' . $bot_key . '/sendMessage', [
                                'chat_id' => $user->chat_id,
                                'text' => 'همراه و عضو محترم
                        لطفا در کنار کار روزانه آیات الهی را نیز بخوانید',
                                'reply_markup' => $decode
                            ]);

                            $khatm->alert = 1;
                            $khatm->save();
                        }
                    }
                }catch (\Exception $exception){
                    Log::error($exception->getMessage());
                }

            })->everyFiveMinutes();
            // send latest alert
            $schedule->call(function (){
                try{
                    $user_khatms = User_khatm::whereStatus('reading')
                        ->where('alert' , 1)
                        ->where('created_at','<', Carbon::now()->subHours(23))->get();
                    //->get();

                    if(count($user_khatms) > 0){
                        $bot_key = config('TelegramSettings.bot_api');
                        foreach ($user_khatms as $khatm){
                            $user = User::whereId($khatm->user_id)->first();
                            if(!$user){
                                Log::alert('user not found');
                                continue;
                            }
                            $send_every_day = Send_everyday::where('user_id' , $user->id)->where('status' , 'on')->first();

                            $array[0] = array(
                                array("text" => 'قرائت را تمام کردم'),
                                array("text" => 'انصراف از ختم'),
                            );
                            if($send_every_day){
                                $array[1] = array(
                                    array("text" => 'لغو ارسال خودکار'),
                                );
                            }else{
                                $array[1] = array(
                                    array("text" => 'هر روز به من ارسال کن'),
                                );
                            }
                            $keyboard = array(
                                "keyboard" => $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' . $bot_key . '/sendMessage', [
                                'chat_id' => $user->chat_id,
                                'text' => 'همراه و عضو محترم
                        لطفا در کنار کار روزانه آیات الهی را نیز بخوانید',
                                'reply_markup' => $decode
                            ]);

                            $khatm->alert = 2;
                            $khatm->save();
                        }
                    }
                }catch (\Exception $exception){
                    Log::error($exception->getMessage());
                }

            })->everyTenMinutes();
            //cancel khatms
            $schedule->call(function (){
                try{
                    $user_khatms = User_khatm::whereStatus('reading')
                        ->whereAlert(2)
                        ->where('created_at','<', Carbon::now()->subHours(24))->get();

                    if(count($user_khatms) > 0){
                        foreach ($user_khatms as $khatm){
                            $khatm->status = 'canceled';
                            $khatm->save();
                        }
                    }
                }catch (\Exception $exception){
                    Log::error($exception->getMessage());
                }

            })->everyFifteenMinutes();
            //send notification to users that want read quran every day
            $schedule->call(function (){
                $send_everyday = Send_everyday::where('status' , 'on')->get();
                //->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);
                            }
                        }
                    }
                }
            })->twiceDaily(9,18);
        }catch (\Exception $exception){
            Log::error($exception);
        }

    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }

    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($chat_id){
        Cache::set('khatm_strted' . $chat_id,'true');
        $user = User::where('chat_id' , $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($user->name ?? '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)
            );
            $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
            ]);
        }

    }

    public function manage_sending_khatm($rows , $user , $khatm_pack , $chat_id , $use_old_khatm = false , $user_khatm = null){
        if(!$use_old_khatm || $user_khatm == null){
            $user_khatm = $this->save_user_khatm($rows , $user , $khatm_pack);
        }
        if(!$user_khatm){
            $this->send_message($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 khatm_packagesSwich($package , User $user ){
        $khatm_packs = Khatm_pack::all();
        if(count($khatm_packs) > 0){
            foreach ($khatm_packs as $khatm_pack){
                if($package == $khatm_pack->name){
                    $count_users_khatm = User_khatm::whereUser_id($user->id)->count();
                    if($count_users_khatm == 0){
                        $rows = Quran::limit($khatm_pack->value)->get();
                        $this->manage_sending_khatm($rows , $user , $khatm_pack , $user->chat_id);
                    }else{
                        //Get the last ending left
                        $old_khatm = User_khatm::whereUser_id($user->id)->latest()->first();
                        $latest_verse = (int)$old_khatm->end_quran_id + 1;
                        if(($latest_verse + (int)$khatm_pack->value) <= 6236){
                            $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->limit($khatm_pack->value)->get();
                        }else{
                            $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->get();
                        }
                        $this->manage_sending_khatm($rows , $user , $khatm_pack , $user->chat_id);
                    }
                    break;
                }
            }
        }
    }*/
    public function khatm_packagesSwich($package , User $user){
        $khatm_packs = Khatm_pack::all();
        $khatm = Khatm::whereStatus('active')->first();
        if ( $khatm === null){
            $khatm = Khatm::first();
            $khatm->status =  'active';
            $khatm->save();
        }

        if(count($khatm_packs) > 0){
            foreach ($khatm_packs as $khatm_pack){

                //تعداد آیه انتخاب شده را چک می کنیم
                if($package == $khatm_pack->name){
                    //delete
                    $this->send_message($user->chat_id , $khatm_pack->name);

                    // تعداد ختم انتخاب شده توسط کاربر در ختم فعال را می یابیم
                    $count_users_khatm = User_khatm::whereKhatm_id($khatm->id)->count();

                    // اگر تا به حال آیاتی از ختم فعال خوانده نشده
                    if($count_users_khatm == 0){
                        $rows = Quran::limit($khatm_pack->value)->get();
                        $this->manage_sending_khatm($rows , $user , $khatm_pack , $user->chat_id );

                        // کاربر آیاتی را از قبل از ختم فعال مطالعه کرده است
                    }else{
                        // چک کردن آیاتی فعال که کاربر هنوز مطالعه آن را تمام نکرده
                        $check_user_active_khatm = User_khatm::whereUser_id($user->id)
                            ->whereStatus('reading')->first();

                        // آیاتی فعال که کاربر هنوز مطالعه آن را تمام نکرده
                        if($check_user_active_khatm !== null){

                            //change
                            $latest_verse = (int)$check_user_active_khatm->end_quran_id + 1;
                            $start_verse = (int)$check_user_active_khatm->start_quran_id;

                            // باید در این قسمت چک کنیم که به آخر قرآن کریم نرسیده باشیم.
                            //به آخر نرسیده ایم
                            if(($latest_verse + (int)$khatm_pack->value) <= 6236){
                                //$rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->limit($khatm_pack->value)->get();
                                $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->limit($khatm_pack->value)->get();

                                // به آخر قرآن رسیده ایم
                            }else{
                                //$rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->get();
                                $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->get();
                            }
                            $this->manage_sending_khatm($rows , $user , $khatm_pack , $user->chat_id);

                            // آیاتی وجود ندارد که کاربر آن را گرفته باشد و مطالعه نکرده باشد
                        }else{

                            // گرفتن آیاتی که وضعیت آنها لغو شده است
                            $old_khatm = User_khatm::whereKhatm_id($khatm->id)->where('status' , 'canceled')
                                ->where('number_verses' , $khatm_pack->value)->first();

                            //$this->send_message($response , $old_khatm->id);
                            $use_old_khatm = true;
                            if(empty($old_khatm)){
                                $old_khatm = User_khatm::whereKhatm_id($khatm->id)->latest('end_quran_id')->first();
                                $use_old_khatm = false;
                            }else{
                                $old_khatm->user_id = $user->id;
                                $old_khatm->status = 'reading';
                                $old_khatm->save();
                            }

                            $latest_verse = (int)$old_khatm->end_quran_id + 1;
                            $start_verse = (int)$old_khatm->start_quran_id;

                            if($use_old_khatm){
                                //به آخر قرآن نرسیده ایم
                                if(($latest_verse + (int)$khatm_pack->value) <= 6236){

                                    $rows = Quran::orderBy('id')->where('id' , '>=',$start_verse)->limit($khatm_pack->value)->get();
                                }else{
                                    $rows = Quran::orderBy('id')->where('id' , '>=',$start_verse)->get();
                                }
                            }else{
                                //به آخر قرآن نرسیده ایم
                                if(($latest_verse + (int)$khatm_pack->value) <= 6236){

                                    $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->limit($khatm_pack->value)->get();
                                }else{
                                    $rows = Quran::orderBy('id')->where('id' , '>=',$latest_verse)->get();
                                }
                            }
                            $this->manage_sending_khatm($rows , $user , $khatm_pack , $user->chat_id);
                        }
                    }
                    break;
                }
            }
        }
    }

    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,
            ]);
        }

    }

}
