<?php
include('../includes/session.php');
include('../includes/config.php');
checkGatewayStatus();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status'=>'error','message'=>'Invalid request']);
    exit;
}

$amount = $_POST['amount'] ?? '';
$minAmt = XyZ_val('balance_add_minumum_amount');

if (!$amount || !is_numeric($amount) || $amount <= $minAmt){
    echo json_encode([
        'status'=>'error',
        'message'=>"Minimum amount is ₹".($minAmt+1)
    ]);
    exit;
}

$url = "https://".JkL_get('paymentapi','gateway_Url')
     ."/qr_verification?amount=".urlencode($amount)
     ."&apikey=".urlencode(JkL_get('paymentapi','gateway_apikey'));

/* ===== DIRECT CURL ===== */
$ch = curl_init();
curl_setopt_array($ch,[
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode([
        'status'=>'error',
        'message'=>'Network Error: '.curl_error($ch)
    ]);
    curl_close($ch);
    exit;
}
curl_close($ch);

$data = json_decode($response,true);

/* ===== API ERROR HANDLING ===== */
if (!$data) {
    echo json_encode([
        'status'=>'error',
        'message'=>'Invalid API response'
    ]);
    exit;
}

if (isset($data['error'])) {
    echo json_encode([
        'status'=>'error',
        'message'=>$data['error']
    ]);
    exit;
}

if (!isset($data['Message']) || $data['Message'] !== 'Success') {
    echo json_encode([
        'status'=>'error',
        'message'=> $data['message'] ?? 'QR generation failed'
    ]);
    exit;
}

/* ===== SUCCESS ===== */
$_SESSION['qr_data'] = $data;
$_SESSION['qr_amount'] = $amount;
$_SESSION['qr_generated_time'] = time();

echo json_encode(['status'=>'success']);
exit;
?>
