<?php
require_once 'db/config.php';
require_once 'includes/currency_helper.php';
session_start();

function json_die($error) {
    if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest") {
        echo json_encode(["success" => false, "error" => $error]);
    } else {
        die($error);
    }
    exit;
}

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'])) {
    $amount = (float)$_POST['amount'];
    $order_type = $_POST['order_type'] ?? 'deposit'; // 'deposit' or 'withdrawal'
    $type = $_POST['type'] ?? 'fiat'; // 'fiat' or 'usdt'
    $currency = $_POST['currency'] ?? 'USDT';
    $network = $_POST['network'] ?? '';
    
    if ($amount <= 0) {
        json_die("Invalid amount");
    }

    $fiat_rates = get_fiat_rates();
    $rate = $fiat_rates[$currency] ?? 1.0;
    
    if ($order_type === 'deposit') {
        $usdt_amount = ($rate > 0) ? ($amount / $rate) : $amount;
    } else {
        // Withdrawal: amount is already in USDT (usually)
        $usdt_amount = $amount;
        
        // For withdrawal, we check balance first
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $balance = (float)$stmt->fetchColumn();
        
        if ($balance < $usdt_amount) {
            json_die("余额不足");
        }
        
        // For withdrawal, we might need a trading password check if present
        if (isset($_POST['trading_password'])) {
            $stmt = $pdo->prepare("SELECT trading_password FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $saved_pass = $stmt->fetchColumn();
            if ($saved_pass && $saved_pass !== $_POST['trading_password']) {
                json_die("交易密码错误");
            }
        }
        
        // Deduct balance immediately for withdrawal
        $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->execute([$usdt_amount, $user_id]);
    }
    
    $expires_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));
    
    $pdo->beginTransaction();
    try {
        // Create order with status 'matching'
        $stmt = $pdo->prepare("INSERT INTO fiat_orders (user_id, order_type, amount, usdt_amount, exchange_rate, currency, status, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, 'matching', ?, CURRENT_TIMESTAMP)");
        $stmt->execute([$user_id, $order_type, $amount, $usdt_amount, $rate, $currency, $expires_at]);
        $order_id = $pdo->lastInsertId();
        
        // Log to transactions table
        $desc = ($order_type === 'deposit') ? "充值申请 #$order_id ($amount $currency)" : "提现申请 #$order_id ($amount $currency)";
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, currency, status, description) VALUES (?, ?, ?, 'USDT', 'pending', ?)");
        $stmt->execute([$user_id, $order_type, ($order_type === 'deposit' ? $usdt_amount : -$usdt_amount), $desc]);

        // Notification message for admin/chat
        $type_text = ($order_type === 'deposit') ? "充值" : "提现";
        $method_info = ($type === 'usdt') ? "USDT ($network)" : "法币 ($currency)";
        
        // More active messages as if user is typing
        if ($order_type === 'deposit') {
            $msg = "你好，我已发起一笔 $amount $currency 的充值申请。请为我匹配收款账户。";
        } else {
            $msg = "你好，我已发起一笔 $amount $currency 的提现申请。请发送收款信息格式给我。";
        }
        
        // System record (visible to admin as a request tag)
        $sys_msg = "📢 订单详情\n类型: $type_text\n金额: $amount $currency\n方式: $method_info\n单号: #$order_id";
        
        $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $msg]);
        
        $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $sys_msg]);
        
        $pdo->commit();
        if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest") { 
            echo json_encode(["success" => true, "order_id" => $order_id]); 
            exit; 
        } else { 
            header("Location: chat.php"); 
        }
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        json_die("Error: " . $e->getMessage());
    }
} else {
    header("Location: index.php");
    exit;
}