<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

if (!store_is_open()) { require __DIR__ . '/coming-soon.php'; exit; }

if (current_customer()) redirect('/account');

$method = in_array($_GET['method'] ?? '', ['password', 'key']) ? $_GET['method'] : 'password';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $posted_method = $_POST['method'] ?? 'password';

    if ($posted_method === 'key') {
        // ---- Keyfile login ----
        if (rate_limit('login_key', 10, 600)) {
            $errors['key'] = 'Too many attempts. Please wait a few minutes.';
        }

        $raw_key = '';

        if (!$errors && !empty($_FILES['keyfile']['tmp_name'])) {
            if ($_FILES['keyfile']['size'] > 8192) {
                $errors['key'] = 'Invalid keyfile.';
            } else {
                $content = @file_get_contents($_FILES['keyfile']['tmp_name']);
                $raw_key = $content !== false ? parse_login_key($content) : '';
            }
        }

        // Fallback: pasted key text
        if (!$errors && $raw_key === '') {
            $pasted  = trim($_POST['keytext'] ?? '');
            $raw_key = $pasted !== '' ? parse_login_key($pasted) : '';
        }

        if (!$errors && $raw_key === '') {
            $errors['key'] = 'No valid keyfile or key provided.';
        }

        if (!$errors) {
            $key_hash = hash('sha256', $raw_key);
            $s = $pdo->prepare('SELECT * FROM customers WHERE login_key_hash=? AND active=1');
            $s->execute([$key_hash]);
            $cust = $s->fetch();
            if ($cust) {
                session_regenerate_id(true);
                $_SESSION['customer_id'] = $cust['id'];
                if (!empty($_POST['remember'])) remember_me_set($cust['id']);
                $pdo->prepare('UPDATE customers SET last_login=NOW() WHERE id=?')->execute([$cust['id']]);
                redirect('/account');
            }
            $errors['key'] = 'Key not recognised or account disabled.';
        }

        $method = 'key';

    } else {
        // ---- Username + password login ----
        if (rate_limit('login', 8, 600)) {
            $errors['username'] = 'Too many attempts. Please wait a few minutes.';
        }

        $username = trim($_POST['username'] ?? '');
        $pass     = $_POST['password'] ?? '';

        if (!$errors && $username === '') $errors['username'] = 'Username required.';
        if (!$errors && $pass === '')     $errors['password'] = 'Password required.';

        if (!$errors) {
            $s = $pdo->prepare('SELECT * FROM customers WHERE username=? AND active=1');
            $s->execute([strtolower($username)]);
            $cust = $s->fetch();
            if ($cust && password_verify($pass, $cust['password_hash'])) {
                session_regenerate_id(true);
                $_SESSION['customer_id'] = $cust['id'];
                if (!empty($_POST['remember'])) remember_me_set($cust['id']);
                $pdo->prepare('UPDATE customers SET last_login=NOW() WHERE id=?')->execute([$cust['id']]);
                redirect('/account');
            }
            $errors['username'] = 'Invalid username or password.';
        }

        $method = 'password';
    }
}

$page_title = 'Sign in';
require __DIR__ . '/includes/header.php';
?>

<div id="page-body">
<main class="content" id="main-content" style="max-width:420px;">

<h2 class="page-heading">Sign in</h2>

<div style="display:flex; gap:0; margin-bottom:18px; border:1px solid #ccc;">
    <a href="/login/password" style="flex:1; text-align:center; padding:7px 0; font-size:1.1em; text-decoration:none;<?= $method !== 'key' ? ' background:#333; color:#fff; font-weight:bold;' : ' background:#f5f5f0; color:#333;' ?>">Username &amp; password</a>
    <a href="/login/key" style="flex:1; text-align:center; padding:7px 0; font-size:1.1em; text-decoration:none;<?= $method === 'key' ? ' background:#333; color:#fff; font-weight:bold;' : ' background:#f5f5f0; color:#333;' ?>">&#128273; Login keyfile</a>
</div>

<?php if ($method === 'key'): ?>

<form method="post" action="/login/key" enctype="multipart/form-data">
  <?= csrf_field() ?>
    <input type="hidden" name="method" value="key">
    <?php if (isset($errors['key'])): ?><div class="flash-err" style="margin-bottom:12px;"><?= esc($errors['key']) ?></div><?php endif; ?>
    <div class="form-row">
        <label>Upload keyfile <span class="muted" style="font-weight:normal;">(.key file from registration)</span></label>
        <input type="file" name="keyfile" accept=".key,.txt,text/plain" style="font-size:12px;">
    </div>
    <div class="form-row" style="margin-top:4px;">
        <label>Or paste key <span class="muted" style="font-weight:normal;">(64-character hex)</span></label>
        <textarea name="keytext" rows="2" style="width:100%; padding:5px 7px; border:1px solid #bbb; font-size:11px; font-family:monospace; resize:vertical;" placeholder="Paste the NXTGN_LOGIN_KEY= value or the full key file contents here"></textarea>
    </div>
    <div class="form-row" style="display:flex; align-items:center; gap:7px; margin-top:0;">
        <input type="checkbox" name="remember" id="rmb-key" value="1">
        <label for="rmb-key" style="font-weight:normal; cursor:pointer; margin:0;">Stay signed in for 30 days</label>
    </div>
    <button type="submit" class="btn btn-primary" style="margin-top:4px;">Sign in with keyfile</button>
</form>

<?php else: ?>

<form method="post" action="/login">
  <?= csrf_field() ?>
    <input type="hidden" name="method" value="password">
    <div class="form-row">
        <label>Username</label>
        <input type="text" name="username" value="<?= esc($_POST['username'] ?? '') ?>" autocomplete="username" autofocus>
        <?php if (isset($errors['username'])): ?><div class="form-error"><?= esc($errors['username']) ?></div><?php endif; ?>
    </div>
    <div class="form-row">
        <label>Password</label>
        <input type="password" name="password" autocomplete="current-password">
        <?php if (isset($errors['password'])): ?><div class="form-error"><?= esc($errors['password']) ?></div><?php endif; ?>
    </div>
    <div class="form-row" style="display:flex; align-items:center; gap:7px; margin-top:0;">
        <input type="checkbox" name="remember" id="rmb" value="1">
      <label for="rmb" style="font-weight:normal; cursor:pointer; margin:0;">Stay signed in for 30 days</label>
    </div>
    <button type="submit" class="btn btn-primary">Sign in</button>
    <span style="margin-left:10px; font-size:1.1em;"><a href="/register">Create account</a></span>
    <div style="margin-top:10px; font-size:1.1em;"><a href="/forgot-password">Forgot password?</a></div>
</form>

<?php endif; ?>

</main>
</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
