<?php

namespace App\Listeners\UserRegistered;

use App\Events\UserRegistered;
use Exception;
use Illuminate\Support\Facades\Log;
use Plugins\Sms\Contracts\SmsDriverInterface;

class SendActivationSMS
{

    public function __construct()
    {
    }

    public function handle(UserRegistered $event)
    {
        if (config('must_verify_mobile')) {
            $to = $event->user->mobile;
            $msg = 'کد تایید شما : '.$event->mobileVerificationCode ?: $event->verificationToken;
            $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);
            try {
                if ($shouldSendByPatterns) {
                    sms()->via($activeDriver)
                        ->pattern('userRegister')
                        ->data(['code' => $event->mobileVerificationCode ?: $event->verificationToken])
                        ->to([$to])
                        ->send();
                } else {
                    sms()->via($activeDriver)->text($msg)->to($to)->send();
                }
            } catch (Exception $e) {
                Log::error(
                    $e->getMessage(),
                    [
                        'code' => $e->getCode(),
                        'line' => $e->getLine(),
                        'file' => $e->getFile()
                    ]
                );
            }
        }
    }
}
