<?php

namespace App\Http\Controllers\SiteAdmin;

use App\Http\Controllers\Concerns\ResolvesSiteContext;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Support\CacheKeys;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class DashboardController extends Controller
{
    use ResolvesSiteContext;

    public function index(Request $request): View
    {
        $siteId = $this->siteId($request);
        $site = $this->site($request);

        $stats = Cache::remember(
            CacheKeys::merchantDashboardStats($siteId),
            now()->addMinutes(10),
            fn () => [
                'admins' => Admin::query()->where('merchant_id', $siteId)->count(),
                'users' => User::query()->forMerchant($siteId)->count(),
                'products' => Product::query()->forMerchant($siteId)->count(),
                'orders' => Order::query()->forMerchant($siteId)->count(),
                'pending_orders' => Order::query()->forMerchant($siteId)->where('status', 'pending')->count(),
            ]
        );

        return view('site_admin.dashboard', [
            'site' => $site,
            'stats' => $stats,
            'cacheMeta' => [
                'store' => config('cache.default'),
                'ttl' => '10m',
            ],
        ]);
    }
}
