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

// Secure input
$order_id_safe = mysqli_real_escape_string($ahk_conn, $order_id);

// Fetch order
$order = mysqli_fetch_assoc(mysqli_query($ahk_conn,
    "SELECT * FROM Learninghistory WHERE tnsid='$order_id_safe' LIMIT 1"));

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

// ================= API CALL =================
$api_key = "98ee590940cd832fb587502bff5c1b4172181a38a9a775a8a3261e82636f345a";
$api_url = "http://maxxapi.site/ll_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);

if($res === false){
    echo json_encode([
        'status'=>'500',
        'message'=>'Curl error: '.curl_error($ch)
    ]);
    exit;
}

curl_close($ch);

$response = json_decode($res, true);

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

// ================= STATUS MAP =================
$status_map = [
    'Pending' => 0,
    'Success' => 1,
    'Refund'  => 2
];

$new_status = $status_map[$response['order_status']] ?? 0;

// ================= UPDATE + REFUND =================
if($order['status'] != $new_status){

    mysqli_begin_transaction($ahk_conn);

    try {

        // 1. Update order status
        $update = mysqli_query($ahk_conn,
            "UPDATE Learninghistory SET status=$new_status WHERE tnsid='$order_id_safe'");

        if(!$update){
            throw new Exception("Status update failed");
        }

        // ================= REFUND LOGIC =================
        if($new_status == 2 && $order['status'] != 2){

            $username = $order['custno'];

            // Get user wallet
            $user = mysqli_fetch_assoc(mysqli_query($ahk_conn,
                "SELECT balance FROM users WHERE phone='$username'"));

            if(!$user){
                throw new Exception("User not found");
            }

            $current_balance = (float)$user['balance'];

            // Get fee (better: store in history table)
            $feeRow = mysqli_fetch_assoc(mysqli_query($ahk_conn,
                "SELECT rate FROM price WHERE service='ll_details'"));

            $fee = (float)($feeRow['rate'] ?? 0);

            $new_balance = $current_balance + $fee;

            // Update wallet
            $walletUpdate = mysqli_query($ahk_conn,
                "UPDATE users SET balance=$new_balance WHERE phone='$username'");

            if(!$walletUpdate){
                throw new Exception("Wallet update failed");
            }

            // Insert wallet history
            $purpose = "LL Refund $order_id";
            $type = "Credit";
            $status_flag = 1;

            $insertHistory = mysqli_query($ahk_conn,
                "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
                 VALUES ('$username', '$fee', '$new_balance', '$purpose', '$status_flag', '$type')");

            if(!$insertHistory){
                throw new Exception("Wallet history insert failed");
            }
        }

        mysqli_commit($ahk_conn);

    } catch (Exception $e) {

        mysqli_rollback($ahk_conn);

        echo json_encode([
            'status'=>'500',
            'message'=>$e->getMessage()
        ]);
        exit;
    }
}

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