<?php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../config/db.php';

$today = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $today)) {
    $today = date('Y-m-d');
}

// ============================================================
// STEP 1: Get ALL users (active + inactive) with their deposit info
// ============================================================
$users_query = mysqli_query($conn, "
    SELECT 
        u.wallet,
        u.name,
        u.account_id,
        u.mobile,
        u.status,
        u.created_at as user_created,
        COALESCE(u.reward_tier_1, 0) AS reward_tier_1,
        COALESCE(u.reward_tier_2, 0) AS reward_tier_2,
        COALESCE(u.reward_tier_3, 0) AS reward_tier_3,
        COALESCE(d.total_deposit, 0) AS total_investment,
        COALESCE(d.deposit_count, 0) AS deposit_count
    FROM users u
    LEFT JOIN (
        SELECT 
            wallet,
            SUM(amount) AS total_deposit,
            COUNT(*) AS deposit_count
        FROM deposits 
        WHERE status = 'success'
        GROUP BY wallet
    ) d ON u.wallet = d.wallet
    ORDER BY u.status DESC, u.name ASC
");

$all_users = [];
$active_users = [];
$inactive_users = [];
$users_with_deposit = [];
$users_without_deposit = [];

if (!$users_query) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database query failed: ' . mysqli_error($conn)
    ]);
    exit;
}

while ($user = mysqli_fetch_assoc($users_query)) {
    $walletAddr = $user['wallet'];
    $accId = trim($user['account_id']);
    $inv = floatval($user['total_investment']);
    $hasDeposit = $inv > 0;
    
    // Calculate trade rate based on investment
    $trade_rate = 4;
    if ($user['reward_tier_3'] == 1) {
        $trade_rate = 7;
    } elseif ($user['reward_tier_2'] == 1) {
        $trade_rate = 6;
    } elseif ($user['reward_tier_1'] == 1) {
        $trade_rate = 5;
    } elseif ($inv >= 500) {
        $trade_rate = 7;
    } elseif ($inv >= 200) {
        $trade_rate = 6;
    } elseif ($inv >= 100) {
        $trade_rate = 5;
    } elseif ($inv >= 60) {
        $trade_rate = 4;
    }
    
    $entry = [
        'wallet' => $walletAddr,
        'name' => $user['name'],
        'account_id' => $accId,
        'mobile' => $user['mobile'] ?? '',
        'status' => $user['status'],
        'total_investment' => round($inv, 2),
        'deposit_count' => intval($user['deposit_count']),
        'has_deposit' => $hasDeposit,
        'trade_rate' => $trade_rate,
        'reward_tier_1' => $user['reward_tier_1'],
        'reward_tier_2' => $user['reward_tier_2'],
        'reward_tier_3' => $user['reward_tier_3'],
        'joined_date' => $user['user_created']
    ];
    
    $all_users[] = $entry;
    
    if ($user['status'] == 'active') {
        $active_users[] = $entry;
        if ($hasDeposit) {
            $users_with_deposit[] = $entry;
        } else {
            $users_without_deposit[] = $entry;
        }
    } else {
        $inactive_users[] = $entry;
    }
}

// ============================================================
// STEP 2: Get today's traded users
// ============================================================
$colCheck = mysqli_query($conn, "SHOW COLUMNS FROM trade_logs LIKE 'account_id'");
$hasAccountId = mysqli_num_rows($colCheck) > 0;

if ($hasAccountId) {
    $traded_sql = "
        SELECT DISTINCT 
            tl.account_id,
            tl.wallet,
            u.name,
            u.mobile,
            u.status
        FROM trade_logs tl
        LEFT JOIN users u ON u.account_id = tl.account_id
        WHERE DATE(tl.created_at) = '$today'
        AND (tl.position != 'PENALTY' OR tl.position IS NULL)
        AND (tl.day_type != 'penalty' OR tl.day_type IS NULL)
    ";
} else {
    $traded_sql = "
        SELECT DISTINCT 
            TRIM(tl.wallet) AS wallet,
            u.account_id,
            u.name,
            u.mobile,
            u.status
        FROM trade_logs tl
        LEFT JOIN users u ON LOWER(TRIM(u.wallet)) = LOWER(TRIM(tl.wallet))
        WHERE DATE(tl.created_at) = '$today'
        AND (tl.position != 'PENALTY' OR tl.position IS NULL)
        AND (tl.day_type != 'penalty' OR tl.day_type IS NULL)
    ";
}

$traded_result = mysqli_query($conn, $traded_sql);
$traded_users_map = [];

