<?php

namespace Yajny\EventsYj\Events;

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

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

        $this->message = "<#> Your Yajny email verification 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, $email)
    {
        $latest_otp = OtpVerification::where('user_id', $user_id)
            ->where('channel', 'email')
            ->where('type', 'reset_password')
            ->where('target', $email)
            ->first();
        if ($latest_otp) {
            $latest_otp->expired_at = date('Y-m-d H:i:s', strtotime('+5 minutes'));
            $latest_otp->save();
            return intval($latest_otp->otp);
        }
        else
            return $this->createOTP($user_id, $email);
    }

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

        return $otp->otp;
    }
}
