<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Spatie\Permission\Models\Role; // Import this
use Illuminate\Support\Facades\DB;

class TenantController extends Controller
{
    public function create()
    {
        return view('landlord.tenants.create');
    }

 public function store(Request $request)
{
    $request->validate([
        'firm_name' => 'required|string|max:255',
        'subdomain' => 'required|alpha_dash|unique:domains,domain',
        'email' => 'required|email|max:255',
        'plan' => 'required|in:free,premium,enterprise',
    ]);

    $fullDomain = $request->subdomain . '.' . config('tenancy.central_domains')[0];

    try {
        $tenant = Tenant::create([
            'id' => $request->subdomain,
            'firm_name' => $request->firm_name,
            'email' => $request->email,
            'plan' => $request->plan,
            'subscription_status' => 'active',
        ]);

        // B. Create Domain
        $tenant->domains()->create([
            'domain' => $fullDomain
        ]);

        // C. Switch Context and Provision User
        $tenant->run(function () use ($request) {
            // 1. Create Roles
            $role = Role::firstOrCreate(['name' => 'super_admin', 'guard_name' => 'web']);
            Role::firstOrCreate(['name' => 'lawyer', 'guard_name' => 'web']);
            Role::firstOrCreate(['name' => 'clerk', 'guard_name' => 'web']);

            // 2. Create User
            $user = User::create([
                'name' => 'Firm Administrator',
                'email' => $request->email,
                'password' => Hash::make('password'),
            ]);

            // 3. Assign Role
            $user->assignRole($role);
        });

        return redirect()->route('dashboard')
            ->with('success', "Firm created! Domain: http://{$fullDomain}");

    } catch (\Exception $e) {
        // MANUAL ROLLBACK
        // If anything failed above, we delete the tenant (which drops the DB)
        // to prevent "zombie" half-created tenants.
        if (isset($tenant)) {
            $tenant->delete();
        }

        // Re-throw the error so you can see what actually happened
        throw $e;
    }
}

public function toggleStatus($id)
{
    $tenant = Tenant::findOrFail($id);

    // Toggle logic
    $tenant->subscription_status = ($tenant->subscription_status === 'active')
        ? 'suspended'
        : 'active';

    $tenant->save();

    $statusMessage = $tenant->subscription_status === 'active'
        ? "Firm access has been restored."
        : "Firm access has been suspended.";

    return back()->with('success', $statusMessage);
}

}
