<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class RegisterController extends Controller
{
    public function showRegistrationForm()
    {
        if (Auth::check()) {
            return redirect()->route(Auth::user()->isAdmin() ? 'dashboard' : 'user.dashboard');
        }
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $request->validate([
            // User fields
            'name'                  => ['required', 'string', 'max:255'],
            'email'                 => ['required', 'email', 'max:255', 'unique:users,email'],
            'password'              => ['required', 'string', 'min:8', 'confirmed'],
            'phone'                 => ['nullable', 'string', 'max:20'],
            'whatsapp_num'          => ['nullable', 'string', 'max:20'],
            // Company fields
            'company_name'          => ['required', 'string', 'max:255'],
            'company_address'       => ['nullable', 'string', 'max:500'],
            'currency'              => ['nullable', 'string', 'max:10'],
            'company_description'   => ['nullable', 'string', 'max:1000'],
        ]);

        // Wrap in a transaction so user + company are always created together
        DB::transaction(function () use ($request) {

            // 1. Create the user first
            $user = User::create([
                'name'          => $request->name,
                'email'         => $request->email,
                'password'      => $request->password,
                'phone'         => $request->phone,
                'whatsapp_num'  => $request->whatsapp_num,
                'business_name' => $request->company_name,
                'plan_status'   => 'trial',
                'role'          => 'user',
                'api_token'     => $token = strtoupper(Str::random(20)),
                'verify_token'  => $token,
            ]);

            // 2. Create company with real user_id
            $company = Company::create([
                'name'        => $request->company_name,
                'address'     => $request->company_address,
                'currency'    => $request->currency ?: 'USD',
                'description' => $request->company_description,
                'user_id'     => $user->id,
            ]);

            // 3. Link user back to company
            $user->update(['company_id' => $company->id]);

            // 4. Log the user in
            Auth::login($user);
        });

        return redirect()->route('user.dashboard');
    }
}
