<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\ActivationAccountMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $customMessage = [
            'name.required' => 'Nama wajib diisi',
            'name.max' => 'Nama maksimal 255 karakter',
            'name.string' => 'Nama harus berupa string',

            'email.required' => 'Email wajib diisi',
            'email.email' => 'Email tidak valid',
            'email.unique' => 'Email sudah terdaftar',

            'password.required' => 'Password wajib diisi',
            'password.confirmed' => 'Password tidak cocok',
            'password.min' => 'Password minimal 8 karakter',
        ];

        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
        ], $customMessage);

        if ($validator->fails()) {
            toast($validator->messages()->all()[0], 'error')->position('top')->autoclose(3000);
            return redirect()->back()->withInput();
        }

        $activationCode = Str::random(4);

        DB::beginTransaction();
        $user = new User();
        $user->username = $request->username;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->activation_code = $activationCode;
        $user->is_active = false;

        try {
            $user->save();
            DB::commit();
            Mail::to($request->email)->send(new ActivationAccountMail($user));
            toast('Registrasi berhasil', 'success')->position('top')->autoclose(3000);
            return redirect()->route('auth.two_step_verify', ['email' => $request->email]);
        } catch (\Throwable $th) {
            DB::rollBack();
            toast($th->getMessage(), 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
