<?php
/**
 * x86.world customer portal — main page.
 *
 * Three states: sign in, expired notice, file listing.
 */

define('X86_PORTAL', 1);
require __DIR__ . '/portal_lib.php';

portal_session_start();

header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header("Content-Security-Policy: default-src 'none'; "
     . "style-src 'self' https://fonts.googleapis.com; "
     . "font-src https://fonts.gstatic.com; "
     . "script-src 'self'; "
     . "img-src 'self' data:; "
     . "connect-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'");

$error  = '';
$notice = '';
$self   = htmlspecialchars(basename($_SERVER['SCRIPT_NAME']), ENT_QUOTES, 'UTF-8');

/* ------------------------------------------------------------------ *
 * Flash messages handed over by download.php
 * ------------------------------------------------------------------ */
if (isset($_GET['e'])) {
    if ($_GET['e'] === 'notfound') {
        $error = 'That file is no longer in your directory. Refresh the list below.';
    } elseif ($_GET['e'] === 'expired') {
        $notice = 'Your access expired while you were downloading.';
    }
}

/* ------------------------------------------------------------------ *
 * POST actions
 * ------------------------------------------------------------------ */
$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action === 'logout') {
    if (portal_csrf_check(isset($_POST['csrf']) ? $_POST['csrf'] : '')) {
        portal_logout();
        header('Location: ' . $self . '?bye=1');
        exit;
    }
    $error = 'Your session token expired. Try again.';
}

if ($action === 'login' && !portal_logged_in()) {
    $email    = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $honeypot = isset($_POST['website']) ? trim($_POST['website']) : '';

    if (!portal_csrf_check(isset($_POST['csrf']) ? $_POST['csrf'] : '')) {
        /* Usually a stale tab rather than an attack — say something useful. */
        $error = 'This page had been open a while and its security token expired. Sign in again.';
    } elseif ($honeypot !== '') {
        /* Only a bot fills a field nobody can see. Costs it an attempt. */
        portal_throttle_fail($email);
        $error = 'Those details were not recognised.';
    } elseif ($email === '' || $password === '') {
        $error = 'Enter both your email address and your access key.';
    } else {
        $wait = portal_throttle_wait($email);
        if ($wait > 0) {
            $error = 'Too many failed attempts. Try again in ' . $wait . ' second'
                   . ($wait === 1 ? '' : 's') . '. If you have mislaid your details, '
                   . 'contact us and we will reissue them.';
        } else {
            $logins = portal_load_logins();
            $key    = strtolower($email);
            $rec    = isset($logins[$key]) ? $logins[$key] : null;

            /* Verify against a dummy hash for unknown addresses so that a wrong
               email costs the same time as a wrong password — no user enumeration. */
            $hash = $rec === null ? DUMMY_HASH : $rec['hash'];
            $ok   = password_verify($password, $hash);

            if ($ok && $rec !== null) {
                portal_throttle_clear($email);
                portal_login_session($rec);
                header('Location: ' . $self);
                exit;
            }
            portal_throttle_fail($email);
            $error = 'Those details were not recognised.';
        }
    }
}

if (isset($_GET['bye'])) {
    $notice = 'Signed out. Close the tab when you are done.';
}

/* ------------------------------------------------------------------ *
 * Work out what to render
 * ------------------------------------------------------------------ */
$record = portal_current_record();

if (portal_logged_in() && $record === null) {
    /* The account vanished from logins.txt mid-session. */
    portal_logout();
    $error = 'Your access has been withdrawn. Please get in touch if that is unexpected.';
}

$view = 'login';
if ($record !== null) {
    $view = portal_is_expired($record['expiry']) ? 'expired' : 'files';
}

$files    = array();
$daysLeft = null;
if ($view === 'files') {
    $files    = portal_list_files($record['site_id']);
    $daysLeft = portal_days_left($record['expiry']);
}

$csrf = portal_csrf_token();
?>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Customer Portal — x86.world</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600;700&family=Playfair+Display:wght@600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="portal.css">
</head>
<body>

<nav>
    <a class="nav-logo" href="<?php echo h(SITE_URL); ?>">x86<span>.world</span> / portal</a>
    <div class="nav-right">
        <?php if ($view === 'login'): ?>
            <a class="nav-help" href="<?php echo h(CONTACT_URL); ?>">Need help?</a>
        <?php else: ?>
            <span class="nav-context">Signed in as <strong><?php echo h($record['email']); ?></strong></span>
            <form method="post" action="<?php echo $self; ?>">
                <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
                <input type="hidden" name="action" value="logout">
                <button type="submit" class="nav-signout">Sign out</button>
            </form>
        <?php endif; ?>
    </div>
</nav>

<?php if ($view === 'login'): ?>
<main class="auth">
    <div class="auth-bg"></div>
    <div class="card auth-card">
        <div class="section-label">Secure delivery</div>
        <h1 class="card-title">Collect your files</h1>
        <p class="card-sub">Sign in with the email address and access key we sent you when your work was completed.</p>

        <?php if ($error !== ''): ?>
            <div class="msg msg-error"><?php echo h($error); ?></div>
        <?php elseif ($notice !== ''): ?>
            <div class="msg msg-info"><?php echo h($notice); ?></div>
        <?php endif; ?>

        <form method="post" action="<?php echo $self; ?>" autocomplete="on">
            <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
            <input type="hidden" name="action" value="login">

            <div class="field">
                <label for="email">Email address</label>
                <input type="email" id="email" name="email" autocomplete="username"
                       spellcheck="false" required autofocus
                       value="<?php echo isset($_POST['email']) ? h($_POST['email']) : ''; ?>">
            </div>

            <div class="field">
                <label for="password">Access key</label>
                <input type="password" id="password" name="password"
                       autocomplete="current-password" required
                       placeholder="three-words-like-this">
            </div>

            <!-- Bots fill this in; people never see it. -->
            <div class="hp" aria-hidden="true">
                <label for="website">Leave this empty</label>
                <input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
            </div>

            <button type="submit" class="btn">Sign in</button>
        </form>

        <p class="card-foot">
            Mislaid your details? We do not reset them automatically &mdash;
            <a href="<?php echo h(CONTACT_URL); ?>">get in touch</a> and we will
            reissue your access key.
        </p>
    </div>
