<?php
/**
 * Shohoj World Pay / Mr Ai Pay - Direct Success Logic
 * Add Money to Wallet + Voucher Auto Delivery System
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

ob_start();

if (file_exists('config.php')) {
    include 'config.php';
} else if (file_exists('common/config.php')) {
    include 'common/config.php';
} else if (file_exists('../config.php')) {
    include '../config.php';
} else {
    die("<b>Error:</b> config.php file not found.");
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$trx_id = $_REQUEST['transaction_id'] ?? $_REQUEST['trx_id'] ?? $_REQUEST['id'] ?? $_REQUEST['payment_id'] ?? null;

if (!$trx_id) {
    $trx_id = "AUTO-" . strtoupper(uniqid());
}

if (!isset($_SESSION['temp_order'])) {
    echo "<div style='text-align:center; margin-top:50px; font-family:sans-serif;'>";
    echo "<h2 style='color:#d97706;'>Order Session Missing!</h2>";
    echo "<a href='index.php'>Go to Home</a>";
    echo "</div>";
    exit();
}

$temp = $_SESSION['temp_order'];

try {
    $user_id   = (int)$_SESSION['user_id'];
    $game_id   = (int)($temp['game_id'] ?? 0); 
    $prod_id   = (int)($temp['product_id'] ?? 0);
    $amount    = (float)$temp['amount'];
    $player_id = !empty($temp['player_id']) ? $temp['player_id'] : 'Auto Payment';
    
    // ==========================================
    // 1. ADD MONEY (WALLET DEPOSIT) LOGIC
    // ==========================================
    if ($prod_id == 0 && $game_id == 0) {
        // ডুপ্লিকেট ডিপোজিট চেক
        $dCheck = $conn->query("SELECT id FROM deposits WHERE trx_id = '$trx_id'");
        if ($dCheck && $dCheck->num_rows > 0) {
            unset($_SESSION['temp_order']);
            header("Location: addmoney.php");
            exit();
        }

        // ইউজারের ব্যালেন্স বৃদ্ধি করা
        $conn->query("UPDATE users SET balance = balance + $amount WHERE id = $user_id");
        
        // ডিপোজিট হিস্ট্রিতে রেকর্ড রাখা (অটো কমপ্লিট)
        $stmt = $conn->prepare("INSERT INTO deposits (user_id, amount, method, trx_id, status, created_at) VALUES (?, ?, 'Auto Pay', ?, 'completed', NOW())");
        $stmt->bind_param("ids", $user_id, $amount, $trx_id);
        $stmt->execute();
        
        unset($_SESSION['temp_order']);
        echo "<script>alert('✅ Successfully added {$amount} ৳ to your Wallet!'); window.location.href='index.php';</script>";
        exit();
    }
    
    // ==========================================
    // 2. PRODUCT PURCHASE (GAME TOPUP) LOGIC
    // ==========================================
    $safe_trx = $conn->real_escape_string($trx_id);
    $check = $conn->query("SELECT id FROM orders WHERE transaction_id = '$safe_trx'");
    if ($check && $check->num_rows > 0) {
        unset($_SESSION['temp_order']);
        header("Location: order.php");
        exit();
    }

    $gameType = 'uid';
    $gRes = $conn->query("SELECT type FROM games WHERE id=$game_id");
    if($gRes && $gRes->num_rows > 0) $gameType = $gRes->fetch_assoc()['type'];

    $method_type = "Shohoj Pay";
    $status_type = ($gameType == 'voucher') ? 'completed' : 'processing';
    
    $stmt = $conn->prepare("INSERT INTO orders (user_id, game_id, product_id, amount, player_id, transaction_id, payment_method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("iiidssss", $user_id, $game_id, $prod_id, $amount, $player_id, $trx_id, $method_type, $status_type);
    $result = $stmt->execute();
    $order_id = $conn->insert_id;

    if ($result) {
        if($gameType == 'voucher') {
            $vRes = $conn->query("SELECT id FROM redeem_codes WHERE product_id=$prod_id AND order_id IS NULL LIMIT 1");
            if($vRes && $vRes->num_rows > 0) {
                $vRow = $vRes->fetch_assoc();
                $conn->query("UPDATE redeem_codes SET order_id=$order_id WHERE id=".$vRow['id']);
            }
            unset($_SESSION['temp_order']);
            echo "<script>alert('Payment Successful! Voucher Code Generated.'); window.location.href='mycode.php';</script>";
            exit();
        }
        
        unset($_SESSION['temp_order']);
        echo "<script>alert('Payment Successful! Your order is processing.'); window.location.href='order.php';</script>";
        exit();
    } else {
        throw new Exception("Database insert failed.");
    }

} catch (Exception $e) {
    echo "Database Error: " . htmlspecialchars($e->getMessage());
}

ob_end_flush();
?>