<?php

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

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;

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

$conn = db();

/**
 * =========================================
 * GET CURRENT STEP
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT COALESCE(MAX(step), 0) as current_step
    FROM transfer_tokens
    WHERE transfer_id = ? AND user_id = ? AND status = 'used'
");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$res = $stmt->get_result()->fetch_assoc();

$current_step = intval($res['current_step'] ?? 0);
$next_step = $current_step + 1;

if ($next_step > 6) {
    echo json_encode([
        "status" => false,
        "message" => "All token steps completed"
    ]);
    exit;
}

/**
 * =========================================
 * FIND TOKEN FOR NEXT STEP
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT * 
    FROM transfer_tokens
    WHERE transfer_id = ?
      AND user_id = ?
      AND step = ?
      AND token = ?
      AND status = 'pending'
");
$stmt->bind_param("iiis", $transfer_id, $user_id, $next_step, $token);
$stmt->execute();
$record = $stmt->get_result()->fetch_assoc();

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

/**
 * =========================================
 * MARK TOKEN AS USED
 * =========================================
 */
$stmt = $conn->prepare("
    UPDATE transfer_tokens
    SET status = 'used', used_at = NOW()
    WHERE id = ?
");
$stmt->bind_param("i", $record['id']);
$stmt->execute();

/**
 * =========================================
 * UPDATE TRANSFER STATUS
 * =========================================
 */
$new_status = ($next_step == 6) ? "processing" : "processing";

$stmt = $conn->prepare("
    UPDATE transfers
    SET status = ?
    WHERE id = ? AND user_id = ?
");
$stmt->bind_param("sii", $new_status, $transfer_id, $user_id);
$stmt->execute();

/**
 * =========================================
 * RESPONSE
 * =========================================
 */
echo json_encode([
    "status" => true,
    "message" => "Step {$next_step} completed successfully",
    "current_step" => $next_step,
    "next_step" => ($next_step < 6) ? $next_step + 1 : "final_process",
    "transfer_status" => $new_status
]);