<?php
/**
 * Verify Login OTP Endpoint
 */

define('TONSUI_LOADED', true);
if (!defined('TONSUI_ALLOW_GUEST')) { define('TONSUI_ALLOW_GUEST', true); }

require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(200);
  exit;
}

function respond_json($ok, $message = '', $data = []) {
  $resp = ['success' => $ok];
  if ($message !== '') { $resp['message'] = $message; }
  foreach ($data as $k => $v) { $resp[$k] = $v; }
  echo json_encode($resp);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  header('Allow: POST');
  respond_json(false, 'Method not allowed');
}

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$code = isset($input['code']) ? trim((string)$input['code']) : '';

if ($code === '') {
  http_response_code(400);
  respond_json(false, 'OTP code is required');
}

$pending = $_SESSION['pending_login'] ?? null;
if (!$pending || !is_array($pending)) {
  http_response_code(400);
  respond_json(false, 'No pending login found');
}

if (time() > (int)($pending['expires'] ?? 0)) {
  unset($_SESSION['pending_login']);
  http_response_code(400);
  respond_json(false, 'OTP expired. Please login again.');
}

if ($code !== (string)($pending['otp'] ?? '')) {
  http_response_code(400);
  respond_json(false, 'Invalid OTP code.');
}

try {
  $stmt = $pdo->prepare('SELECT id, username, email, is_admin FROM users WHERE id = ? LIMIT 1');
  $stmt->execute([ (int)$pending['user_id'] ]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
  $user = null;
}

if (!$user) {
  unset($_SESSION['pending_login']);
  http_response_code(400);
  respond_json(false, 'User not found');
}

$_SESSION['user_id'] = (int)$user['id'];
$_SESSION['username'] = (string)$user['username'];
$_SESSION['email'] = (string)$user['email'];
$_SESSION['is_admin'] = !empty($user['is_admin']);
$_SESSION['logged_in'] = true;
$_SESSION['last_activity'] = time();

unset($_SESSION['pending_login']);
session_regenerate_id(true);

$userData = [
  'id' => (int)$user['id'],
  'username' => (string)$user['username'],
  'email' => (string)$user['email'],
  'is_admin' => !empty($user['is_admin'])
];

respond_json(true, 'Login verified', ['user' => $userData]);
