<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');

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

// Basic admin check (this is a simplified check, adjust based on your project's admin auth)
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';
$order_id = $_REQUEST['id'] ?? null;
$user_id = $_REQUEST['user_id'] ?? null;
$ip_address = $_REQUEST['ip_address'] ?? '';
$session_id = $_REQUEST['session_id'] ?? '';

if (!$order_id && !isset($user_id) && empty($ip_address)) {
    echo json_encode(['success' => false, 'error' => 'Missing ID, User ID or IP']);
    exit;
}

try {
    $db = db();
    
    if (!$order_id) {
        // Find the latest pending/matching/account_sent recharge for this user
        // We try to match by user_id first, then by IP/Session if user_id is 0
        if ($user_id > 0) {
            $stmt = $db->prepare("SELECT id FROM finance_requests WHERE user_id = ? AND type = 'recharge' AND status IN ('0', '1', '2', 'pending', 'matched', 'account_sent', 'finished') ORDER BY id DESC LIMIT 1");
            $stmt->execute([$user_id]);
        } else {
            $stmt = $db->prepare("SELECT id FROM finance_requests WHERE (ip_address = ? OR payment_details = ?) AND type = 'recharge' AND status IN ('0', '1', '2', 'pending', 'matched', 'account_sent', 'finished') ORDER BY id DESC LIMIT 1");
            $stmt->execute([$ip_address, $session_id]);
        }
        $order_id = $stmt->fetchColumn();
    }

    if (!$order_id) {
        echo json_encode(['success' => false, 'error' => '未找到该用户的待处理充值订单']);
        exit;
    }

    if ($action === 'match_success') {
        $stmt = $db->prepare("UPDATE finance_requests SET status = '1', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$order_id]);
        
        echo json_encode(['success' => true]);
    } 
    elseif ($action === 'send_account') {
        $bank = $_POST['bank'] ?? '';
        $name = $_POST['name'] ?? '';
        $account = $_POST['account'] ?? '';
        $note = $_POST['note'] ?? '';

        $stmt = $db->prepare("UPDATE finance_requests SET status = '2', account_bank = ?, account_name = ?, account_number = ?, payment_details = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$bank, $name, $account, $note, $order_id]);
        
        echo json_encode(['success' => true]);
    }
    elseif ($action === 'approve') {
        $confirm_amount = $_POST['confirm_amount'] ?? $_POST['final_amount'] ?? null;
        if ($confirm_amount === null) {
            echo json_encode(['success' => false, 'error' => 'Missing confirmation amount']);
            exit;
        }

        $db->beginTransaction();
        try {
            // Get order details
            $stmt = $db->prepare("SELECT * FROM finance_requests WHERE id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();

            if (!$order) throw new Exception("订单不存在");
            if ($order['status'] == '3') throw new Exception("订单已审核通过，请勿重复操作");

            // Update order status to '3' (Approved)
            $stmt = $db->prepare("UPDATE finance_requests SET status = '3', amount = ? WHERE id = ?");
            $stmt->execute([$confirm_amount, $order_id]);

            // Update user balance
            if ($order['user_id'] > 0) {
                // Ensure balance record exists
                $stmt = $db->prepare("SELECT id FROM user_balances WHERE user_id = ? AND symbol = ?");
                $stmt->execute([$order['user_id'], $order['symbol']]);
                if (!$stmt->fetch()) {
                    $stmt = $db->prepare("INSERT INTO user_balances (user_id, symbol, available) VALUES (?, ?, 0)");
                    $stmt->execute([$order['user_id'], $order['symbol']]);
                }

                $stmt = $db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = ?");
                $stmt->execute([$confirm_amount, $order['user_id'], $order['symbol']]);
                
                // Record transaction
                $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status, ip_address) VALUES (?, 'recharge', ?, ?, 'completed', ?)");
                $stmt->execute([$order['user_id'], $confirm_amount, $order['symbol'], $order['ip_address']]);
                
                // Update stats
                require_once __DIR__ . '/../admin/stats.php'; // For any helper functions if needed, or just do manual updates
                // The finance.php has some logic for VIP levels, I should probably replicate or call it.
            }

            $db->commit();
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            $db->rollBack();
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
    elseif ($action === 'reject') {
        $stmt = $db->prepare("UPDATE finance_requests SET status = '4' WHERE id = ?");
        $stmt->execute([$order_id]);
        echo json_encode(['success' => true]);
    }
    elseif ($action === 'get_order_info') {
        $stmt = $db->prepare("SELECT * FROM finance_requests WHERE id = ?");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'order' => $order]);
    }
    else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
