<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Auth;
use App\Csrf;
use App\Pin;
use App\Repositories\Container;
use App\Session;

class HubController
{
    public function loginForm(): void
    {
        if (Auth::check()) { redirect('/hub'); }
        echo view('layouts.blank', [
            'content' => view('hub.login'),
            'title'   => t('hub.login.title'),
        ]);
    }

    public function login(): void
    {
        Csrf::requireValid();
        $username = trim((string)($_POST['username'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $user = Auth::attempt($username, $password);

        // Explicit redirect from 403 switch-account form
        $explicitRedirect = trim((string)($_POST['_redirect'] ?? ''));

        if (!$user) {
            $_SESSION['_flash']['error'] = t('hub.login.invalid');
            // If switching from 403, redirect back to that page so they see the error
            if ($explicitRedirect) {
                $_SESSION['after_login'] = $explicitRedirect;
            }
            redirect('/hub/login');
        }
        Auth::login($user);
        $next = $explicitRedirect ?: ($_SESSION['after_login'] ?? '/hub');
        unset($_SESSION['after_login']);
        redirect($next);
    }

    public function logout(): void
    {
        Auth::logout();
        Session::destroy();
        redirect('/hub/login');
    }

    public function setupPinForm(): void
    {
        $user = Auth::user();
        if (!$user) redirect('/hub/login');
        echo view('layouts.blank', [
            'content' => view('hub.setup-pin', ['user' => $user]),
            'title'   => t('hub.setup_pin.title'),
        ]);
    }

    public function setupPin(): void
    {
        Csrf::requireValid();
        $user = Auth::user();
        if (!$user) redirect('/hub/login');
        $pin = (string)($_POST['pin'] ?? '');
        $confirm = (string)($_POST['pin_confirm'] ?? '');
        if (!preg_match('/^\d{4,6}$/', $pin) || $pin !== $confirm) {
            $_SESSION['_flash']['error'] = t('hub.setup_pin.invalid');
            redirect('/hub/setup-pin');
        }
        Container::users()->save(array_merge($user, [
            'pin_hash' => Pin::hash($pin),
            'pin_set_at' => now_iso(),
        ]));
        Container::audit()->log($user['id'], 'SET_PIN', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('hub.setup_pin.success');
        redirect('/hub');
    }

    public function changePasswordForm(): void
    {
        $user = Auth::user();
        if (!$user) redirect('/hub/login');
        echo view('layouts.blank', [
            'content' => view('hub.change-password', ['user' => $user]),
            'title'   => t('hub.change_password.title'),
        ]);
    }

    public function changePassword(): void
    {
        Csrf::requireValid();
        $user = Auth::user();
        if (!$user) redirect('/hub/login');

        $newPw      = (string)($_POST['new_password'] ?? '');
        $confirmPw  = (string)($_POST['confirm_password'] ?? '');

        if (strlen($newPw) < 8) {
            $_SESSION['_flash']['error'] = t('hub.change_password.too_short');
            redirect('/hub/change-password');
        }
        if ($newPw !== $confirmPw) {
            $_SESSION['_flash']['error'] = t('hub.change_password.mismatch');
            redirect('/hub/change-password');
        }

        Container::users()->save(array_merge($user, [
            'password_hash'        => password_hash($newPw, PASSWORD_DEFAULT),
            'must_change_password' => false,
        ]));
        Container::audit()->log($user['id'], 'CHANGE_PASSWORD', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('hub.change_password.success');
        redirect('/hub');
    }

    public function dashboard(): void
    {
        // Auto-cancel past unconfirmed appointments (throttled, runs max once/hour)
        \App\Services\AppointmentCleanup::autoCancelExpired();

        $user = Auth::user();
        $appts = Container::appointments();
        $today = (new \DateTimeImmutable('today'))->format('Y-m-d');
        $todays = array_values(array_filter($appts->all(), function ($a) use ($today) {
            return isset($a['start_at']) && str_starts_with($a['start_at'], $today);
        }));
        $counts = [
            'PENDING'   => count($appts->byStatus('PENDING')),
            'APPROVED'  => count($appts->byStatus('APPROVED')),
            'COMPLETED' => count($appts->byStatus('COMPLETED')),
            'CANCELED'  => count($appts->byStatus('CANCELED')),
        ];
        render('hub', 'hub.dashboard', compact('user', 'todays', 'counts'), t('hub.dashboard.title'));
    }
}
