<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Session;
use App\Core\View;
use App\Repositories\InpatientDailyRevenueRuleSettingsRepository;
use Throwable;

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

        $hospitalCode = Auth::hospital();
        try {
            $repository = new InpatientDailyRevenueRuleSettingsRepository($hospitalCode);
            $rules = $repository->load();
            $errorMessage = '';
        } catch (Throwable $e) {
            $rules = [];
            $errorMessage = current_lang() === 'ar'
                ? 'تعذر تحميل إعدادات الإيراد اليومي في الوقت الحالي.'
                : 'Daily revenue settings are temporarily unavailable.';
            error_log('[InpatientDailyRevenueSettings] ' . $e->getMessage());
        }

        View::render('inpatient_daily_revenue/settings', [
            'title' => current_lang() === 'ar' ? 'إعدادات الإيراد اليومي' : 'Daily Revenue Settings',
            'activePage' => 'inpatient-daily-revenue-settings',
            'hospitalCode' => $hospitalCode,
            'hospital' => \config('hospitals.' . $hospitalCode, []),
            'rules' => $rules,
            'canEdit' => $this->canEdit(),
            'successMessage' => Session::flash('daily_revenue_settings_success'),
            'errorMessage' => Session::flash('daily_revenue_settings_error') ?: $errorMessage,
        ]);
    }

    public function save(): void
    {
        Auth::requireLogin();
        if (!$this->canEdit()) {
            $this->forbidden();
            return;
        }

        $lang = current_lang();
        if (!Csrf::validate((string)Request::post('_csrf', ''))) {
            Session::flash('daily_revenue_settings_error', $lang === 'ar'
                ? 'انتهت صلاحية الجلسة. برجاء إعادة المحاولة.'
                : 'Session expired. Please try again.');
            $this->redirectToSettings();
        }

        $input = Request::post('rules', []);
        if (!is_array($input)) {
            $input = [];
        }

        try {
            $repository = new InpatientDailyRevenueRuleSettingsRepository(Auth::hospital());
            $repository->save($input, Auth::name());
            Session::flash('daily_revenue_settings_success', $lang === 'ar'
                ? 'تم حفظ إعدادات الإيراد اليومي بنجاح.'
                : 'Daily revenue settings were saved successfully.');
        } catch (Throwable $e) {
            error_log('[InpatientDailyRevenueSettingsSave] ' . $e->getMessage());
            Session::flash('daily_revenue_settings_error', $lang === 'ar'
                ? 'لم يتم حفظ الإعدادات. برجاء مراجعة القيم المدخلة والمحاولة مرة أخرى.'
                : 'Settings were not saved. Please review the entered values and try again.');
        }

        $this->redirectToSettings();
    }

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

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

    private function redirectToSettings(): void
    {
        \redirect('index.php?page=inpatient-daily-revenue-settings&lang=' . current_lang());
    }

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