<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\AccessControl;
use App\Core\Auth;
use App\Core\Request;
use App\Core\View;
use App\Services\DiarAccessPolicy;
use App\Repositories\DiarExecutiveOverviewRepository;
use Throwable;

final class DiarExecutiveOverviewController
{
    public function index(): void
    {
        Auth::requireLogin();
        // DIAR_6B_2_R2_EXECUTIVE_ACL
        $policy = new DiarAccessPolicy();
        if (!$policy->canViewModule('executive')) {
            $policy->redirectHiddenRoute();
        }

        $filters = [
            'site' => strtoupper(trim((string)Request::get('site', 'ALL'))),
            'period' => strtolower(trim((string)Request::get('period', 'latest_closed'))),
            'month' => trim((string)Request::get('month', '')),
        ];
        $data = $this->emptyData($filters);
        $loadError = '';
        try {
            $data = (new DiarExecutiveOverviewRepository())->overview($this->allowedSites(), $filters);
        } catch (Throwable $e) {
            error_log('[DIAR-6B.2-R3.1][ExecutiveDashboard] ' . $e->getMessage());
            $loadError = $this->tr(
                'The medication risk overview is temporarily unavailable.',
                'تعذر تح�
يل النظرة التنفيذية ل�
خاطر �
خزون الأدوية �
ؤقتًا.'
            );
        }

        View::render('diar_command_center/executive_overview', [
            'title' => $this->tr('DIAR Executive Dashboard', 'لوحة DIAR للإدارة العليا'),
            'activePage' => 'diar-executive-overview',
            'hospitalCode' => Auth::hospital(),
            'hospital' => \config('hospitals.' . Auth::hospital(), []),
            'overview' => $data,
            'filters' => $filters,
            'loadError' => $loadError,
            'allowedSites' => $this->allowedSites(),
            'capabilities' => $this->capabilities(),
        ]);
    }

    /** @return array<int,string> */
    private function allowedSites(): array
    {
        $sites = [];
        if (AccessControl::allowsBranch('mnh')) {
            $sites[] = 'MNH';
        }
        if (AccessControl::allowsBranch('njch')) {
            $sites[] = 'NJCH';
        }
        return $sites;
    }

    /** @return array<string,bool> */
    private function capabilities(): array
    {
        $policy = new DiarAccessPolicy();
        return [
            'executive_overview' => $policy->canOpenRoute('diar-executive-overview'),
            'command' => $policy->canOpenRoute('diar-command-center'),
            'runs' => $policy->canOpenRoute('diar-engine-runs'),
            'movements' => $policy->canOpenRoute('diar-movement-dictionary'),
            'facts' => $policy->canOpenRoute('diar-daily-facts'),
            'cases' => $policy->canOpenRoute('diar-cases'),
            'investigations' => $policy->canOpenRoute('diar-investigations'),
            'reports' => $policy->canOpenRoute('diar-reports'),
            'rules' => $policy->canOpenRoute('diar-rules'),
        ];
    }

    /** @param array<string,string> $filters @return array<string,mixed> */
    private function emptyData(array $filters): array
    {
        return [
            'filters' => $filters,
            'requested_sites' => [],
            'available_sites' => [],
            'unavailable_sites' => [],
            'partial_coverage' => true,
            'scope_status' => 'UNAVAILABLE',
            'selected_month' => '',
            'month_status' => '',
            'updated_through' => '',
            'summary' => [],
            'site_cards' => [],
            'trend' => [],
            'top_stores' => [],
            'top_items' => [],
            'month_options' => [],
            'snapshot_refs' => [],
            'contract' => [],
        ];
    }

    private function tr(string $en, string $ar): string
    {
        return current_lang() === 'ar' ? $ar : $en;
    }
}
