<?php

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

/**
 * =========================================
 * DEMOBANK TOKEN GENERATOR (ADMIN USE)
 * =========================================
 * Generates secure step-based transfer tokens
 */

// Only admin allowed (basic check)
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die(json_encode([
        "status" => false,
        "message" => "Unauthorized access"
    ]));
}

// Get input
$user_id   = $_POST['user_id'] ?? null;
$transfer_id = $_POST['transfer_id'] ?? null;
$step      = $_POST['step'] ?? 1; // 1–6 steps
$reason    = $_POST['reason'] ?? 'Security verification required';

if (!$user_id || !$transfer_id) {
    die(json_encode([
        "status" => false,
        "message" => "Missing required fields"
    ]));
}

// Validate step (1–6 only)
if ($step < 1 || $step > 6) {
    die(json_encode([
        "status" => false,
        "message" => "Invalid token step"
    ]));
}

$conn = db();

// Generate secure token
$token = strtoupper(bin2hex(random_bytes(3))) . '-' . random_int(1000, 9999);

// Expiry (15 minutes per token stage)
$expires_at = date("Y-m-d H:i:s", strtotime("+15 minutes"));

/**
 * Insert token into database
 * Table required: transfer_tokens
 */
$stmt = $conn->prepare("
    INSERT INTO transfer_tokens 
    (user_id, transfer_id, token, step, reason, expires_at, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
");

$stmt->bind_param(
    "iissss",
    $user_id,
    $transfer_id,
    $token,
    $step,
    $reason,
    $expires_at
);

$success = $stmt->execute();

if ($success) {
    echo json_encode([
        "status" => true,
        "message" => "Token generated successfully",
        "token" => $token,
        "step" => $step,
        "expires_at" => $expires_at
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Failed to generate token"
    ]);
}