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

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'];
    $type = $_POST['type'] ?? 'fiat';
    $currency = $_POST['currency'] ?? 'USDT';
    $network = $_POST['network'] ?? '';
    
    $fiat_rates = get_fiat_rates();
    $rate = $fiat_rates[$currency] ?? 1.0;
    $usdt_amount = ($rate > 0) ? ($amount / $rate) : $amount;
    
    $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, amount, usdt_amount, exchange_rate, currency, status, expires_at, created_at) VALUES (?, ?, ?, ?, ?, 'matching', ?, CURRENT_TIMESTAMP)");
        $stmt->execute([$user_id, $amount, $usdt_amount, $rate, $currency, $expires_at]);
        $order_id = $pdo->lastInsertId();
        
        // Log to transactions table
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, currency, status, description) VALUES (?, 'deposit', ?, 'USDT', 'pending', ?)");
        $stmt->execute([$user_id, $usdt_amount, "Deposit Request #$order_id ($amount $currency)"]);

        // Explicit notification message for admin/chat
        $method_info = ($type === 'usdt') ? "USDT ($network)" : "法币 ($currency)";
        $msg = "升匆 用户发起充值，金额 $amount $currency\n订单号: #$order_id\n方式: $method_info";
        
        $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $msg]);
        
        $pdo->commit();
        header("Location: chat.php");
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
} else {
    header("Location: deposit.php");
    exit;
}
