<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Lib\DashboardStats;
use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Incident;
use App\Models\Tenant;
use App\Models\WorkOrder;
use Core\Controller;
use Core\Session;

final class HomeController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    public function index(): void
    {
        $tenantId = (int) ($_SESSION['tenant_id'] ?? 0);
        $stats    = DashboardStats::compute($tenantId);

        $this->render('home/index', array_merge($stats, [
            'user'          => Session::user(),
            'tenant'        => Tenant::findById($tenantId),
            'dashboardMode' => 'exec',
            'openIncidents' => Incident::listForTenant($tenantId, ['status' => 'open']),
            'openWos'       => WorkOrder::listForTenant($tenantId, ['status' => 'in_progress']),
        ]));
    }

    /**
     * JSON endpoint powering the Vue-driven date-range refresh.
     * GET /Home/data?from=YYYY-MM-DD&to=YYYY-MM-DD
     */
    public function data(): void
    {
        $tenantId = (int) ($_SESSION['tenant_id'] ?? 0);
        $from = trim((string) ($_GET['from'] ?? '')) ?: null;
        $to   = trim((string) ($_GET['to']   ?? '')) ?: null;

        foreach (['from' => $from, 'to' => $to] as $k => $v) {
            if ($v !== null && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $v)) {
                $this->json(['error' => "Bad {$k} — expected YYYY-MM-DD"], 422);
            }
        }
        if ($from && $to && strtotime($from) > strtotime($to)) {
            $this->json(['error' => 'from cannot be after to'], 422);
        }

        $this->json(DashboardStats::compute($tenantId, $from, $to));
    }
}
