<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; // Important import
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;

class TenantRegisterController extends Controller
{
    public function showRegistrationForm()
    {
        return view('auth.register-tenant');
    }

    public function register(Request $request)
    {
        // 1. Validation (Moved OUTSIDE try-catch so form errors show up correctly)
        $request->validate([
            'firm_name' => 'required|string|max:255',
            // CRITICAL FIX: Check 'tenants' table too to prevent SQL Error 1062
            'subdomain' => 'required|alpha_dash|unique:domains,domain|unique:tenants,id',
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        try {
            // 2. Database Transaction
            // We capture the created tenant in the $tenant variable
            $tenant = DB::transaction(function () use ($request) {

                // A. Create the Tenant
                $tenant = Tenant::create([
                    'id' => $request->subdomain,
                    'firm_name' => $request->firm_name,
                    'email' => $request->email,
                ]);

                // B. Create the Domain
                $tenant->domains()->create([
                    'domain' => $request->subdomain . '.' . config('tenancy.central_domains')[0],
                ]);

                // C. Create the User INSIDE the tenant's database
                $tenant->run(function () use ($request) {
                    User::create([
                        'name' => $request->name,
                        'email' => $request->email,
                        'password' => Hash::make($request->password),
                        'role' => 'admin',
                    ]);
                });

                return $tenant; // Return to the $tenant variable outside
            });

            // 3. Success Redirect
            $protocol = request()->secure() ? 'https://' : 'http://';
            $domain = $tenant->domains->first()->domain;
            $loginUrl = $protocol . $domain . '/login';

            return redirect($loginUrl . '?registered=true');

        } catch (\Exception $e) {
            // 4. Handle System Errors
            // Log the full error for you to debug
            \Log::error("Tenant Registration Failed: " . $e->getMessage());

            // Show a friendly message to the user
            return redirect()->back()
                ->withInput($request->except('password', 'password_confirmation'))
                ->withErrors(['error' => 'Registration failed. Please try a different subdomain or contact support.']);
        }
    }
}
