<?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;
$otp         = $_POST['otp'] ?? null;

if (!$transfer_id || !$otp) {
    echo json_encode([
        "status" => false,
        "message" => "Transfer ID and OTP are 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 OTP RECORD
 * (assumes otp table exists)
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT * 
    FROM transfer_otp
    WHERE transfer_id = ?
      AND user_id = ?
      AND otp = ?
      AND status = 'pending'
    ORDER BY id DESC
    LIMIT 1
");
$stmt->bind_param("iis", $transfer_id, $user_id, $otp);
$stmt->execute();
$otpRecord = $stmt->get_result()->fetch_assoc();

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

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

/**
 * =========================================
 * UPDATE TRANSFER STATUS
 * =========================================
 */
$stmt = $conn->prepare("
    UPDATE transfers
    SET status = 'otp_verified', updated_at = NOW()
    WHERE id = ? AND user_id = ?
");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();

/**
 * =========================================
 * RESPONSE
 * =========================================
 */
echo json_encode([
    "status" => true,
    "message" => "OTP verified successfully",
    "transfer_id" => $transfer_id,
    "next_step" => "token_step_1",
    "status_updated" => "otp_verified"
]);