<?php
// Aggressive Logging payment.php
require_once 'config.php';

// Log EVERYTHING that comes to this script
$raw_input = file_get_contents('php://input');
$log_entry = "[" . date('Y-m-d H:i:s') . "] CONNECTION FROM: " . $_SERVER['REMOTE_ADDR'] . " | BODY: " . $raw_input . "\n";
file_put_contents(__DIR__ . '/debug.log', $log_entry, FILE_APPEND);

$data = json_decode($raw_input, true);
$amount = (float)($data['amount'] ?? 0);
$utr = $data['utr'] ?? null;
$user_id = $data['user_id'] ?? null;

if (!$amount || !$utr || !$user_id) {
    file_put_contents(__DIR__ . '/debug.log', "   -> ERROR: Invalid Data\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
    exit;
}

// 1. Check for Duplicate UTR
$check_utr = supabase_request('GET', 'transactions?utr=eq.' . $utr);
if ($check_utr['status'] == 200 && !empty($check_utr['data'])) {
    file_put_contents(__DIR__ . '/debug.log', "   -> ERROR: Duplicate UTR\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'Duplicate UTR']);
    exit;
}

// 2. Find Latest Pending Order for this amount
$order_res = supabase_request('GET', 'transactions?status=eq.pending&amount=eq.' . $amount . '&order=created_at.desc&limit=1');

if ($order_res['status'] == 200 && !empty($order_res['data'])) {
    $order = $order_res['data'][0];
    
    // 3. Update Transaction to Completed
    supabase_request('PATCH', 'transactions?id=eq.' . $order['id'], [
        'status' => 'completed',
        'utr' => $utr
    ]);

    // 4. Update User Balance (System default user)
    $user_res = supabase_request('GET', 'users?id=eq.' . $user_id);
    if (!empty($user_res['data'])) {
        $new_balance = (float)$user_res['data'][0]['wallet_balance'] + $amount;
        supabase_request('PATCH', 'users?id=eq.' . $user_id, ['wallet_balance' => $new_balance]);
        file_put_contents(__DIR__ . '/debug.log', "   -> SUCCESS: Order {$order['order_id']} Completed!\n", FILE_APPEND);
    }

    // 5. Update Merchant Balance & Trigger Callback
    if (!empty($order['merchant_id'])) {
        $merchant_res = supabase_request('GET', 'merchants?id=eq.' . $order['merchant_id']);
        if (!empty($merchant_res['data'])) {
            $merchant = $merchant_res['data'][0];
            
            // Increment Merchant Balance
            $new_m_balance = (float)($merchant['balance'] ?? 0) + $amount;
            supabase_request('PATCH', 'merchants?id=eq.' . $merchant['id'], ['balance' => $new_m_balance]);
            
            $callback_url = $merchant['callback_url'];
            if (!empty($callback_url)) {
                $callback_payload = json_encode([
                    "code" => "SUCCESS",
                    "data" => [
                        "status" => "COMPLETED",
                        "order_id" => $order['order_id'],
                        "amount" => $amount,
                        "utr" => $utr,
                        "id" => $order['id']
                    ]
                ]);

                $ch = curl_init($callback_url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $callback_payload);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                $callback_result = curl_exec($ch);
                curl_close($ch);

                file_put_contents(__DIR__ . '/debug.log', "   -> MERCHANT BALANCE UPDATED (+₹$amount) & CALLBACK SENT TO {$merchant['business_name']}\n", FILE_APPEND);
            }
        }
    }

    echo json_encode(['status' => 'success', 'message' => 'Payment processed']);
} else {
    file_put_contents(__DIR__ . '/debug.log', "   -> ERROR: No Pending Order for Amount $amount\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'No matching order']);
}
?>
