<?php

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

/**
 * =========================================
 * DEMOBANK OTP VERIFY ENDPOINT
 * =========================================
 */

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

// Get OTP from request (POST preferred)
$otp = $_POST['otp'] ?? $_GET['otp'] ?? null;

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

// Load OTP service
$otpService = new OTPService();

// Verify OTP
$result = $otpService->verifyOTP($user_id, $otp);

// Response
if ($result['status']) {

    /**
     * OPTIONAL:
     * Mark session flag for transfer approval
     */
    $_SESSION['otp_verified'] = true;

    echo json_encode([
        "status" => true,
        "message" => "OTP verified successfully"
    ]);

} else {

    echo json_encode([
        "status" => false,
        "message" => $result['message']
    ]);
}