<?php

namespace App\Services;

use App\Models\Submodule;
use App\Models\UserPackage;
use Exception;

class Register
{
    public function createAccount($inputData){
        $result = [];
        $user = app(\App\Models\User::class);
        if ($saved = $user->addUser($inputData)) {
            $result = $saved;
            $result['security_key'] = customEncrypt(json_encode(['user_id'=>$saved->id]));
        }

        return $result;
    }

    public function addProfile($inputData,$user_id):bool{
        $result = false;
        $user = app(\App\Models\User::class);
        if ($saved = $user->userupdate($inputData,$user_id)) {
            $result = true;
        }

        return $result;
    }
    /**
     * @throws Exception
     */
    public function addPackage($package_id, $user_id){

        $comapanyTypeArray = [
            '1'=>3,
            '2'=>3,
            '3'=>1
        ];

        $userPackage = new UserPackage();

        if($userPackage->isExistPackage($package_id,$user_id)){
            throw new \Exception("Package already taken.");
        }
        $inputData['package_id'] = $package_id;
        $inputData['user_id'] = $user_id;
        if(!$userPackage->setUserPackage($inputData)) {
            throw new \Exception("Package doesn't added.Please try again!");
        }

        $user = app(\App\Models\User::class);

        $updateData['credit_report_company_type'] = $comapanyTypeArray[$inputData['package_id']];

        if(!$user->userupdate($updateData,$inputData['user_id'])){
            throw new \Exception("Package doesn't added.Please try again!");
        }

        return true;
    }

    public function emailVarification($inputData){
        $result = [];
        $user = app(\App\Models\User::class);
        if ($saved = $user->getUserByEmail($inputData)) {
            $result = $saved;
        }
        return $result;
    }

    public function roleList($inputData)
    {
        $result = [];
        $submoduleResult=Submodule::join('modules', 'submodules.module_id', '=', 'modules.id')
            ->select('submodules.*','modules.name as moduleName');

        $result= $submoduleResult->get();

        return $result;

    }
}