</main>

<?php elseif ($view === 'expired'): ?>
<main class="container">
    <div class="expired-panel">
        <div class="section-label">Access expired</div>
        <h1>Your download window has closed</h1>

        <span class="expired-detail">Access ran until <?php echo h($record['expiry']); ?></span>

        <p>
            Your files have not been deleted. We hold completed work for a good
            while after delivery &mdash; the download link is simply closed once
            the agreed window ends.
        </p>
        <p>
            Drop us a line and we will reopen your access, usually the same day.
            Quote <strong><?php echo h($record['email']); ?></strong> and we will
            not need anything else.
        </p>

        <div class="expired-actions">
            <a class="btn btn-ghost" href="<?php echo h(CONTACT_URL); ?>">Contact us</a>
            <a class="btn btn-ghost" href="mailto:<?php echo h(CONTACT_EMAIL); ?>"><?php echo h(CONTACT_EMAIL); ?></a>
        </div>
    </div>
</main>

<?php else: ?>
<main class="container">
    <div class="section-label">Your delivery</div>
    <h1 class="page-title">Files ready to download</h1>
    <p class="page-sub">Everything below was produced from your media. Check the SHA-256 against your own copy once the transfer finishes.</p>

    <?php if ($error !== ''): ?>
        <div class="msg msg-error"><?php echo h($error); ?></div>
    <?php elseif ($notice !== ''): ?>
        <div class="msg msg-info"><?php echo h($notice); ?></div>
    <?php endif; ?>

    <?php if ($daysLeft !== null && $daysLeft <= 7): ?>
        <div class="msg msg-warn">
            <?php
            if ($daysLeft === 0) {
                echo 'Today is the last day of your access window.';
            } elseif ($daysLeft === 1) {
                echo 'Your access window ends tomorrow.';
            } else {
                echo 'Your access window ends in ' . (int)$daysLeft . ' days.';
            }
            ?>
            Download what you need, or <a href="<?php echo h(CONTACT_URL); ?>">ask us to extend it</a>.
        </div>
    <?php endif; ?>

    <div class="stats">
        <div class="stat">
            <span class="stat-value"><?php echo count($files); ?></span>
            <span class="stat-label">File<?php echo count($files) === 1 ? '' : 's'; ?> ready</span>
        </div>
        <div class="stat">
            <span class="stat-value"><?php echo h(portal_human_size(portal_total_size($files))); ?></span>
            <span class="stat-label">Total size</span>
        </div>
        <div class="stat">
            <span class="stat-value<?php echo ($daysLeft !== null && $daysLeft <= 7) ? ' warn' : ''; ?>">
                <?php echo $daysLeft === null ? 'Open' : h($record['expiry']); ?>
            </span>
            <span class="stat-label">
                <?php echo $daysLeft === null ? 'No expiry set' : h(portal_expiry_phrase($daysLeft)); ?>
            </span>
        </div>
    </div>

    <?php if (count($files) === 0): ?>
        <div class="empty">
            <h2>Nothing here yet</h2>
            <p>Your files will appear on this page as soon as the work is finished.
               We will email you when they do &mdash; no need to keep checking.</p>
        </div>
    <?php else: ?>
        <table class="files">
            <thead>
                <tr>
                    <th>File</th>
                    <th class="num">Size</th>
                    <th class="num">Added</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($files as $f): ?>
                <tr>
                    <td>
                        <a class="file-name" href="download.php?f=<?php echo rawurlencode($f['name']); ?>"
                           download><?php echo h($f['name']); ?></a>
                        <div><span class="chip"><?php echo h($f['kind']); ?></span></div>
                        <?php if ($f['hash'] !== null): ?>
                        <div class="hashrow">
                            <span class="hash"><em>sha256</em> <?php echo h($f['hash']); ?></span>
                            <button type="button" class="copy" data-hash="<?php echo h($f['hash']); ?>">Copy</button>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td class="num" data-label="Size"><?php echo h(portal_human_size($f['size'])); ?></td>
                    <td class="num" data-label="Added"><?php echo h(date('d M Y', $f['mtime'])); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="tools">
            <a href="download.php?sums=1">Download SHA256SUMS manifest</a>
            <span>Verify with <code>sha256sum -c SHA256SUMS</code> on Linux or macOS,
                  or <code>certutil -hashfile &lt;file&gt; SHA256</code> on Windows.</span>
        </div>
    <?php endif; ?>
</main>
<?php endif; ?>

<footer>
    <span class="footer-logo">x86<span>.world</span></span>
    <ul class="footer-links">
        <li><a href="<?php echo h(SITE_URL); ?>">Main site</a></li>
        <li><a href="<?php echo h(CONTACT_URL); ?>">Contact</a></li>
    </ul>
    <span class="footer-copy">&copy; <?php echo date('Y'); ?> x86.world &middot; Real hardware. Real preservation.</span>
</footer>

<script src="portal.js"></script>
</body>
</html>
