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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
global $pdo;

try {
    // Auto-create USDT table if it doesn't exist in your SQL dump
    $pdo->exec("CREATE TABLE IF NOT EXISTS `usdt_details` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `usdt_address` varchar(100) NOT NULL,
      `network` varchar(20) DEFAULT 'TRC20',
      PRIMARY KEY (`id`),
      KEY `user_id` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

    // Fetch Balance
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
    $balance = $wallet ? number_format((float)$wallet['balance'], 2, '.', '') : "0.00";

    // Fetch Min Withdraw
    $minWithdraw = 110.00; 
    $setStmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = 'min_withdrawal' LIMIT 1");
    $setStmt->execute();
    $minW = $setStmt->fetchColumn();
    if ($minW) $minWithdraw = (float)$minW;

    // Fetch Saved Accounts
    $bankStmt = $pdo->prepare("SELECT * FROM bank_details WHERE user_id = ? ORDER BY id DESC LIMIT 1");
    $bankStmt->execute([$userId]);
    $savedBank = $bankStmt->fetch(PDO::FETCH_ASSOC);

    $upiStmt = $pdo->prepare("SELECT upi_id FROM upi_details WHERE user_id = ? ORDER BY id DESC LIMIT 1");
    $upiStmt->execute([$userId]);
    $savedUpi = $upiStmt->fetch(PDO::FETCH_ASSOC);

    $usdtStmt = $pdo->prepare("SELECT usdt_address FROM usdt_details WHERE user_id = ? ORDER BY id DESC LIMIT 1");
    $usdtStmt->execute([$userId]);
    $savedUsdt = $usdtStmt->fetch(PDO::FETCH_ASSOC);

    // Fetch History
    $histStmt = $pdo->prepare("SELECT amount, status, created_at FROM withdraw_requests WHERE user_id = ? ORDER BY id DESC LIMIT 10");
    $histStmt->execute([$userId]);
    $history = $histStmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'balance' => $balance,
        'min_withdraw' => number_format($minWithdraw, 2, '.', ''),
        'bank' => $savedBank ?: null,
        'upi' => $savedUpi ?: null,
        'usdt' => $savedUsdt ?: null,
        'history' => $history
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>