<?php
namespace laravelLara\lskllc\Commands;

use App\Events\ChatMessageEvent;
use App\Events\LiveNotification;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Customer;
use App\Models\Setting;
use Carbon\Carbon;
use App\Jobs\MailSend;
use App\Models\Ticket\Ticket;
use Mail;
use App\Models\EmailTemplate;
use App\Notifications\TicketCreateNotifications;
use App\Models\Imap_setting;
use App\Models\Ticket\Comment;
use Symfony\Component\Mime\Email;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;

class TicketAutoProcess extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ticket:autoprocess';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $cronset = Setting::where('key','cronjob_set')->first();
        $cronset->value = null;
        $cronset->updated_at = now();
        $cronset->update();

        // notification autodelete
        if(setting('AUTO_NOTIFICATION_DELETE_ENABLE') == 'on'){
            $users = User::get();
            foreach($users as $user){
                foreach($user->notifications as $del){
                    if($del->read_at != null){
                        $read = $del->read_at->adddays(setting('AUTO_NOTIFICATION_DELETE_DAYS'));
                        if($read <= now()->timezone(setting('default_timezone'))){
                            $del->delete();
                        }
                    }
                }
            }
        }

        // autoresponse
        if(setting('AUTO_RESPONSETIME_TICKET') == 'yes'){

            $responsetimes = Ticket::get();

            foreach($responsetimes as $responsetime){
                if($responsetime->auto_replystatus != null){
                    if(Carbon::parse($responsetime->auto_replystatus)->timezone(setting('default_timezone')) < now()->timezone(setting('default_timezone'))){

                        $responsetime->replystatus = 'Waiting for response';
                        $responsetime->auto_replystatus = null;
                        $responsetime->update();

                        $comment = Comment::create([
                            'ticket_id' => $responsetime->id,
                            'user_id' => null,
                            'cust_id' => null,
                            'comment' => 'Waiting for response has been send for this ticket',
                            'commenttype' => 'tickethistory',
                        ]);

                        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$responsetime->id,$responsetime->cust->id,$comment,'tickethistory',User::first()->name));

                        $ticketData = [
                            'ticket_username' => $responsetime->cust->username,
                            'ticket_closingtime' => setting('AUTO_CLOSE_TICKET_TIME'),
                            'ticket_title' => $responsetime->subject,
                            'ticket_id' => $responsetime->ticket_id,
                            'ticket_description' => $responsetime->message,
                            'ticket_status' => $responsetime->status,
                            'replystatus' => $responsetime->replystatus,
                            'ticket_category' => $responsetime->category != null ? $responsetime->category->name : 'Category not available',
                            'item_name' => $responsetime->item_name != null ? $responsetime->item_name : 'Item Name not available',
                        ];

                        try{

                            $replySubject = 'Re: ' . $responsetime->subject;
                            $emailtemplate = EmailTemplate::where('code', 'customer_send_ticket_response')->first();
                            $body = $emailtemplate->body;

                            foreach ($ticketData as $key => $value) {
                                $body = str_replace('{{'.$key.'}}', $value, $body);
                                $body = str_replace('{{ '.$key.' }}', $value, $body);
                            }

                            $email = (new Email())->html($body);

                            $imap_username = setting('IMAP_USERNAME');

                            Mail::raw('', function ($message) use ($email, $responsetime, $imap_username, $replySubject) {
                                $message->from($imap_username)
                                    ->to($responsetime->cust->email)
                                    ->subject($replySubject)
                                    ->getHeaders()->addTextHeader('In-Reply-To', '<' . $responsetime->MessageID . '>');

                                $message->getHeaders()->addTextHeader('References', '<' . $responsetime->MessageID . '>');
                                $message->setBody($email->getBody(), 'text/html');
                            });

                        }catch(\Exception $e){
                            //
                        }
                        $cust = Customer::find($responsetime->cust_id);
                        $cust->notify(new TicketCreateNotifications($responsetime));

                    }
                }

            }
        }

        // trashed ticket delete
        if(setting('trashed_ticket_autodelete') == 'on'){
            $trashedttt = Ticket::onlyTrashed()->get();
            foreach($trashedttt as $trashedtt)
            {
                if ($trashedtt != null) {
                    if(Carbon::parse($trashedtt->deleted_at)->timezone(setting('default_timezone'))->adddays(setting('trashed_ticket_delete_time')) < now()->timezone(setting('default_timezone')))
                    {
                        $trashedtt->forceDelete();
                    }
                }
            }
        }

        // auto close ticket
        if(setting('AUTO_CLOSE_TICKET') == 'yes'){
            $autocloses = Ticket::get();
            foreach($autocloses as $autoclose){
                if($autoclose->auto_close_ticket != null){
                    if(Carbon::parse($autoclose->auto_close_ticket)->timezone(setting('default_timezone')) < now()->timezone(setting('default_timezone')))
                    {
                        if($autoclose->replystatus == 'Solved'){
                            $autoclose->status = 'Closed';
                            $autoclose->closing_ticket = now();
                            $autoclose->auto_close_ticket = null;
                        }else{
                            $autoclose->status = 'Closed';
                            $autoclose->replystatus = 'Unanswered';
                            $autoclose->closing_ticket = now();
                            $autoclose->auto_close_ticket = null;
                        }
                        $autoclose->update();

                        $comment = Comment::create([
                            'ticket_id' => $autoclose->id,
                            'user_id' => null,
                            'cust_id' => null,
                            'comment' => 'This ticket is auto closed',
                            'commenttype' => 'tickethistory',
                        ]);

                        $ticket = $autoclose;
                        $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
                        $comment->ticketinfo = $ticketinfo;

                        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$autoclose->id,$autoclose->cust->id,$comment,'tickethistory',User::first()->name));

                        $ticketData = [
                            'ticket_username' => $autoclose->cust->username,
                            'ticket_id' => $autoclose->ticket_id,
                            'ticket_title' => $autoclose->subject,
                            'ticket_description' => $autoclose->message,
                            'ticket_status' => $autoclose->status,
                            'ticket_category' => $autoclose->category != null ? $autoclose->category->name : 'Category not available',
                            'item_name' => $autoclose->item_name != null ? $autoclose->item_name : 'Item Name not available',
                        ];

                        try{

                            $replySubject = 'Re: ' . $autoclose->subject;
                            $emailtemplate = EmailTemplate::where('code', 'customer_send_ticket_autoclose')->first();
                            $body = $emailtemplate->body;

                            foreach ($ticketData as $key => $value) {
                                $body = str_replace('{{'.$key.'}}', $value, $body);
                                $body = str_replace('{{ '.$key.' }}', $value, $body);
                            }

                            $email = (new Email())->html($body);

                            $imap_username = setting('IMAP_USERNAME');

                            Mail::raw('', function ($message) use ($email, $autoclose, $imap_username, $replySubject) {
                                $message->from($imap_username)
                                    ->to($autoclose->cust->email)
                                    ->subject($replySubject)
                                    ->getHeaders()->addTextHeader('In-Reply-To', '<' . $autoclose->MessageID . '>');

                                $message->getHeaders()->addTextHeader('References', '<' . $autoclose->MessageID . '>');
                                $message->setBody($email->getBody(), 'text/html');
                            });
                        }
                        catch(\Exception $e){
                            //
                        }

                        $cust = Customer::find($autoclose->cust_id);
                        $cust->notify(new TicketCreateNotifications($autoclose));
                    }
                }

            }
        }

        // auto overdue ticket
        if(setting('AUTO_OVERDUE_TICKET') == 'yes'){
            $autooverdues = Ticket::get();

            foreach($autooverdues as $autooverdue){
                if($autooverdue->auto_overdue_ticket != null){
                    if(Carbon::parse($autooverdue->auto_overdue_ticket)->timezone(setting('default_timezone')) < now()->timezone(setting('default_timezone'))){
                        $autooverdue->overduestatus = 'Overdue';
                        $autooverdue->auto_overdue_ticket = null;

                        $autooverdue->update();

                        $comment = Comment::create([
                            'ticket_id' => $autooverdue->id,
                            'user_id' => null,
                            'cust_id' => null,
                            'comment' => 'This ticket has been auto overdue',
                            'commenttype' => 'tickethistory',
                        ]);

                        $ticket = $autooverdue;
                        $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
                        $comment->ticketinfo = $ticketinfo;

                        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$autooverdue->id,$autooverdue->cust->id,$comment,'tickethistory',User::first()->name));

                        $ticketData = [
                            'ticket_title' => $autooverdue->subject,
                            'ticket_username' => $autooverdue->cust->username,
                            'ticket_overduetime' => setting('AUTO_OVERDUE_TICKET_TIME'),
                            'ticket_id' => $autooverdue->ticket_id,
                            'ticket_description' => $autooverdue->message,
                            'ticket_status' => $autooverdue->status,
                            'ticket_admin_url' => fetchticketviewurl($autooverdue),
                            'ticket_category' => $autooverdue->category != null ? $autooverdue->category->name : 'Category not available',
                            'item_name' => $autooverdue->item_name != null ? $autooverdue->item_name : 'Item Name not available',
                        ];

                        try{

                            $assigneuser = User::find($autooverdue->selfassignuser_id);
                            if($assigneuser != null){
                                $assigneuser->notify(new TicketCreateNotifications($autooverdue));
                                $userticketviewurl = fetchticketviaautoviewurl($autooverdue,$assigneuser->id);
                                $ticketData['ticket_admin_url'] = $userticketviewurl;
                                event(new LiveNotification('This ticket status is overdue ' . $autooverdue->ticket_id,$assigneuser,$autooverdue,fetchticketviewurl($autooverdue)));
                                if($assigneuser->usetting->emailnotifyon == 1){
                                    dispatch((new MailSend($assigneuser->email, 'customer_send_ticket_overdue', $ticketData)));
                                }
                            }

                            $users = User::get();
                            foreach($users as $user){
                                if($user->can('All Tickets') && $user->usetting->emailnotifyon == 1 && $user->id != $autooverdue->selfassignuser_id){
                                    $user->notify(new TicketCreateNotifications($autooverdue));
                                    $userticketviewurl = fetchticketviaautoviewurl($autooverdue,$user->id);
                                    $ticketData['ticket_admin_url'] = $userticketviewurl;
                                    event(new LiveNotification('This ticket status is overdue ' . $autooverdue->ticket_id,$user,$autooverdue,fetchticketviewurl($autooverdue)));
                                    dispatch((new MailSend($user->email, 'customer_send_ticket_overdue', $ticketData)));
                                }
                            }


                        }catch(\Exception $e){
                            //
                        }
                    }
                }
            }
        }

        // bot response
        if(setting('botresponseenable') == 'on'){
            $tickets = Ticket::where('status','New')->get();
            foreach($tickets as $ticket){
                $sendbotresponse = false;
                if($ticket->comments->isNotEmpty()){
                    $filteredComments = $ticket->comments->filter(function ($comment) {
                        return $comment->user_id !== null && $comment->commenttype === null;
                    });
                    $sendbotresponse = $filteredComments->isEmpty();
                }else{
                    $sendbotresponse = $ticket->comments->isEmpty();
                }

                if($sendbotresponse == true){
                    $createdtime = Carbon::parse($ticket->created_at);
                    if(setting('time_detection') == 'hours'){
                        $executioncode = $createdtime->addHours(setting('botsresponse_time'))->timezone(setting('default_timezone'));
                    }else{
                        $executioncode = $createdtime->addMinutes(setting('botsresponse_time'))->timezone(setting('default_timezone'));
                    }
                    $holidays = \App\Models\Holiday::whereDate('startdate', '<=', $createdtime->toDateString())->whereDate('enddate', '>=', $createdtime->toDateString())->where('status',1)->get();
                    if($holidays->isNotEmpty()){
                        if($executioncode < now()->timezone(setting('default_timezone'))){
                            $body = setting('response_description');
                            $this->excutionofdatasending($ticket,$body);
                        }
                    }else{
                        foreach(bussinesshour() as $bussiness){
                            if($createdtime->timezone(setting('default_timezone'))->format('D') == $bussiness->weeks){
                                $currentTime = strtotime(now()->timezone(setting('default_timezone'))->format('h:i A'));
                                $startTime = strtotime($bussiness->starttime);
                                $endTime = strtotime($bussiness->endtime);
                                $breakStartTime = strtotime($bussiness->breakstarttime);
                                $breakEndTime = strtotime($bussiness->breakendtime);

                                if (($startTime <= $currentTime && $currentTime <= $endTime && !($breakStartTime <= $currentTime && $currentTime <= $breakEndTime)) || $bussiness->starttime == "24H") {
                                    if($executioncode < now()->timezone(setting('default_timezone'))){
                                        $body = setting('response_description');
                                        $this->excutionofdatasending($ticket,$body);
                                    }
                                } else {
                                    if($executioncode < now()->timezone(setting('default_timezone'))){
                                        $body = setting('response_description_exclude_business_hours');
                                        $this->excutionofdatasending($ticket,$body);
                                    }
                                }

                                // if(strtotime($bussiness->starttime) <= strtotime($createdtime->timezone(setting('default_timezone'))->format('h:i A')) && strtotime($bussiness->endtime) >= strtotime($createdtime->timezone(setting('default_timezone'))->format('h:i A'))|| $bussiness->starttime == "24H"){
                                //     if($executioncode < now()->timezone(setting('default_timezone'))){
                                //         $body = setting('response_description');
                                //         $this->excutionofdatasending($ticket,$body);
                                //     }
                                // }else{
                                //     if($executioncode < now()->timezone(setting('default_timezone'))){
                                //         $body = setting('response_description_exclude_business_hours');
                                //         $this->excutionofdatasending($ticket,$body);
                                //     }
                                // }
                            }

                        }
                    }
                }
            }
        }
    }

    private function excutionofdatasending($ticket,$body)
    {
        $commentData = [
            'ticket_id' => $ticket->ticket_id,
            'ticket_username' => $ticket->cust->username,
            'ticket_title' => $ticket->subject,
            'ticket_description' => $ticket->message,
            'ticket_status' => $ticket->status,
        ];

        foreach ($commentData as $key => $value) {
            $body = str_replace('{{' . $key . '}}', $value, $body);
            $body = str_replace('{{ ' . $key . ' }}', $value, $body);
        }

        $comment = Comment::create([
            'ticket_id' => $ticket->id,
            'user_id' => 741741741,
            'cust_id' => null,
            'comment' => $body,
            'display' => 1,
        ]);

        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$comment,'agentticketreply',$ticket->cust->username));

        $ticket->replystatus = 'Bot-Replied';
        $ticket->auto_close_ticket = null;
        $ticket->auto_replystatus = null;
        $ticket->auto_overdue_ticket = null;
        $ticket->overduestatus = null;
        $ticket->last_reply = now();
        $ticket->update();

        $cust = Customer::find($ticket->cust_id);
        $cust->notify(new TicketCreateNotifications($ticket));

        if ($ticket->tickettype == 'emalitoticket') {
            $imap_username = setting('IMAP_USERNAME');
            $replySubject = 'Re: ' . $ticket->subject;

            $email = (new Email())->html($body);

            Mail::raw('', function ($message) use ($email, $ticket, $imap_username, $replySubject) {
                $message->from($imap_username)
                    ->to($ticket->cust->email)
                    ->subject($replySubject)
                    ->getHeaders()->addTextHeader('In-Reply-To', '<' . $ticket->MessageID . '>');

                $message->getHeaders()->addTextHeader('References', '<' . $ticket->MessageID . '>');
                $message->setBody($email->getBody(), 'text/html');
            });
        }else{
            $validator = new EmailValidator();
            if($validator->isValid($ticket->cust->email, new RFCValidation()) == true){
                Mail::send('admin.email.template', ['emailBody' => $body], function ($message) use ($ticket) {
                    $message->to($ticket->cust->email)->subject('Bot Response to Your ticket.');
                });
            }
        }
    }
}