<?php
session_start();
ob_start();

header('Content-Type: application/json');
require("../../includes/config.php"); 

$user_otp = $_POST['otp_code'] ?? '';

if (!isset($_SESSION['pending_otp']) || time() > $_SESSION['otp_expiry']) {
    echo json_encode(['status' => 'error', 'message' => 'OTP expired or session invalid.']);
    exit;
}

if ($user_otp === $_SESSION['pending_otp']) {
    // 1. Fetch the username from the database using the temp ID
    $admin_id = $_SESSION['temp_admin_id'];
    $stmt = $pdo->prepare("SELECT username FROM admin_account WHERE id = ? LIMIT 1");
    $stmt->execute([$admin_id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($admin) {
        // 2. PROMOTE to final session
        $_SESSION['admin_id'] = $admin_id;
        $_SESSION['admin_user'] = $admin['username']; // <--- SESSION CREATED HERE
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['last_activity'] = time(); // Initialize timeout timer

        // 3. CLEAN UP temp data
        unset($_SESSION['pending_otp']);
        unset($_SESSION['temp_admin_id']);
        unset($_SESSION['otp_expiry']);
        
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'User account no longer exists.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Incorrect OTP code.']);
}
?>