<?php
// Function to bridge Supabase Payment to Game MySQL Database
require_once 'mysql_config.php';

function update_game_database($order_id, $amount, $user_id) {
    global $conn_mysql;
    
    if (!$conn_mysql) return false;

    $log_file = __DIR__ . '/debug.log';
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Bridging to MySQL for Order: $order_id\n", FILE_APPEND);

    // 1. Update the 'thevani' table (Transaction Log)
    // Map order_id to dharavahi and status to sthiti (1 = Success)
    $stmt = $conn_mysql->prepare("UPDATE thevani SET sthiti = '1' WHERE dharavahi = ?");
    $stmt->bind_param("s", $order_id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        file_put_contents($log_file, "   -> MySQL 'thevani' updated.\n", FILE_APPEND);
        
        // 2. Update the 'shonu_kaichila' table (Wallet balance)
        // Map user_id to balakedara and add amount to motta
        $stmt_wallet = $conn_mysql->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
        $stmt_wallet->bind_param("ds", $amount, $user_id);
        $stmt_wallet->execute();

        if ($stmt_wallet->affected_rows > 0) {
            file_put_contents($log_file, "   -> MySQL Wallet updated successfully.\n", FILE_APPEND);
            return true;
        } else {
            file_put_contents($log_file, "   -> MySQL Wallet update FAILED (User not found?).\n", FILE_APPEND);
        }
    } else {
        file_put_contents($log_file, "   -> MySQL 'thevani' update FAILED (Order not found?).\n", FILE_APPEND);
    }

    return false;
}
?>
