<?php
/**
 * i-doit
 *
 * Password reset entry point.
 *
 * @package    i-doit
 * @subpackage General
 * @copyright  synetics GmbH
 * @license    http://www.i-doit.com/license
 */

use idoit\Module\UserSettings\Controller\PasswordResetController;
use Symfony\Component\HttpFoundation\Request;

try {
    $wwwPath = isys_application::instance()->www_path;
    /** @var isys_component_session $session */
    $session = isys_application::instance()->container->get('session');
    $passwordReset = isys_application::instance()->container->get('reset_password');

    $isPasswordRequestEndpoint = str_starts_with($_SERVER['REQUEST_URI'], "{$wwwPath}forgot-password");
    $isPasswordSetEndpoint = str_starts_with($_SERVER['REQUEST_URI'], "{$wwwPath}reset-password");

    if ($passwordReset->isActive()) {
        // Include the 'init.php' for the autoloader.
        include dirname(__DIR__) . '/init.php';

        $request = Request::createFromGlobals();
        if ($session->is_logged_in() && ($isPasswordRequestEndpoint || $isPasswordSetEndpoint)) {
            (new PasswordResetController())->showSessionActiveError($request)
                ->send();
            die;
        }

        if ($isPasswordRequestEndpoint) {
            if ($request->getMethod() === 'GET') {
                (new PasswordResetController())->resetPasswordScreen($request)
                    ->send();
            } else {
                (new PasswordResetController())->sendResetPasswordRequest($request)
                    ->send();
            }
            die;
        }

        if ($isPasswordSetEndpoint) {
            if ($request->getMethod() === 'GET') {
                (new PasswordResetController())->setNewPasswordScreen($request)
                    ->send();
            } else {
                (new PasswordResetController())->setNewPassword($request)
                    ->send();
            }
            die;
        }
    }
} catch (\Throwable $e) {
    try {
        (new PasswordResetController())->showError(new Request(), $e)
            ->send();
        die;
    } catch (isys_exception $e) {
        $e->write_log();
    } catch (Throwable $e) {
        // Do nothing, will fall back to the defaul login screen.
    }
}
