<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
// use Stancl\Tenancy\Database\Models\Tenant;
use App\Models\Tenant;
use App\Models\Domain;

class TenantController extends Controller
{
    public function index()
    {
        $tenants = Tenant::with('domains')->latest()->paginate(20);
        return view('admin.tenants.index', compact('tenants'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'company_name' => ['required','string','max:255'],
            'domain'       => ['required','string','max:255','unique:domains,domain'],
            'admin_name'   => ['required','string','max:255'],
            'admin_email'  => ['required','email','max:255'],
            'admin_pass'   => ['required','string','min:8'],
        ]);

        $tenant = Tenant::create([
            'id'   => (string) Str::uuid(),
            'data' => ['name' => $data['company_name']],
        ]);

        $tenant->domains()->create([
            'domain' => $data['domain'], // e.g. companyabc.yourapp.com
        ]);

        // Create first tenant user in tenant DB
        $tenant->run(function () use ($data) {
            \App\Models\User::create([
                'name'     => $data['admin_name'],
                'email'    => $data['admin_email'],
                'password' => Hash::make($data['admin_pass']),
            ]);
        });

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

    public function destroy(Tenant $tenant)
    {
        // optional: delete related domains
        $tenant->domains()->delete();

        // deletes tenant record (tenant DB data depends on your tenancy config)
        $tenant->delete();

        return back()->with('success', 'Tenant deleted.');
    }
}
