<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();

    // 1. Get Balance
    $stmt = $pdo->prepare("SELECT diamonds FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $balance = $stmt->fetchColumn();

    // 2. Get Transactions (Mocked for now as we don't have a transactions table populated yet)
    // In a real app, query the 'transactions' table
    $transactions = [];
    
    // Check if transactions table exists and has data
    try {
        $stmt_tx = $pdo->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
        $stmt_tx->execute([$user_id]);
        $transactions = $stmt_tx->fetchAll();
    } catch (Exception $e) {
        // Table might not exist or be empty
    }

    // 3. Get Global Settings
    $stmt_settings = $pdo->query("SELECT setting_key, setting_value FROM site_config WHERE setting_key IN ('diamond_exchange_rate', 'min_withdrawal_diamonds', 'sales_fee_percent', 'marketplace_category_fees')");
    $settings = $stmt_settings->fetchAll(PDO::FETCH_KEY_PAIR);

    echo json_encode([
        'status' => 'success',
        'diamonds' => (int)$balance,
        'transactions' => $transactions,
        'settings' => [
            'exchange_rate' => isset($settings['diamond_exchange_rate']) ? (float)$settings['diamond_exchange_rate'] : 0.01,
            'min_withdrawal' => isset($settings['min_withdrawal_diamonds']) ? (int)$settings['min_withdrawal_diamonds'] : 100,
            'sales_fee_base' => isset($settings['sales_fee_percent']) ? (float)$settings['sales_fee_percent'] : 10,
            'chat_unlock_fee' => isset($settings['chat_unlock_fee_percent']) ? (float)$settings['chat_unlock_fee_percent'] : 20,
            'subscription_fee' => isset($settings['subscription_fee_percent']) ? (float)$settings['subscription_fee_percent'] : 25,
            'category_fees' => json_decode($settings['marketplace_category_fees'] ?? '{}', true)
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
