<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Vendor;
use App\Models\PurchaseOrder;
use App\Models\Warehouse;
use App\Models\Inventory;
use Inertia\Inertia;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $centralDomains = config('tenancy.central_domains', []);

        $demoPort = config('tenancy.demo_tenant_port');
        if ((!$demoPort || request()->getPort() != $demoPort) && in_array(request()->getHost(), $centralDomains)) {
            return redirect()->route('landlord.dashboard');
        }

        $stats = [
            'productsCount' => Product::count(),
            'vendorsCount' => Vendor::count(),
            'purchaseOrdersCount' => PurchaseOrder::count(),
            'warehousesCount' => Warehouse::count(),
            'totalInventoryValue' => Inventory::join('products', 'inventories.product_id', '=', 'products.id')
                ->sum('inventories.quantity'), // Simplified, maybe just sum quantities for now
            'pendingOrdersCount' => PurchaseOrder::where('status', 'pending')->count(),
            'lowStockCount' => Inventory::whereColumn('quantity', '<=', 'safety_stock')->count(),
        ];

        return Inertia::render('Dashboard', [
            'stats' => $stats,
        ]);
    }
}
