<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\LoginActivities;
use App\Models\Page;
use App\Models\User;
use App\Rules\Recaptcha;
use App\Traits\NotifyTrait;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use App\Models\CustomCss;

class RegisteredUserController extends Controller
{
    use NotifyTrait;

    public function create()
    {
        if (! setting('account_creation', 'permission')) {
            abort('403', 'User registration is closed now');
        }

        $page = Page::where('code', 'register')->where('locale', app()->getLocale())->where('theme', site_theme())->first();

        if (! $page) {
            $page = Page::where('code', 'register')->where('locale', defaultLocale())->where('theme', site_theme())->first();
        }

        $data = json_decode($page?->data, true);

        $location = getLocation();
        $googleReCaptcha = plugin_active('Google reCaptcha');

        $customCss = CustomCss::first();
        
        return view('frontend::auth.register', compact('location', 'data', 'googleReCaptcha', 'customCss'));
    }

    /**
     * Handle an incoming registration request.
     *
     * @return RedirectResponse
     *
     * @throws ValidationException
     */
    public function store(Request $request)
    {
        // Validate request
        $isUsername = (bool) getPageSetting('username_validation') && getPageSetting('username_show');
        $isPhone = (bool) getPageSetting('phone_validation') && getPageSetting('phone_show');
        $isGender = (bool) getPageSetting('gender_validation') && getPageSetting('gender_show');
        $isCompanyName = (bool) getPageSetting('company_name_validation') && getPageSetting('company_name_show');

        $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'g-recaptcha-response' => [Rule::requiredIf(plugin_active('Google reCaptcha')), new Recaptcha],
            'gender' => [Rule::requiredIf($isGender), 'in:male,female,others'],
            'username' => [Rule::requiredIf($isUsername), 'string', 'max:255', 'unique:users'],
            'phone' => [Rule::requiredIf($isPhone), 'string', 'max:255'],
            'company_name' => [Rule::requiredIf($isCompanyName), 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', Rules\Password::defaults()],
            'i_agree' => ['required'],
        ]);

        // Register user
        $user = User::create([
            'first_name' => $request->get('first_name'),
            'last_name' => $request->get('last_name'),
            'company_name' => $isCompanyName ? $request->get('company_name') : null,
            'gender' => $isGender ? $request->get('gender') : null,
            'username' => $isUsername ? $request->get('username') : generateUsername($request->get('first_name'), $request->get('last_name')),
            'phone' => $isPhone ? $request->get('phone') : null,
            'email' => $request->get('email'),
            'password' => Hash::make($request->get('password')),
        ]);

        $shortcodes = [
            '[[full_name]]' => $user->full_name,
        ];

        // Notify user and admin
        $this->pushNotify('new_user', $shortcodes, route('admin.user.edit', $user->id), $user->id, 'Admin');
        $this->smsNotify('new_user', $shortcodes, $user->phone);

        Auth::login($user);
        LoginActivities::add();

        return to_route('user.dashboard');
    }
}