if ($traded_result) {
    while ($row = mysqli_fetch_assoc($traded_result)) {
        $key = !empty($row['account_id']) ? trim($row['account_id']) : strtolower(trim($row['wallet']));
        $traded_users_map[$key] = [
            'account_id' => $row['account_id'] ?? '',
            'wallet' => $row['wallet'] ?? '',
            'name' => $row['name'] ?? '',
            'mobile' => $row['mobile'] ?? ''
        ];
    }
}

// ============================================================
// STEP 3: Get today's penalized users
// ============================================================
$penalty_sql = "
    SELECT DISTINCT
        tl.account_id,
        tl.wallet,
        ABS(tl.pnl_amount) as penalty_amount,
        tl.created_at,
        u.name,
        u.mobile
    FROM trade_logs tl
    LEFT JOIN users u ON u.account_id = tl.account_id OR u.wallet = tl.wallet
    WHERE DATE(tl.created_at) = '$today'
    AND tl.position = 'PENALTY'
    AND tl.day_type = 'penalty'
";

$penalty_result = mysqli_query($conn, $penalty_sql);
$penalized_users_map = [];

if ($penalty_result) {
    while ($row = mysqli_fetch_assoc($penalty_result)) {
        $key = !empty($row['account_id']) ? trim($row['account_id']) : strtolower(trim($row['wallet']));
        $penalized_users_map[$key] = [
            'account_id' => $row['account_id'] ?? '',
            'wallet' => $row['wallet'] ?? '',
            'name' => $row['name'] ?? '',
            'mobile' => $row['mobile'] ?? '',
            'penalty_amount' => abs(floatval($row['penalty_amount'])),
            'penalized_at' => $row['created_at']
        ];
    }
}

// ============================================================
// STEP 4: Prepare no-trade users (active users with deposit who didn't trade)
// ============================================================
$no_trade_users = [];
foreach ($users_with_deposit as $user) {
    $accId = trim($user['account_id']);
    $walletKey = strtolower(trim($user['wallet']));
    
    $didTrade = isset($traded_users_map[$accId]) || isset($traded_users_map[$walletKey]);
    $isPenalized = isset($penalized_users_map[$accId]) || isset($penalized_users_map[$walletKey]);
    
    if (!$didTrade && !$isPenalized && $user['status'] == 'active') {
        // Get current balance for this user
        $balance_query = mysqli_query($conn, "
            SELECT COALESCE(SUM(pnl_amount), 0) as total_roi
            FROM trade_logs
            WHERE (account_id = '$accId' OR wallet = '{$user['wallet']}')
            AND (position != 'PENALTY' OR position IS NULL)
            AND (day_type != 'penalty' OR day_type IS NULL)
        ");
        $roi = 0;
        if ($balance_query) {
            $roi_row = mysqli_fetch_assoc($balance_query);
            $roi = floatval($roi_row['total_roi']);
        }
        
        $current_balance = max(0, $user['total_investment'] + $roi);
        $penalty_amount = round($current_balance * ($user['trade_rate'] * 2) / 100, 2);
        
        $no_trade_users[] = [
            'wallet' => $user['wallet'],
            'name' => $user['name'],
            'account_id' => $user['account_id'],
            'mobile' => $user['mobile'],
            'total_investment' => $user['total_investment'],
            'current_balance' => round($current_balance, 2),
            'trade_rate' => $user['trade_rate'],
            'penalty_rate' => $user['trade_rate'] * 2,
            'penalty_amount' => $penalty_amount,
            'roi_income' => round($roi, 2)
        ];
    }
}

// ============================================================
// FINAL RESPONSE
// ============================================================
$response = [
    'status' => 'success',
    'date' => $today,
    'summary' => [
        'total_users' => count($all_users),
        'active_users' => count($active_users),
        'inactive_users' => count($inactive_users),
        'users_with_deposit' => count($users_with_deposit),
        'users_without_deposit' => count($users_without_deposit),
        'traded_today' => count($traded_users_map),
        'penalized_today' => count($penalized_users_map),
        'no_trade_today' => count($no_trade_users)
    ],
    'users' => [
        'all' => $all_users,
        'active' => $active_users,
        'inactive' => $inactive_users,
        'with_deposit' => $users_with_deposit,
        'without_deposit' => $users_without_deposit
    ],
    'today_activity' => [
        'traded' => array_values($traded_users_map),
        'penalized' => array_values($penalized_users_map),
        'not_traded' => $no_trade_users
    ]
];

echo json_encode($response, JSON_PRETTY_PRINT);
?>