<?php

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

/**
 * =========================================
 * DEMOBANK TOKEN VALIDATOR
 * =========================================
 * Validates each progressive token step
 * and controls transfer progression.
 */

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

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

$user_id = $_SESSION['user_id'] ?? null;

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

// Input
$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 RECORD
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT * FROM transfer_tokens 
    WHERE transfer_id = ? 
    AND token = ? 
    AND user_id = ?
    ORDER BY created_at DESC 
    LIMIT 1
");

$stmt->bind_param("isi", $transfer_id, $token, $user_id);
$stmt->execute();

$result = $stmt->get_result();
$record = $result->fetch_assoc();

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

/**
 * =========================================
 * CHECK EXPIRY
 * =========================================
 */
if (strtotime($record['expires_at']) < time()) {
    // Mark expired
    $conn->query("UPDATE transfer_tokens SET status='expired' WHERE id=" . (int)$record['id']);

    echo json_encode([
        "status" => false,
        "message" => "Token expired"
    ]);
    exit;
}

/**
 * =========================================
 * CHECK STEP MATCH
 * =========================================
 */
if ((int)$record['step'] !== (int)$step) {
    echo json_encode([
        "status" => false,
        "message" => "Invalid token step"
    ]);
    exit;
}

/**
 * =========================================
 * CHECK IF ALREADY USED
 * =========================================
 */
if ($record['status'] === 'used') {
    echo json_encode([
        "status" => false,
        "message" => "Token already used"
    ]);
    exit;
}

/**
 * =========================================
 * STEP VALIDATION SUCCESS
 * =========================================
 */

// Get UI message
$messageData = getTokenMessage($step);

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

/**
 * OPTIONAL: Progress to next step logic
 * (handled by token_engine.php)
 */

echo json_encode([
    "status" => true,
    "message" => "Token validated successfully",
    "step" => $step,
    "ui" => [
        "title" => $messageData['title'],
        "message" => $messageData['message'],
        "duration" => $messageData['duration']
    ],
    "transfer_id" => $transfer_id
]);