<?php

namespace App;

use App\Events\V1\EventSendOtpSms;
use App\Events\V1\EventSentOtpEmail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Mail;

class OtpManager extends Model
{
    const STATUS_UNVERIFIED = 'unverified';

    use SoftDeletes;

    protected $table = 'otp_manager';

    protected $fillable = ['mobile_number', 'otp', 'deleted_at'];

    public static function addEntry($otp, $mobile_number, array $param = []) {
        $obj = new self;
        $obj->otp = $otp;
        $obj->mobile_number = $mobile_number;
        $obj->save();
        $param['id'] = $obj->id;
        event(new EventSendOtpSms($param));
        event(new EventSentOtpEmail($param));
        return $obj;
    }

    public static function getOtpEntry($id, $status = '') {
        $query = self::where('id', $id);
        if(!empty($status)) {
            $query = $query->where('status', $status);
        }
        $obj = $query->first();

        if(!empty($obj)) {
            return $obj;
        }
        return false;
    }


    public function sendOtpOnEmail(array $param = []) {
        if(Arr::has($param, 'application_id')) {
            if(Arr::has($param,'applicant') && Arr::get($param,'applicant') == 1){
                $data = ConsumerApplication::where('id', Arr::get($param,'application_id'))->where('mobile_number', $this->mobile_number)->first(['email', 'name']);
            } else {
                $data = ConsumerApplication::where('id', Arr::get($param,'application_id'))->where('co_applicant_mobile_number', $this->mobile_number)->first(['co_applicant_email as email', 'co_applicant_name as name']);
            }
        } else if (Arr::has($param,'merchant_id')){
            $data = Merchant::where('id', Arr::get($param,'merchant_id'))->first(['email', 'merchant_name as name']);
        }
        if(!empty($data->email)){
            $message = "Dear ".$data->name.",<br/>Your OTP for E-Signing Agreement with Credit Fair is  ".$this->otp.".";
            $email = $data->email;
            Mail::send('emails.reminders.basic_reminder',
                ['body'=> $message]
                , function ($message) use ($email) {
                    $message->to($email)->subject('OTP for E-Signing Agreement with Credit Fair');
                });
            return true;
        }
        return "No email found to send OTP";
    }


    public function sendOtpOnSms(array $param = []) {
        $mobile_number = '91' . $this->mobile_number;
        $message = "Your Credit Fair verification code is ".$this->otp."<br/>Best Regards,<br/>Team Credit Fair";
        $entity = ['templateid' => '1307161519272825845', 'entityid' => Templates::$entityid];
        send_sms($mobile_number, ['message' => $message, 'OTP' => true, 'templateDetails' => $entity]);
        return true;
    }
}
