<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once('../../database/config.php');

$encodedData = $_POST['data'] ?? '';

if (empty($encodedData)) {
    echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Data missing']);
    exit;
}

$decodedData = base64_decode($encodedData);
if ($decodedData === false) {
    echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Decode failed']);
    exit;
}

parse_str($decodedData, $params);
$orderid = $params['orderid'] ?? '';

if (empty($orderid)) {
    echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Order ID missing']);
    exit;
}

$stmt = $conn->prepare("SELECT txn_status, transactions_id, amount, utr_number FROM create_orders WHERE orderid = ?");
$stmt->execute([$orderid]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if ($order) {
    if ($order['txn_status'] === 'SUCCESS') {
        echo json_encode([
            'status_code' => 200,
            'status' => 'Success',
            'message' => 'Transaction Successful',
            'data' => [
                'txn_id' => $order['transactions_id'],
                'txn_status' => 'SUCCESS',
                'amount' => $order['amount'],
                'utr' => $order['utr_number']
            ]
        ]);
    } else {
        echo json_encode([
            'status_code' => 202,
            'status' => 'Pending',
            'message' => 'Waiting for payment'
        ]);
    }
} else {
    echo json_encode(['status_code' => 404, 'status' => 'Error', 'message' => 'Order not found']);
}
?>
