<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\Timezone;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
use Illuminate\Support\Str;

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)
    {
        $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:' . User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'policy_check' => 'accepted',
        ]);

        // 1. Create the Client first
        $slug = 'flixoo-'.time();
        $client = new Client();
        $client->first_name = $request->first_name;
        $client->last_name = $request->last_name;
        $client->company_name = 'flixoo';
        $client->webhook_verify_token = Str::random(30);
        $client->api_key = Str::random(30);
        $client->slug = $slug;
        $client->save();

        // 2. Create the User and assign the client_id
        $user = User::create([
            'first_name' => $request->first_name,
            'last_name'  => $request->last_name,
            'role_id'    => 2,
            'email'      => $request->email,
            'password'   => Hash::make($request->password),
            'client_id'  => $client->id
        ]);

        // event(new Registered($user));

        Auth::login($user);

        return response()->json([
            'status' => 'success',
            'redirect' => url('/')
        ]);
    }
}
