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

$order_id = $_GET['order_id'] ?? '';

if (!$order_id) {
    echo json_encode(['status'=>'400','message'=>'order_id is required']);
    exit;
}

$order_id_safe = mysqli_real_escape_string($ahk_conn, $order_id);

$order = mysqli_fetch_assoc(mysqli_query($ahk_conn,
"SELECT * FROM mvcc WHERE order_id='$order_id_safe' LIMIT 1"));

if(!$order){
    echo json_encode(['status'=>'404','message'=>'Order not found']);
    exit;
}

$api_key = "98ee590940cd832fb587502bff5c1b4172181a38a9a775a8a3261e82636f345a";

$api_url = "http://maxxapi.site//mvcc_check_status?api_key={$api_key}&order_id={$order_id_safe}";

$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $api_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15
]);

$res = curl_exec($ch);
curl_close($ch);

$response = json_decode($res,true);

if(!$response || $response['status']!='200'){
echo json_encode(['status'=>'500','message'=>'API call failed']);
exit;
}

$new_status = 0;

if($response['order_status']=='Pending') $new_status = 0;
elseif($response['order_status']=='Processing') $new_status = 1;
elseif($response['order_status']=='Completed') $new_status = 2;

if($order['status'] != $new_status){
mysqli_query($ahk_conn,
"UPDATE mvcc SET status='$new_status' WHERE order_id='$order_id_safe'");
}

echo json_encode([
'status'=>'200',
'order_id'=>$order_id,
'order_status'=>$response['order_status']
]);
?>