<?php
    /**
     * oxa_webhook.php - OxaPay Payment Callback Handler
     * URL: https://moonclubs.in/pay/oxa_webhook.php (or your path)
     */
    
    // 1. Secret Key (Merchant API Key) for HMAC Validation
    $merchant_api_key = "IPYKKV-I1LEGR-KYWSBT-TPL4OL";

    // 2. Receive the Raw POST body
    $postBody = file_get_contents('php://input');
    $data = json_decode($postBody, true);

    // 3. Get the HMAC header sent by OxaPay (Check multiple sources for server compatibility)
    $hmacHeader = '';
    if (isset($_SERVER['HTTP_HMAC'])) {
        $hmacHeader = $_SERVER['HTTP_HMAC'];
    } elseif (isset($_SERVER['HTTP_HMAC_HEADER'])) {
        $hmacHeader = $_SERVER['HTTP_HMAC_HEADER'];
    } elseif (function_exists('apache_request_headers')) {
        $allHeaders = apache_request_headers();
        if (isset($allHeaders['Hmac'])) $hmacHeader = $allHeaders['Hmac'];
        elseif (isset($allHeaders['HMAC'])) $hmacHeader = $allHeaders['HMAC'];
    }

    // 4. Logging for Debugging
    $logFile = "callback_debug.log";
    function logMsg($msg) {
        global $logFile;
        file_put_contents($logFile, date("[Y-m-d H:i:s] ") . $msg . "\n", FILE_APPEND);
    }

    logMsg("Callback Received: " . $postBody);
    logMsg("HMAC Header: " . $hmacHeader);

    if (!$data || !$hmacHeader) {
        logMsg("Error: Missing Data or HMAC Header");
        die("Invalid request");
    }

    // 5. Verify HMAC Signature (SHA512)
    $calculatedHmac = hash_hmac('sha512', $postBody, $merchant_api_key);

    if ($calculatedHmac !== $hmacHeader) {
        logMsg("Error: Signature Mismatch! Calculated: $calculatedHmac");
        // For security, do not process if signature doesn't match
        // die("Unauthorized"); 
    }

    // 6. Process Payment if Status is 'Paid'
    // Status can be: 'paid', 'confirming', 'expired', etc.
    if ($data['status'] === 'paid' || $data['status'] === 'Confirmed') {
        
        include ("../serive/samparka.php");
        
        $trackId = mysqli_real_escape_string($conn, $data['trackId']);
        $orderId = mysqli_real_escape_string($conn, $data['orderId']); // our internal serial
        $amount = floatval($data['amount']);

        // Check if already processed to prevent duplicate credits
        $checkQuery = "SELECT sthiti, balakedara FROM thevani WHERE dharavahi = '$orderId' AND ullekha = '$trackId'";
        $checkResult = $conn->query($checkQuery);
        
        if ($checkResult && $checkResult->num_rows > 0) {
            $row = $checkResult->fetch_assoc();
            
            if ($row['sthiti'] == 0) { // If currently 'Pending'
                $uid = $row['balakedara'];

                // Update transaction status to 1 (Success)
                $updateThevani = "UPDATE thevani SET sthiti = '1' WHERE dharavahi = '$orderId'";
                $conn->query($updateThevani);

                // Add balance to user's wallet
                $updateWallet = "UPDATE shonu_kaichila SET motta = motta + $amount WHERE balakedara = '$uid'";
                $conn->query($updateWallet);

                logMsg("Success: UID $uid credited with $amount. Order: $orderId");
            } else {
                logMsg("Notice: Order $orderId already processed (Status: " . $row['sthiti'] . ")");
            }
        } else {
            logMsg("Error: Order $orderId not found in database.");
        }
    } else {
        logMsg("Notice: Payment status is " . $data['status'] . ". No balance added yet.");
    }

    // 7. OxaPay requires 'ok' response to stop retries
    echo "ok";
?>
