<?php

namespace App\Channels;

use Exception;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Plugins\Sms\Contracts\SmsDriverInterface;

class SmsChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  Notification  $notification
     * @return void
     */

    public function send($notifiable, Notification $notification)
    {
        if (config('sms_notifications') and $notifiable->mobile) {
            try {
                $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) {
                    sms()
                        ->via($activeDriver)
                        ->pattern('staffReply')
                        ->data([
                                'ticketSubject' => $notification->ticket->subject,
                                'ticketId' => $notification->ticket->id,
                            ]
                        )
                        ->to([$notifiable->mobile])
                        ->send();

                } else {
                    $message = $notification->toSms($notifiable);
                    sms()->via($activeDriver)->text($message)->to([$notifiable->mobile])->send();
                }
            } catch (Exception $e) {
                Log::error($e->getMessage(), [
                        'code' => $e->getCode(),
                        'line' => $e->getLine(),
                        'file' => $e->getFile()
                    ]
                );
            }
        }
    }
}
