<?php

require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/session.php";

/**
 * =========================================
 * DEMOBANK TOKEN VALIDATOR (NO EXPIRY)
 * =========================================
 * Tokens do NOT expire anymore.
 * They remain valid until used.
 */

header('Content-Type: application/json');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check login
$user_id = $_SESSION['user_id'] ?? null;

if (!$user_id) {
    echo json_encode([
        "status" => false,
        "message" => "Unauthorized access"
    ]);
    exit;
}

// Inputs
$transfer_id = $_POST['transfer_id'] ?? null;
$token       = $_POST['token'] ?? null;
$step        = $_POST['step'] ?? null;

if (!$transfer_id || !$token || !$step) {
    echo json_encode([
        "status" => false,
        "message" => "Missing required fields"
    ]);
    exit;
}

$conn = db();

// Fetch token (NO expiry check)
$stmt = $conn->prepare("
    SELECT id, status 
    FROM transfer_tokens 
    WHERE user_id = ? 
      AND transfer_id = ? 
      AND token = ? 
      AND step = ?
    ORDER BY created_at DESC
    LIMIT 1
");

$stmt->bind_param("iisi", $user_id, $transfer_id, $token, $step);
$stmt->execute();
$record = $stmt->get_result()->fetch_assoc();

if (!$record) {
    echo json_encode([
        "status" => false,
        "message" => "Invalid token"
    ]);
    exit;
}

// Prevent reuse
if ($record['status'] !== 'pending') {
    echo json_encode([
        "status" => false,
        "message" => "Token already used"
    ]);
    exit;
}

// Mark as used
$stmt = $conn->prepare("UPDATE transfer_tokens SET status = 'used' WHERE id = ?");
$stmt->bind_param("i", $record['id']);
$stmt->execute();

// Mark session progress
$_SESSION['token_step_' . $step] = true;

echo json_encode([
    "status" => true,
    "message" => "Token validated successfully",
    "step" => $step
]);