<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use Illuminate\Http\Request;

class RegisterTenantController extends Controller
{
    public function store(Request $request)
    {
        // 1. Validate Input
        $data = $request->validate([
            'firm_name' => 'required|string',
            'domain' => 'required|string|alpha_dash|unique:domains,domain',
            'email' => 'required|email',
            'password' => 'required'
        ]);

        // 2. Create the Tenant (This creates the Database!)
        $tenant = Tenant::create([
            'id' => $data['domain'], // e.g. 'smith-law'
            'firm_name' => $data['firm_name'],
            // You can pass extra attributes here that you want in the 'tenants' table
        ]);

        // 3. Create the Domain (e.g. smith-law.legalpro.com)
        $tenant->domains()->create([
            'domain' => $data['domain'] . '.' . config('tenancy.central_domains')[0]
        ]);

        // 4. Create the Admin User INSIDE that new database
        // We use run() to execute code "inside" the tenant's context
        $tenant->run(function () use ($data) {
            \App\Models\User::create([
                'name' => 'Admin',
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
                'role' => 'admin', // Ensure you have roles setup
            ]);
        });

        return redirect()->route('dashboard')->with('success', 'Firm created! You can now login at ' . $tenant->domains->first()->domain);
    }
}
