<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\BranchReadiness;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Session;
use App\Core\View;

final class AuthController
{
    public function loginForm(): void
    {
        if (Auth::check()) {
            Session::save();
            \redirect('index.php?page=dashboard&lang=' . \current_lang());
        }

        View::render('auth/login', [
            'title' => \t('auth.title'),
            'error' => Session::flash('error'),
        ], null);
    }

    public function login(): void
    {
        if (!Csrf::validate((string) Request::post('_csrf', ''))) {
            Session::flash('error', \current_lang() === 'ar' ? 'انتهت صلاحية الجلسة، برجاء المحاولة مرة أخرى.' : 'Session expired. Please try again.');
            \redirect('index.php?page=login&lang=' . \current_lang());
        }

        $lang = \normalize_lang((string) Request::post('lang', \current_lang()));
        $_GET['lang'] = $lang;

        $username = trim((string) Request::post('username', ''));
        $password = (string) Request::post('password', '');

        // Login is intentionally fixed to the configured primary/default hospital.
        // Branch switching happens after successful authentication from the workspace.
        $hospital = \default_hospital();

        if ($username === '' || $password === '') {
            Session::flash('error', $lang === 'ar' ? 'برجاء إدخال اسم المستخدم وكلمة المرور.' : 'Please enter username and password.');
            \redirect('index.php?page=login&lang=' . $lang);
        }

        if (!Auth::attempt($username, $password, $hospital)) {
            Session::flash('error', $lang === 'ar' ? 'بيانات الدخول غير صحيحة أو لا توجد صلاحية Dashboard.' : 'Invalid credentials or no Dashboard permission.');
            \redirect('index.php?page=login&lang=' . $lang);
        }

        Session::save();
        \redirect('index.php?page=dashboard&lang=' . $lang);
    }

    public function switchHospital(): void
    {
        Auth::requireLogin();

        $lang = \normalize_lang((string) Request::post('lang', \current_lang()));
        $_GET['lang'] = $lang;

        if (!Csrf::validate((string) Request::post('_csrf', ''))) {
            Session::flash('error', $lang === 'ar' ? 'انتهت صلاحية الجلسة، برجاء المحاولة مرة أخرى.' : 'Session expired. Please try again.');
            \redirect('index.php?page=dashboard&lang=' . $lang);
        }

        $hospital = \normalize_hospital_code((string) Request::post('hospital', Auth::hospital()));
        if (!BranchReadiness::isConfigured($hospital)) {
            Session::flash(
                'error',
                $lang === 'ar' ? 'الفرع المحدد غير صحيح.' : 'Invalid branch selection.'
            );
        } elseif (!BranchReadiness::isLive($hospital)) {
            Session::flash(
                'error',
                $lang === 'ar'
                    ? 'هذا الفرع غير متاح حاليًا حتى اكتمال واعتماد جاهزيته.'
                    : 'This branch is not available until its readiness is completed and approved.'
            );
        } elseif (!Auth::setHospital($hospital)) {
            Session::flash(
                'error',
                $lang === 'ar' ? 'تعذر تغيير الفرع.' : 'The branch could not be changed.'
            );
        }

        Session::save();
        $redirectTo = (string) Request::post('redirect_to', 'index.php?page=dashboard&lang=' . $lang);
        if (strpos($redirectTo, 'index.php') !== 0) {
            $redirectTo = 'index.php?page=dashboard&lang=' . $lang;
        }
        \redirect($redirectTo);
    }

    public function logout(): void
    {
        Auth::logout();
        \redirect('index.php?page=login&lang=' . \current_lang());
    }
}
