<?php
require_once __DIR__ . '/_super_admin_common.php';

$body = sa_require_post_json();
$cfg = sa_load_super_admin_cfg();
sa_session_start_secure($cfg);

$wait = sa_is_login_temporarily_blocked();
if ($wait > 0) {
    sa_json_response(429, ['status' => 'error', 'message' => 'Too many failed attempts. Try again in ' . $wait . 's.']);
}

$email = strtolower(trim((string)($body['email'] ?? '')));
$password = (string)($body['password'] ?? '');
$expectedEmail = strtolower(trim((string)($cfg['hardcoded_admin_email'] ?? '')));
$expectedHash = (string)($cfg['hardcoded_admin_password_hash'] ?? '');
// Prefer password_hash() only; hardcoded_admin_password_plain is legacy and should not be used in production.
$expectedPlain = (string)($cfg['hardcoded_admin_password_plain'] ?? '');

if ($email === '' || $password === '') {
    sa_json_response(400, ['status' => 'error', 'message' => 'Email and password are required']);
}

$okHash = ($expectedHash !== '') && password_verify($password, $expectedHash);
$okPlain = ($expectedPlain !== '') && hash_equals($expectedPlain, $password);
$ok = ($email === $expectedEmail) && ($okHash || $okPlain);
if (!$ok) {
    sa_record_failed_login_attempt();
    sa_json_response(401, ['status' => 'error', 'message' => 'Invalid credentials']);
}

sa_clear_failed_login_attempts();
session_regenerate_id(true);
$_SESSION['is_super_admin'] = true;
$_SESSION['super_admin_email'] = $expectedEmail;
$_SESSION['super_admin_uid'] = 'hardcoded-admin';
$_SESSION['super_admin_login_at'] = time();
$_SESSION['super_admin_last_seen'] = time();

sa_json_response(200, [
    'status' => 'success',
    'message' => 'Login successful',
    'email' => $expectedEmail
]);
