<?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;
}

$transfer_id = $_POST['transfer_id'] ?? null;

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

$conn = db();

/**
 * =========================================
 * FETCH TRANSFER
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT * FROM transfers 
    WHERE id = ? AND user_id = ?
");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$transfer = $stmt->get_result()->fetch_assoc();

if (!$transfer) {
    echo json_encode([
        "status" => false,
        "message" => "Transfer not found"
    ]);
    exit;
}

/**
 * =========================================
 * CHECK STATUS
 * =========================================
 */
if ($transfer['status'] === 'completed') {
    echo json_encode([
        "status" => false,
        "message" => "Transfer already completed"
    ]);
    exit;
}

if ($transfer['status'] === 'cancelled') {
    echo json_encode([
        "status" => false,
        "message" => "Transfer was cancelled and cannot be resumed"
    ]);
    exit;
}

/**
 * =========================================
 * DETERMINE NEXT STEP
 * =========================================
 */
$next_step = "unknown";

switch ($transfer['status']) {

    case "pending":
        $next_step = "otp_verification";
        break;

    case "otp_verified":
        $next_step = "token_step_1";
        break;

    case "processing":
        $next_step = "token_verification";
        break;

    default:
        $next_step = "review_required";
        break;
}

/**
 * =========================================
 * RESPONSE
 * =========================================
 */
echo json_encode([
    "status" => true,
    "message" => "Transfer resumed successfully",
    "transfer_id" => $transfer_id,
    "current_status" => $transfer['status'],
    "next_step" => $next_step
]);