<?php
/*
 * Copyright (c) 2023.
 *
 * A.Сапаргалиев
 * ТОО "Дизайн лаборатория А7"
 * Астана
 */

namespace App\Modules\Auth\Http\Controllers;

use A7kz\Platform\Http\Controllers\Controller;
use A7kz\Platform\Models\UniModel;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use JetBrains\PhpStorm\NoReturn;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = null;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
        $this->redirectTo = lurl('/');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $usersTable = (new User())->getTable();

        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255', Rule::unique($usersTable, 'username')],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique($usersTable, 'email')],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'biniin' => ['required', 'string', 'min:12', 'max:12'],
            'isorg' => ['boolean'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User;
     */
    #[NoReturn] protected function create(array $data)
    {
        $user = new User();

        $user->forceFill([
            'name' => $data['name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password'])
        ]);

        $user->save();

        $userRole = UniModel::model('core_roles')
            ->where('alias', 'user')
            ->first();

        if (!empty($userRole)) {
            $userRoleModel = UniModel::model('core_user_roles');

            $userRoleModel->forceFill([
                'user_id' => $user->id,
                'role_id' => $userRole->id
            ]);

            $userRoleModel->save();
        }
        $company = UniModel::model(config('platform.company.tables.company'))
            ->firstOrCreate([
                'name'      => $data['name'],
                'biniin'    => $data['biniin'],
                'fullname'  => $data['name'],
                'segment'   => 'sol'
            ]);

        $ucr = UniModel::model(config('platform.company.tables.company_user_role'))
            ->firstOrCreate([
                'user_id' => $user->id,
                'role_id' => 7,
                'company_id' => $company->id
            ]);
        if (!$ucr) {
            UniModel::model(config('platform.company.tables.company_user_role'))
                ->create([
                    'user_id' => $user->id,
                    'role_id' => 6,
                    'company_id' => $company->id
                ]);
        }

        UniModel::model(config('platform.company.tables.company_user'))
            ->firstOrCreate([
                'company_id' => $company->id,
                'user_id'    => $user->id,
                'default'    => true,
            ]);

        return $user;
    }

    public function showRegistrationForm()
    {
        return view('platform.auth::register');
    }
}
