<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\View;
use App\Repositories\ExecutiveRepository;
use Throwable;

final class DashboardController
{
    public function index(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode);
        $executive = [];
        $executiveError = null;

        try {
            $executive = (new ExecutiveRepository($hospitalCode))->commandCenter();
        } catch (Throwable $e) {
            $executiveError = $e->getMessage();
            $this->log($e);
        }

        View::render('dashboard/index', [
            'title' => 'Executive Command Center',
            'activePage' => 'dashboard',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'executive' => $executive,
            'executiveError' => $executiveError,
        ]);
    }

    private function log(Throwable $e): void
    {
        $file = \storage_path('logs/app.log');
        $dir = dirname($file);
        if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
        @file_put_contents($file, '[' . date('c') . '] DashboardController: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
    }
}
