<?php
    /**
     * callback_tester.php - Simple Auto-Tester with Log Viewer
     */

    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    echo "<h2>OxaPay Callback Simple Tester</h2>";

    $defOrder = "";
    $defAmt = "100";
    $logFile = "callback_debug.log";

    // Try to include DB connection
    $samparkaPath = "../serive/samparka.php";
    if (file_exists($samparkaPath)) {
        include ($samparkaPath);
        
        if (isset($conn)) {
            // Find latest pending order using only orderId (dharavahi)
            $latestQuery = "SELECT dharavahi, motta FROM thevani WHERE sthiti = '0' LIMIT 1";
            $latestResult = $conn->query($latestQuery);
            
            if ($latestResult && $latestResult->num_rows > 0) {
                $row = $latestResult->fetch_assoc();
                $defOrder = $row['dharavahi'];
                $defAmt   = $row['motta'];
                echo "<p style='color:blue;'><b>✓ Found latest pending order in DB:</b> $defOrder</p>";
            } else {
                echo "<p style='color:orange;'><b>! No pending orders found.</b> Please generate a recharge request first.</p>";
            }
        }
    }

    echo "<hr>";
?>
    <form method="POST">
        <label>Internal Order ID (dharavahi):</label><br>
        <input type="text" name="orderId" value="<?php echo $defOrder; ?>" required><br><br>
        
        <label>Amount:</label><br>
        <input type="text" name="amount" value="<?php echo $defAmt; ?>" required><br><br>
        
        <input type="submit" name="test" value="Confirm Payment and Add Balance">
    </form>
<?php
    if (isset($_POST['test'])) {
        $target_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . str_replace("callback_tester.php", "oxa_webhook.php", $_SERVER['REQUEST_URI']);
        $merchant_api_key = "IPYKKV-I1LEGR-KYWSBT-TPL4OL";

        $orderId = $_POST['orderId'];
        $amount  = $_POST['amount'];

        // Get trackId from DB automatically
        $trackId = "TEST_TRACK"; 
        if (isset($conn)) {
            $e_order = mysqli_real_escape_string($conn, $orderId);
            $q = $conn->query("SELECT ullekha FROM thevani WHERE dharavahi = '$e_order'");
            if ($q && $q->num_rows > 0) {
                $r = $q->fetch_assoc();
                $trackId = $r['ullekha'];
            }
        }

        $data = [
            "trackId" => $trackId,
            "orderId" => $orderId,
            "status"  => "paid",
            "amount"  => $amount,
            "currency" => "INR"
        ];

        $postBody = json_encode($data);
        $hmac = hash_hmac('sha512', $postBody, $merchant_api_key);

        echo "<h3>Attempting to call: $target_url</h3>";

        $ch = curl_init($target_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'HMAC: ' . $hmac
        ]);

        $response = curl_exec($ch);
        $curlErr = curl_error($ch);
        curl_close($ch);

        echo "<hr><h3>Simulation Results:</h3>";
        if ($curlErr) echo "<p style='color:red;'>CURL Error: $curlErr</p>";
        echo "<b>Response:</b> <pre>" . htmlspecialchars($response) . "</pre>";
        
        if (trim($response) === "ok") {
            echo "<p style='color:green; font-size: 20px;'><b>✓ SUCCESS: Payment Confirmed!</b></p>";
        } else {
            echo "<p style='color:red;'><b>FAILED:</b> Webhook did not return 'ok'. See logs below.</p>";
        }
    }

    // --- LOG VIEWER ---
    echo "<hr><h3>Live Debug Logs (callback_debug.log):</h3>";
    if (file_exists($logFile)) {
        $logs = file($logFile);
        $lastLogs = array_slice($logs, -15); // Show last 15 lines
        echo "<div style='background:#f4f4f4; padding:10px; border:1px solid #ccc; font-family:monospace; height:300px; overflow-y:scroll;'>";
        foreach ($lastLogs as $line) {
            $color = (strpos($line, 'Error') !== false) ? 'red' : ((strpos($line, 'Success') !== false) ? 'green' : 'black');
            echo "<span style='color:$color'>" . htmlspecialchars($line) . "</span><br>";
        }
        echo "</div>";
    } else {
        echo "<p>No logs found yet. Log file will be created when a callback is received.</p>";
    }
?>
