<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use App\Models\User;

class LandlordController extends Controller
{
    public function index()
    {
        // Overview stats across the whole SaaS
        $stats = [
            'total_firms' => Tenant::count(),
            'active_firms' => Tenant::where('subscription_status', 'active')->count(),
            'total_revenue' => Tenant::sum('total_paid'), // Assuming you add this column
            'new_this_month' => Tenant::whereMonth('created_at', now()->month)->count(),
        ];

        $tenants = Tenant::with('domains')->latest()->paginate(10);

        return view('landlord.dashboard', compact('stats', 'tenants'));
    }

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

        // 1. Fetch the Main Admin User from the Tenant's Database
        // We assume the tenant's email is the identifier for the main admin.
        $tenantAdmin = $tenant->run(function () use ($tenant) {
            return User::where('email', $tenant->email)->with('roles')->first();
        });

        return view('landlord.tenants.show', compact('tenant', 'tenantAdmin'));
    }

    public function update(Request $request, $id)
    {
        $tenant = Tenant::findOrFail($id);

        // 1. Validate
        $request->validate([
            'firm_name' => 'required|string|max:255',
            'email'     => 'required|email', // We don't use unique here strictly to allow keeping same email
            'plan'      => 'required|in:free,premium,enterprise',
            'role'      => 'required|string' // The role to assign (super_admin, lawyer, etc)
        ]);

        // 2. Update Central Tenant Record
        $tenant->update([
            'firm_name' => $request->firm_name,
            'email'     => $request->email,
            'plan'      => $request->plan,
        ]);

        // 3. Update the User INSIDE the Tenant Database
        $tenant->run(function () use ($request, $tenant) {

            // A. Find the user (using the OLD email or the ID if you had it)
            // For simplicity, we search by the stored email.
            // NOTE: If you changed the email in step 2, we might lose them if we don't track the old one.
            // A safer way is to fetch the user *before* updating the tenant, or assume there's only 1 admin for now.
            $user = User::where('email', $tenant->getOriginal('email'))->first();

            if ($user) {
                // B. Update User Details
                $user->update([
                    'name'  => $request->firm_name . ' Admin', // Optional: Rename user to match firm
                    'email' => $request->email,
                ]);

                // C. Sync Roles (The Magic Part)
                // Ensure the role exists before assigning
                $roleName = $request->role;
                // We use 'web' guard because that's what the tenant uses
                $role = \Spatie\Permission\Models\Role::firstOrCreate(['name' => $roleName, 'guard_name' => 'web']);

                $user->syncRoles($role);
            }
        });

        return redirect()->route('landlord.tenants.show', $tenant->id)
            ->with('success', 'Tenant and Admin Role updated successfully!');
    }

    public function edit( $id)
    {

        $tenant = Tenant::findOrFail($id);

        // 1. Fetch the Main Admin User from the Tenant's Database
        // We assume the tenant's email is the identifier for the main admin.
        $tenantAdmin = $tenant->run(function () use ($tenant) {
            return User::where('email', $tenant->email)->with('roles')->first();
        });
               return view('landlord.tenants.edit', compact('tenant', 'tenantAdmin'));

    }

    public function impersonate(Tenant $tenant)
    {
        // Generate the secure redirect to the tenant domain
        $redirectUrl = $tenant->run(function () {
            $admin = \App\Models\User::where('role', 'admin')->first();

            if (!$admin) return null;

            return URL::signedRoute(
                'impersonate.verify',
                ['user' => $admin->id],
                now()->addMinutes(1)
            );
        });

        if (!$redirectUrl) {
            return back()->with('error', 'No admin found for this firm.');
        }

        return redirect($redirectUrl);
    }

    public function toggleStatus(Tenant $tenant)
    {
        // Toggle between active and suspended
        $newStatus = ($tenant->subscription_status === 'active') ? 'suspended' : 'active';

        $tenant->update([
            'subscription_status' => $newStatus
        ]);

        $message = $newStatus === 'suspended'
            ? "Workspace for {$tenant->firm_name} has been suspended."
            : "Workspace for {$tenant->firm_name} has been reactivated.";

        return back()->with('status', $message);
    }
}
