<?php

namespace App\Models\Users;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\Users\AccountsModel;
use App\Models\Users\Botmessage;
use App\Models\Users\Botmessageoption;
use App\Models\Users\Botvisitorhistory;
use App\Models\Users\Contacts;
use App\Models\WhatsappBotApi;
use Illuminate\Http\Request;

class Botvisitor extends Model
{
    protected $table = 'bot_visitors';
    use HasFactory;

    public const SESSION_HOUR = 24;

    //get Accounts of a particular company
    public static function saveVisitor($contact_id, $bot_info_id)
    {
        $session =  NOW();
        $submit_data = array(
            'contact_id' => $contact_id,
            'fk_bot_info' => $bot_info_id,
            'session_id' => $session,
            'status' => 1,
            'created_at' => NOW()
        );
        $visitor_id = DB::table('bot_visitors')->insertGetId($submit_data);

        return $visitor_id;
    }
    // check either visitor has with status 1
    public static function checkVisitor($vistor_phone_no, $contact_id, $bot_number)
    {

        // this query will check if a visitor number session is continue or not
        $data = Botvisitor::Select('bot_visitors.id', 'bot_visitors.created_at')
            ->join('contacts', 'bot_visitors.contact_id', '=', 'contacts.id')
            ->where('bot_visitors.status', 1)
            ->where('contacts.phone_number', $vistor_phone_no)
            ->where('contacts.id', $contact_id)
            ->latest('bot_visitors.created_at')
            ->first();

        // number already exist on visitor now calculate it's session time
        // if return false which measn start from benginings

        $accounts_Info = AccountsModel::getAccountsonPoneNumber($bot_number);


        $botInfo =  Botinfo::Select('bot_info.bot_timeout_hr')
            ->join('accounts', 'accounts.id', '=', 'bot_info.account_id')
            ->where('bot_info.account_id', $accounts_Info->id)
            ->first();

        //return $data;
        if ($data != Null) {

            $hour = abs(strtotime(NOW()) - strtotime($data->created_at)) / (60 * 60);

            //if visitor session is old then the defined bot info table horus will be check / otherwise it will update all  and start form begining
            if (floor($hour) > $botInfo->bot_timeout_hr) {
                //r eturn "floor";
                Botvisitor::updateVisitor($contact_id);
                Botvisitorhistory::updateVisitorHistory($data->id);
                return false;
            } else {
                return $data->id;
            }
        } else {
            return false;
        }
    }

    public static function updateVisitor($contact_id)
    {

        // DB::table('bot_visitors')
        //     ->updateOrInsert(
        //         ['bot_visitors.contact_id' => $contact_id],
        //         ['status' => 0, 'updated_at' => date("Y-m-d H:i:s")]
        //     );
        DB::table('bot_visitors')
            ->where('contact_id', $contact_id)
            ->update(['status' => 0]);
    }

    public static function resetBot($visitor_id)
    {
        $bot_visitor = Botvisitor::find($visitor_id);
        $contact = Contacts::find($bot_visitor->contact_id);
        BotmsgFormula::setStatus($visitor_id);
        Botvisitor::updateVisitor($contact->id);
        Botvisitorhistory::updateVisitorHistory($visitor_id);
    }

    public static function process($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo)
    {
        
        if ($msg_data->is_externalaction_before) {

            if ($msg_data->id != 41.1) {
                BotExternalAction::checkactionBefore($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo);
            }
        }

        $data_options_for_sent = Botmessageoption::getMsgoptionbymsgID($msg_data->id);

        $text_to_be_sent = Botmessageoption::formattingMessage($data_options_for_sent, $msg_data->text, $msg_data->type);

        $text_to_be_sent = Botmessage::findVariable($text_to_be_sent, $visitor_id);
        $text_to_be_sent = Botmessage::findFormula($text_to_be_sent, $visitor_id, $text_message, $BotInfo);
        $text_to_be_sent = Botmessage::findAPIResponse($text_to_be_sent, $visitor_id);

        // if input validation fail exit inside





        $whatsapp_obj = new WhatsappBotApi($bot_number);
        if ($msg_data->type == Botmessage::SIMPLE_MESSAGE) {
            //$resp_code = 200;
            $resp_code = $whatsapp_obj->BotSimpleMessage($vistor_phone_no, $text_to_be_sent);
        } else if ($msg_data->type == Botmessage::BUTTONS) {
            $button_options = Botmessageoption::where('msgs_id', $msg_data->id)->get();
            $resp_code =  $whatsapp_obj->BotButtonMessage($vistor_phone_no, $text_to_be_sent, $button_options);
        } else if ($msg_data->type == Botmessage::PRODUCT_MESSAGE) {

            $data_options_for_sent = Botmessageoption::getMsgoptionbymsgID($msg_data->id);
            $resp_code = $whatsapp_obj->BotProdutMessage($vistor_phone_no, $msg_data->text, $data_options_for_sent);
        } else if ($msg_data->type == Botmessage::TEMPLATE_SiMPLE) {

            //$data_options_for_sent = Botmessageoption::getMsgTemplateDetails($msg_data->id);

            $resp_code = $whatsapp_obj->BotTemplateSimple($vistor_phone_no, $msg_data);

            //return $resp_code;
        } else {

            $data_options_for_sent = Botmessageoption::getMsgoptionbymsgID($msg_data->id);
            // add formula values on optoin text
            for ($i = 0; $i < sizeof($data_options_for_sent); $i++) {
                $txt = Botmessage::findFormula($data_options_for_sent[$i]->option_text, $visitor_id, $text_message, $BotInfo);
                //$data_options_for_sent[$i]->valid_answer  = $txt;
                $data_options_for_sent[$i]->option_text  = $txt;
            }


            $resp_code = $whatsapp_obj->BotInteractiveMessage($vistor_phone_no, $text_to_be_sent, $data_options_for_sent);
        }


        if ($resp_code == 200) {
            $re =  Botvisitorhistory::saveVisitorHistory($visitor_id, $msg_data->id, $text_message, $wamid, "", $msg_data->sequence);
            // this is for email whatsappmssage and api calls

            if ($msg_data->is_externalaction) {

                BotExternalAction::externalProcess($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo);
            }
            // this is for reset the bot
            // if ($msg_data->is_lastmsg) {
            //     Botvisitor::resetBot($visitor_id);
            // }

            print_r($re);
            return $re;
        }
    }
}
