<?php

namespace App\Http\Controllers\SuperAdmin;

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

use Illuminate\Support\Facades\Auth;

class TenantController extends Controller
{
    public function index()
    {
        $tenants = Tenant::all();
        return view('super-admin.tenants.index', compact('tenants'));
    }

    public function create()
    {
        return view('super-admin.tenants.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'id' => 'required|string|unique:mysql.tenants',
            'domain' => 'required|string|unique:mysql.domains,domain',
        ]);

        $tenant = Tenant::create([
            'id' => $validated['id'],
            'last_updated_by' => Auth::user()->name ?? 'Super Admin',
        ]);

        $tenant->domains()->create([
            'domain' => $validated['domain'],
        ]);

        return redirect()->route('super-admin.tenants.index')
            ->with('success', 'Tenant created successfully.');
    }

    public function edit($id)
    {
        $tenant = Tenant::findOrFail($id);
        return view('super-admin.tenants.edit', compact('tenant'));
    }

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

        $validated = $request->validate([
            'domain' => 'required|string|unique:mysql.domains,domain,' . $tenant->domains->first()->id,
        ]);

        // Update domain
        $tenant->domains()->update([
            'domain' => $validated['domain'],
        ]);

        $tenant->update([
            'last_updated_by' => Auth::user()->name ?? 'Super Admin',
        ]);

        return redirect()->route('super-admin.tenants.index')
            ->with('success', 'Tenant updated successfully.');
    }

    public function destroy($id)
    {
        $tenant = Tenant::findOrFail($id);
        $tenant->delete();

        return redirect()->route('super-admin.tenants.index')
            ->with('success', 'Tenant deleted successfully.');
    }
}
