<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant;
use App\Models\TenantCategory;
use App\Services\TenantService;
use Illuminate\Support\Str;

class TenantController extends Controller
{
    protected $tenantService;

    public function __construct(TenantService $tenantService)
    {
        $this->tenantService = $tenantService;
    }

    public function index()
    {
        $tenants = Tenant::orderBy('created_at', 'desc')->paginate(10);
        return view('admin.tenants.index', compact('tenants'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'domain' => 'required|string|unique:tenants,domain|max:255',
        ]);

        // Auto-generate DB name
        $dbName = 'tenant_' . str_replace('-', '_', Str::slug($validated['domain']));
        
        $tenantData = [
            'name' => $validated['name'],
            'domain' => $validated['domain'],
            'database_name' => $dbName,
            'status' => 'active',
        ];

        try {
            $this->tenantService->createTenant($tenantData);
            return redirect()->route('admin.tenants.index')->with('success', 'Tenant created successfully.');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to create tenant: ' . $e->getMessage()])->withInput();
        }
    }

    public function show(Tenant $tenant)
    {
        $tenant->load(['users', 'subscription.plan']);
        return view('admin.tenants.show', compact('tenant'));
    }

    public function edit(Tenant $tenant)
    {
        $categories = TenantCategory::where('is_active', true)->get();
        return view('admin.tenants.edit', compact('tenant', 'categories'));
    }

    public function update(Request $request, Tenant $tenant)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'status' => 'required|in:active,inactive,suspended',
            'tenant_category_id' => 'required|exists:tenant_categories,id',
        ]);

        $tenant->update($validated);

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

    public function destroy(Tenant $tenant)
    {
        // For safety, we are NOT dropping the database automatically here.
        // Just deleting the record.
        $tenant->delete();

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