<?php

namespace Yajny\EventsYj\Events;

use Yajny\EventsYj\Events\YajnyEvent;
use Yajny\Member\Models\OtpVerification;

class SendOTP extends YajnyEvent
{
    public $user;
    public $phone_number;
    public $message;
    public $queue = 'otp';
    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct($user, $phone_number)
    {
        $this->user = $user;
        $this->phone_number = $phone_number;
        $otp = $this->getOTP($user->user_id, $phone_number);

        $this->message = "<#>Thanks for registering to Yajny! Your Yajny activation code is {$otp}";
        if ($user->user_lang == 'ar')
            $this->message = "<#>شكراً لتسجيلك في يچني! كود التفعيل الخاص بك في يچني هو {$otp}";
    }

    /**
     * Handle the event.
     *
     * @param  DummyEvent  $event
     * @return void
     */
    public function handle(DummyEvent $event)
    {
        //
    }

    private function getOTP($user_id, $phone_number)
    {
        $latest_otp = OtpVerification::where('user_id', $user_id)
            ->where('channel', 'phone')
            ->where('type', 'mobile_verify')
            ->where('target', $phone_number)
            ->first();
        if ($latest_otp) {
            $latest_otp->expired_at = date('Y-m-d H:i:s', strtotime('+15 minutes'));
            $latest_otp->save();
            return intval($latest_otp->otp);
        }
        else
            return $this->createOTP($user_id, $phone_number);
    }

    private function createOTP($user_id, $phone_number)
    {
        $otp = new OtpVerification();
        $otp->user_id = $user_id;
        $otp->channel = 'phone';
        $otp->type = 'mobile_verify';
        $otp->target = $phone_number;
        $otp->otp = rand(1000, 9999);
        $otp->expired_at = date('Y-m-d H:i:s', strtotime('+15 minutes'));
        $otp->save();

        return $otp->otp;
    }
}
