<?php

namespace App\Listeners\Tickets;

use App\Events\tickets\Created;
use App\Events\tickets\UserReplied;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;
use Mockery\Exception;
use Plugins\Sms\Contracts\SmsDriverInterface;
use Plugins\Sms\Exceptions\SmsDriverNotFoundException;
use Plugins\Sms\Exceptions\SmsDriverNotSupportPatternException;

class InformDepartment implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * inform department staffs using their emails
     * cause sending emails and sms takes much time and resources
     * it's preferred to send emails as bcc and send sms as an array
     * instead of sending emails and sms individually to every user.
     * @param $departmentStaffs
     * @param $ticket
     * @return bool|MailMessage
     */
    public function sendTicketCreatedEmailToDepartment($departmentStaffs, $ticket)
    {
        if (config('email_notifications')) {
            $emails = $departmentStaffs->pluck('email')->toArray();
            return Mail::to(config('site_email'))
                ->bcc($emails)
                ->send(new \App\Mail\tickets\Created($ticket));
        }
        return false;
    }

    /**
     * inform department staffs using their mobile
     * cause sending emails and sms takes much time and resources
     * it's preferred to send emails as bcc and send sms as an array
     * instead of sending emails and sms individually to every user.
     * @param $departmentStaffs
     * @param $ticket
     * @return void
     * @throws \Exception
     */
    public function sendTicketCreatedSmsToDepartment($departmentStaffs, $ticket)
    {
        $to = $departmentStaffs->pluck('mobile')->toArray();
        $text = 'تیکت جدیدی با موضوع' . $ticket->subject . ' دریافت شد ';
        $smsSettings = json_decode(getConfig("sms_settings"), true);
        $activeDriver = $smsSettings["active_driver"];
        $driverSettings = $smsSettings['drivers'][$activeDriver];
        $driver = config('sms.map.'.$activeDriver);
        /** @var SmsDriverInterface $driverInstance */
        $driverInstance = new $driver();
        $shouldSendByPatterns = $driverInstance->shouldSendByPattern($driverSettings);

        if ($shouldSendByPatterns) {
            foreach ($to as $receiver) {
                $res = sms()
                    ->via($activeDriver)
                    ->pattern('ticketCreate')
                    ->data([
                        'ticketSubject' => $ticket->subject,
                        'ticketId' => $ticket->id,
                    ])
                    ->to([$receiver])
                    ->send();
            }
        } else {
            sms()->via($activeDriver)->to($to)->text($text)->send();
        }
    }

    /**
     * inform department staffs using their emails
     * cause sending emails and sms takes much time and resources
     * it's preferred to send emails as bcc and send sms as an array
     * instead of sending emails and sms individually to every user.
     * @param $departmentStaffs
     * @param $event
     * @return bool|MailMessage
     */
    public function sendTicketRepliedEmailToDepartment($departmentStaffs, $event)
    {
        if (config('email_notifications')) {
            $emails = $departmentStaffs->pluck('email')->toArray();
            return Mail::to(config('site_email'))
                ->bcc($emails)
                ->send(new \App\Mail\tickets\UserReplied($event->ticket, $event->reply));
        }
        return false;
    }

    /**
     * inform department staffs using their mobile
     * cause sending emails and sms takes much time and resources
     * it's preferred to send emails as bcc and send sms as an array
     * instead of sending emails and sms individually to every user.
     * @param $departmentStaffs
     * @param $event
     * @return void
     * @throws SmsDriverNotFoundException
     * @throws SmsDriverNotSupportPatternException
     */
    public function sendTicketRepliedSmsToDepartment($departmentStaffs, $event)
    {
        $to = $departmentStaffs->pluck('mobile')->toArray();
        $text = 'تیکت موضوع ' . $event->ticket->subject . ' پاسخ جدیدی دریافت کرد ';
        $smsSettings = json_decode(getConfig("sms_settings"), true);
        $activeDriver = $smsSettings["active_driver"];
        $driverSettings = $smsSettings['drivers'][$activeDriver];
        $driver = config('sms.map.'.$activeDriver);
        /** @var SmsDriverInterface $driverInstance */
        $driverInstance = new $driver();
        $shouldSendByPatterns = $driverInstance->shouldSendByPattern($driverSettings);

        if ($shouldSendByPatterns) {
            foreach ($to as $receiver) {
                sms()
                    ->via($activeDriver)
                    ->pattern('userReply')
                    ->data([
                        'ticketSubject' => $event->ticket->subject,
                        'ticketId' => $event->ticket->id,
                    ])
                    ->to([$receiver])
                    ->send();
            }
        } else {
            sms()->via($activeDriver)->to($to)->text($text)->send();
        }
    }

    /**
     * Handle the event.
     *
     * @return void
     * @throws \Exception
     */
    public function handle($event)
    {
        $departmentStaffs = $event->ticket->department->users()->get();
        if ($event instanceof UserReplied) {
            if (config('email_notifications')) {
                $this->sendTicketRepliedEmailToDepartment($departmentStaffs, $event);
            }
            if (config('sms_notifications')) {
                $this->sendTicketRepliedSmsToDepartment($departmentStaffs, $event);
            }
            foreach ($departmentStaffs as $departmentStaff) {
                $departmentStaff->notify(new \App\Notifications\Tickets\UserReplied($event->ticket, $event->reply));
            }
        } elseif ($event instanceof Created) {
            if (config('email_notifications')) {
                $this->sendTicketCreatedEmailToDepartment($departmentStaffs, $event->ticket);
            }
            if (config('sms_notifications')) {
                $this->sendTicketCreatedSmsToDepartment($departmentStaffs, $event->ticket);
            }
            foreach ($departmentStaffs as $departmentStaff) {
                $departmentStaff->notify(new \App\Notifications\Tickets\Created($event->ticket));
            }
        }
    }
}
