<?php

namespace App\Http\Controllers;

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

class TenantManagementController extends Controller
{
    /**
     * Display a listing of the tenants.
     */
    public function index(Request $request)
    {
        $query = Tenant::with('domains')->latest();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('tenant_id', 'like', "%{$search}%")
                  ->orWhere('school_name', 'like', "%{$search}%");
        }

        $tenants = $query->paginate(20);
        return view('admin.tenants.index', compact('tenants'));
    }

    /**
     * Display the specified tenant.
     */
    public function show(Tenant $tenant)
    {
        $tenant->load('domains', 'invoices');
        
        $pendingBalance = $tenant->invoices()->where('status', 'pending')->sum('amount');
        $totalPaid = $tenant->invoices()->where('status', 'paid')->sum('amount');
        $surplus = \Illuminate\Support\Facades\DB::table('tenantbalances')
                    ->where('tenant_id', $tenant->tenant_id)
                    ->value('balance') ?? 0;

        return view('admin.tenants.show', compact('tenant', 'pendingBalance', 'totalPaid', 'surplus'));
    }

    /**
     * Show the form for editing the specified tenant.
     */
    public function edit(Tenant $tenant)
    {
        return view('admin.tenants.edit', compact('tenant'));
    }

    /**
     * Update the specified tenant in storage.
     */
    public function update(Request $request, Tenant $tenant)
    {
        $validated = $request->validate([
            'school_name' => 'required|string|max:255',
            'is_active' => 'boolean',
            'subscription_ends_at' => 'nullable|date',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $tenant->update($validated);

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

    /**
     * Remove the specified tenant from storage.
     */
    public function destroy(Tenant $tenant)
    {
        // Delete the tenant record from the central registry.
        $tenant->delete();

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