<?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 {
    // 1. Fetch User Balance (🔥 FIX: 'wallets' ki jagah 'users' table se balance liya 🔥)
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    $balance = $user ? (float)$user['balance'] : 0.00;

    // 2. Fetch Active Methods & Channels
    $methodsStmt = $pdo->query("SELECT * FROM payment_methods WHERE status = 1 ORDER BY id ASC");
    $methods = $methodsStmt->fetchAll(PDO::FETCH_ASSOC);

    $channelsStmt = $pdo->query("SELECT * FROM payment_channels WHERE status = 1");
    $allChannels = $channelsStmt->fetchAll(PDO::FETCH_ASSOC);

    $formattedData = [];

    foreach ($methods as $m) {
        $methodChannels = [];
        foreach ($allChannels as $c) {
            if ($c['method_id'] == $m['id']) {
                $methodChannels[] = [
                    'id' => $c['id'],
                    'name' => $c['channel_name'],
                    'min' => (float)$c['min_amount'],
                    'max' => (float)$c['max_amount'],
                    'address' => $c['pay_address']
                ];
            }
        }
        
        // Agar is method me channels hain tabhi frontend pe bhejo
        if(count($methodChannels) > 0) {
            $formattedData[] = [
                'id' => $m['id'],
                'name' => $m['name'],
                'type' => $m['type'],
                'bonus' => $m['bonus_text'],
                'channels' => $methodChannels
            ];
        }
    }

    echo json_encode([
        'success' => true,
        'balance' => number_format($balance, 2),
        'methods' => $formattedData
    ]);

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