<?php
class AuthController extends Controller
{
    public function showLogin(Request $request): void
    {
        $this->view('auth/login', [
            'title' => lang('auth.login'),
        ], 'auth');
    }

    public function login(Request $request): void
    {
        // CSRF check
        if (!CSRF::validate($request->csrfToken())) {
            if ($request->isAjax()) {
                $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
                return;
            }
            $this->redirect('/login', ['errors' => ['Invalid security token']]);
            return;
        }

        $username = trim($request->post('username', ''));
        $password = $request->post('password', '');

        if (empty($username) || empty($password)) {
            if ($request->isAjax()) {
                $this->json(['success' => false, 'message' => 'Username and password are required'], 422);
                return;
            }
            $this->redirect('/login', ['errors' => ['Username and password are required'], 'old' => ['username' => $username]]);
            return;
        }

        $result = Auth::login($username, $password, $request);

        if ($result['success']) {
            $redirectTo = Session::getFlash('redirect_after_login') ?? '/dashboard';
            if ($request->isAjax()) {
                $this->json(['success' => true, 'redirect' => $redirectTo]);
                return;
            }
            $this->redirect($redirectTo);
        } else {
            if ($request->isAjax()) {
                $this->json(['success' => false, 'message' => $result['message']], 401);
                return;
            }
            Session::flash('error', $result['message']);
            Session::flash('old', ['username' => $username]);
            $this->redirect('/login');
        }
    }

    public function logout(Request $request): void
    {
        Auth::logout($request);
        Response::redirect('/login');
    }
}