<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\View;
use App\Repositories\InpatientDailyRevenueRepository;
use App\Services\InpatientDailyRevenueService;
use App\Services\XlsxExportService;
use Throwable;

final class InpatientDailyRevenueController
{
    public function index(): void
    {
        Auth::requireLogin();
        if (!$this->canAccess()) {
            $this->forbidden();
            return;
        }

        $hospitalCode = Auth::hospital();
        $loadResult = $this->loadReport($hospitalCode);
        $report = $loadResult['report'];
        $errorMessage = $loadResult['errorMessage'];

        View::render('inpatient_daily_revenue/index', [
            'title' => current_lang() === 'ar' ? 'الإيراد اليومي للمرضى المنومين' : 'Daily Inpatient Revenue',
            'activePage' => 'inpatient-daily-revenue',
            'hospitalCode' => $hospitalCode,
            'hospital' => \config('hospitals.' . $hospitalCode, []),
            'report' => $report,
            'errorMessage' => $errorMessage,
        ]);
    }

    public function export(): void
    {
        Auth::requireLogin();
        if (!$this->canAccess()) {
            http_response_code(403);
            return;
        }

        $hospitalCode = Auth::hospital();
        $loadResult = $this->loadReport($hospitalCode);
        $report = $loadResult['report'];
        $errorMessage = $loadResult['errorMessage'];
        if ($errorMessage !== '') {
            http_response_code(503);
            echo $errorMessage;
            return;
        }

        $hospital = \config('hospitals.' . $hospitalCode, []);
        $report['hospital_code'] = strtoupper($hospitalCode);
        $report['hospital_name'] = is_array($hospital) ? (string)($hospital['name'] ?? '') : '';
        $filename = strtoupper($hospitalCode) . '_Daily_Revenue_' . date('Y-m-d') . '.xlsx';

        (new XlsxExportService())->streamFinalWorkbook($report, $filename);
    }

    private function canAccess(): bool
    {
        $user = Auth::user();
        return (int)($user['dashboard_role_revenue'] ?? 0) === 1;
    }

    /**
     * @return array{report: array<string,mixed>, errorMessage: string}
     */
    private function loadReport(string $hospitalCode): array
    {
        try {
            $rows = (new InpatientDailyRevenueRepository($hospitalCode))->currentInpatientsWithRevenue();
            return [
                'report' => (new InpatientDailyRevenueService())->build($rows),
                'errorMessage' => '',
            ];
        } catch (Throwable $e) {
            $errorMessage = current_lang() === 'ar'
                ? 'تعذر تحميل الإيراد اليومي في الوقت الحالي. يرجى المحاولة مرة أخرى بعد قليل.'
                : 'Daily inpatient revenue is temporarily unavailable. Please try again shortly.';
            error_log('[InpatientDailyRevenue] ' . $e->getMessage());

            return [
                'report' => (new InpatientDailyRevenueService())->build([]),
                'errorMessage' => $errorMessage,
            ];
        }
    }

    private function forbidden(): void
    {
        http_response_code(403);
        View::render('errors/403', [
            'title' => current_lang() === 'ar' ? 'غير مصرح بالدخول' : 'Access not available',
            'activePage' => '',
        ]);
    }
}
