<?php
require_once('../database/config.php');
header('Content-Type: application/json');
error_reporting(0);
ini_set('display_errors', 0);
ob_start();
session_start();

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

$username = $_SESSION['username'];
$stmt = $conn->prepare("SELECT usertype FROM loginusers WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

if (!$user || $user['usertype'] != 'mainadmin') {
    echo json_encode(['status' => 'error', 'message' => 'Permission Denied']);
    exit;
}

if (!isset($_POST['orderid']) || !isset($_POST['status'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Parameters']);
    exit;
}

$orderid = $_POST['orderid'];
$status = $_POST['status']; // 'SUCCESS' or 'FAILED'

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

if (!$order) {
    echo json_encode(['status' => 'error', 'message' => 'Order Not Found']);
    exit;
}

// Update Status
$update = $conn->prepare("UPDATE create_orders SET txn_status = ?, transactions_id = COALESCE(NULLIF(transactions_id, ''), NULLIF(api_txn_id, ''), ?) WHERE orderid = ?");
$manual_id = strtoupper(substr(md5($orderid . time()), 0, 12));
if ($update->execute([$status, $manual_id, $orderid])) {
    
    // If Success, Trigger Callback Logic (Simplified)
    if ($status == 'SUCCESS') {
        // Send Callback
        // We can reuse or include the existing callback logic if available, 
        // or just rely on the cron/callback worker.
        // For now, let's just mark it as success. The merchant should have a callback mechanism.
        
        // Try to trigger callback if URL exists
        $user_query = $conn->prepare("SELECT callback_url FROM loginusers WHERE username = ?");
        $user_query->execute([$order['user']]);
        $u_data = $user_query->fetch();
        
        if ($u_data && !empty($u_data['callback_url'])) {
             $callbackFile = __DIR__ . '/send_callback.php';
             if (file_exists($callbackFile)) {
                 require_once($callbackFile);
                 if (function_exists('sendCallback')) {
                     sendCallback($conn, $orderid, $status);
                 }
             }
        }
        
        // Update Upi Pool Status if it was Bank UPI
        $merchant_name = $order['merchant_name'] ?? '';
        if (stripos($merchant_name, 'Bank UPI') !== false) {
             require_once('../database/UpiPoolManager.php');
             if (class_exists('UpiPoolManager')) {
                 $upiManager = new UpiPoolManager($conn);
                 $upiManager->updateTransactionStatus($orderid, 'success');
             }
        }
    }

    ob_clean();
    echo json_encode(['status' => 'success', 'message' => 'Transaction Updated Successfully']);
} else {
    ob_clean();
    echo json_encode(['status' => 'error', 'message' => 'Database Update Failed']);
}
?>
