<?php
// Function to send callback to merchant
function sendCallback($conn, $orderid, $status) {
    // Log file path for debug
    $logFile = __DIR__ . '/callback_debug.log';
    
    try {
        // Fetch order details
        $stmt = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
        $stmt->execute([$orderid]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - Order not found: $orderid\n", FILE_APPEND);
            return false;
        }

        // Fetch user callback url
        $stmtUser = $conn->prepare("SELECT callback_url FROM loginusers WHERE username = ?");
        $stmtUser->execute([$order['user']]);
        $userRow = $stmtUser->fetch(PDO::FETCH_ASSOC);

        if ($userRow && !empty($userRow['callback_url'])) {
            $callback_url = $userRow['callback_url'];
            
            // Prepare callback data
            $data = [
                'user' => $order['user'],
                'status' => $status,
                'txn_status' => $status, // Alias for compatibility
                'orderid' => $order['orderid'],
                'amount' => $order['amount'],
                'txn_id' => $order['transactions_id'],
                'transactions_id' => $order['transactions_id'], // Alias for compatibility
                'utr_number' => $order['utr_number'],
                'received_from' => $order['received_from'],
                'date' => $order['date'],
                'created_at' => $order['created_at'],
                'timestamp' => time()
            ];

            // Send cURL request
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $callback_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err = curl_error($ch);
            curl_close($ch);
            
            // Log to file
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - Callback sent for $orderid to $callback_url. Response: $http_code\n", FILE_APPEND);

            // Log to database if table exists
            try {
                $checkTable = $conn->query("SHOW TABLES LIKE 'callback_logs'");
                if ($checkTable->rowCount() > 0) {
                    $logStmt = $conn->prepare("INSERT INTO callback_logs 
                        (order_id, user_name, callback_url, amount, txn_status, utr_number, api_txn_id, received_from, sent_data, response, http_code, status, error_message) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    
                    $logStmt->execute([
                        $order['orderid'],
                        $order['user'],
                        $callback_url,
                        $order['amount'],
                        $status,
                        $order['utr_number'],
                        $order['transactions_id'],
                        $order['received_from'],
                        json_encode($data),
                        $response,
                        $http_code,
                        ($http_code == 200 ? 'Sent' : 'Failed'),
                        $err
                    ]);
                }
            } catch (Exception $e) {
                // Ignore DB log error
                file_put_contents($logFile, date('Y-m-d H:i:s') . " - DB Log Error: " . $e->getMessage() . "\n", FILE_APPEND);
            }

            return true;
        } else {
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - No callback URL for user: " . $order['user'] . "\n", FILE_APPEND);
        }
    } catch (Exception $e) {
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - Exception: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
    return false;
}
?>
