<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Otp;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class OtpService
{
    public function generateOtp()
    {
        if (!app()->isProduction()) {
            return config('sms-manager.otp_default_value');
        }

        $characters = '0123456789';
        $charactersLength = strlen($characters);
        $length = config('sms-manager.otp_length');
        $otp = '';
        for ($i = 0; $i < $length; $i++) {
            $otp .= Str::substr($characters, random_int(0, $charactersLength - 1), 1);
        }

        return $otp;
    }

    public function sendOtp($cellphone, $code)
    {
        if (!app()->isProduction()) {
            return true;
        }

        $smsService = new SmsService;

        return $smsService->sendVerifyWithKavenegar($cellphone, config('sms-manager.otp_template_name'), $code);
    }

    public function checkOtp($cellphone, $code)
    {
        $otp = Otp::where('cellphone', $cellphone)->latest()->first();
        if (! $otp) {
            return false;
        }

        return Hash::check($code, $otp->code);
    }

    public function getLatestCode($cellphone)
    {
        return Otp::where('cellphone', $cellphone)->latest()->firstOrFail();
    }
}
