<?php


namespace App\Http\Services;


use App\Enums\SMSEnums;
use App\Factory\SMSFactory\FirebaseSMSFactory;
use App\Factory\SMSFactory\OoredooSMSFactory;
use App\Factory\SMSFactory\vodafoneSMSFactory;
use App\Models\SMSLog;
use Carbon\Carbon;

class SMSService
{
    private $provider;
    private $user;

    public function __construct($user)
    {
        $this->user =   $user;

        $this->provider = new vodafoneSMSFactory();

//        if ( $user->country->code == '+974') {
//            $this->provider = new OoredooSMSFactory();
//        } else {
//            $this->provider = new FirebaseSMSFactory();
//        }
    }

    public function provider() {
        return $this->provider;
    }

    public function sendActivationCode($user): string
    {
        if( ! $this->canSendSms() ) { return  'limited'; }

        if(app()->isProduction()){
            $code     =   random_int(1000, 9999);
        }else{
            $code     = 1234;
        }
        $message  = trans('global.your_activation_code', ['code'=>$code]);
        if(app()->isProduction()){
            $res = $this->provider->sendMessage($message, $user->phone_with_code);
        }else{
            $res ='';
        }
        $this->provider->saveMessageToDB($message, SMSEnums::Activation, $user, $res, $code);
        return trans('global.message_was_sent_successfully');
    }

    public function sendResetCode($user): string
    {
        if( ! $this->canSendSms() ) { return  'limited'; }

        if(app()->isProduction()){
            $code     =   random_int(1000, 9999);
        }else{
            $code     = 1234;
        }
        $message  = trans('global.your_reset_code', ['code'=>$code]);
        if(app()->isProduction()) {
            $res = $this->provider->sendMessage($message, $user->phone_with_code);
        }else{
            $res ='';
        }
        $this->provider->saveMessageToDB($message, SMSEnums::ResetPassword, $user, $res, $code);
        return trans('global.message_was_sent_successfully');
    }

    public function canSendSms() {
        return config('services.sms.sms_allow') && SMSLog::query()
                ->where('created_at', Carbon::today())
                ->where('user_id', $this->user->id)
                ->count() < config('services.sms.sms_limitation');
    }
}
