<?php

namespace Modules\User\Services;

use Illuminate\Http\Request;
use Modules\User\Models\Verification;
use Modules\User\Interfaces\VerificationRepositoryInterface;

class VerificationService
{
    private VerificationRepositoryInterface $verificationRepository;

    public function __construct(VerificationRepositoryInterface $verificationRepository, private UserService $userService)
    {
        $this->verificationRepository = $verificationRepository;
    }
    public function get(array $request = [])
    {
        $builder = $this->verificationRepository->get($request);


        if (@$request['code']) {
            $builder->where('code', $request['code']);
        }
        if (@$request['phone']) {
            $builder->where('phone', $request['phone']);
        }
        if (@$request['op']) {
            $builder->where('op', $request['op']);
        }
        // if (@$request['id_number']) {
        //     $builder->where('id_number', $request['id_number']);
        // }



        $verifications = $builder->first();
        return $verifications;
    }
    public function checkItem($id)
    {
        $verification = $this->verificationRepository->checkItem($id);
        return $verification;
    }

    public function getItem($id)
    {
        return $this->verificationRepository->getItem($id);
    }
    public function createCode(array $request): Verification
    {
        $code = rand(1000, 9999);
        $verification = null;
        $checkCode = $this->get($request);
        $request['code'] = $code;
        if ($request['op'] !== "register") {
            $user = $this->userService->get(['phone' => $request['phone']])->first();
            $request['user_id'] = $user->id;
        }
        if ($checkCode) {
            $verification = $this->update($request, $checkCode->id);
        }
        if (!$verification) {
            $verification = $this->create($request);
        }
        return $verification;
    }
    public function create(array $request): Verification
    {
        $verification = $this->verificationRepository->create($request);
        return $verification;
    }
    public function update(array $request, int $id): Verification
    {
        $verification = $this->checkItem($id);
        $verification = $this->verificationRepository->update($request, $verification);
        return $verification;
    }
    public function destroy(int $id): void
    {
        $verification = $this->checkItem($id);
        if ($verification) {
            $this->verificationRepository->destroy($verification);
        }
    }


}
