<?php
/**
 * User Log On Page
 *
 * Accepts the user's e-mail address (multi-user) and password (multi-user or single-user-with-password) and attempts
 * to log them on to Feed Reader Central
 *
 * @author Daniel J. Summers <daniel@bitbadger.solutions>
 * @license MIT
 */

declare(strict_types=1);

include '../../start.php';

use BitBadger\InspiredByFSharp\Option;
use FeedReaderCentral\{Key, Security};

Security::verifyUser(redirectIfAnonymous: false);

// Users already logged on have no need of this page
if (key_exists(Key::UserId, $_SESSION)) frc_redirect('/');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Security::logOnUser($_POST['email'] ?? '', $_POST['password'], Option::of($_POST['returnTo'] ?? null));
    // If we're still here, something didn't work; preserve the returnTo parameter
    $_GET['returnTo'] = $_POST['returnTo'];
}

$isSingle = SECURITY_MODEL === Security::SingleUserPasswordMode;

page_head('Log On'); ?>
<h1>Log On</h1>
<article>
    <form method=POST action=/user/log-on><?php
        if (($_GET['returnTo'] ?? '') !== '') { ?>
            <input type=hidden name=returnTo value="<?=$_GET['returnTo']?>"><?php
        }
        if (!$isSingle) { ?>
            <label>
                E-mail Address
                <input type=email name=email required autofocus>
            </label><?php
        } ?>
        <label>
            Password
            <input type=password name=password required<?=$isSingle ? ' autofocus' : ''?>>
        </label>
        <span class=break></span>
        <button type=submit>Log On</button>
    </form>
</article><?php
page_foot();