<?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 users who traded today (excluding penalty trades)
// ============================================================
$traded_accounts = [];
$traded_wallets  = [];

$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'trade_logs'");
if (mysqli_num_rows($table_check) > 0) {
    $trade_query = mysqli_query($conn, "
        SELECT DISTINCT account_id, wallet
        FROM trade_logs
        WHERE DATE(created_at) = '$today'
          AND (position != 'PENALTY' OR position IS NULL)
          AND (day_type != 'penalty' OR day_type IS NULL)
    ");
    if ($trade_query) {
        while ($row = mysqli_fetch_assoc($trade_query)) {
            if (!empty($row['account_id'])) $traded_accounts[trim($row['account_id'])] = true;
            if (!empty($row['wallet']))     $traded_wallets[strtolower(trim($row['wallet']))] = true;
        }
    }
}

// ============================================================
// STEP 2: Get already penalized users for this date
// ============================================================
$penalized_accounts = [];
$penalized_wallets  = [];
$penalty_list       = [];

$penalty_query = mysqli_query($conn, "
    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'
");
if ($penalty_query) {
    while ($row = mysqli_fetch_assoc($penalty_query)) {
        if (!empty($row['account_id'])) $penalized_accounts[trim($row['account_id'])] = true;
        if (!empty($row['wallet']))     $penalized_wallets[strtolower(trim($row['wallet']))] = true;
        $penalty_list[] = [
            'wallet'     => $row['wallet'],
            'account_id' => $row['account_id'],
            'name'       => $row['name']   ?? '—',
            'mobile'     => $row['mobile'] ?? '—',
            'amount'     => abs(floatval($row['penalty_amount'])),
            'time'       => $row['created_at']
        ];
    }
}

// ============================================================
// STEP 3: ALL users who have total deposit >= 60 (active investors)
// — No status filter, purely deposit-based like the dashboard
// ============================================================
$users_list       = []; // did NOT trade, not penalized
$traded_users_list = []; // traded today
$total_active     = 0;

$users_query = mysqli_query($conn, "
    SELECT
        u.wallet,
        u.name,
        u.account_id,
        u.mobile,
        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(dep.total_deposit, 0) AS total_investment
    FROM users u
    LEFT JOIN (
        SELECT wallet, SUM(amount) AS total_deposit
        FROM deposits
        WHERE status = 'success'
        GROUP BY wallet
    ) dep ON u.wallet = dep.wallet
    WHERE COALESCE(dep.total_deposit, 0) >= 60
    ORDER BY u.name ASC
");

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

while ($user = mysqli_fetch_assoc($users_query)) {
    $inv       = floatval($user['total_investment']);
    $walletAddr = $user['wallet'];
    $accId      = trim($user['account_id']);
    $walletKey  = strtolower(trim($walletAddr));

    $total_active++;

    // ── ROI income (non-penalty trades only) ──
    $roi_res = mysqli_query($conn, "
        SELECT COALESCE(SUM(pnl_amount), 0) AS total_roi
        FROM trade_logs
        WHERE (account_id = '$accId' OR wallet = '$walletAddr')
          AND (position != 'PENALTY' OR position IS NULL)
          AND (day_type != 'penalty' OR day_type IS NULL)
    ");
    $roi = $roi_res ? floatval(mysqli_fetch_assoc($roi_res)['total_roi']) : 0;

    // ── Withdrawals ──
    $wd_res = mysqli_query($conn, "
        SELECT COALESCE(SUM(amount), 0) AS total_wd
        FROM withdrawals
        WHERE wallet = '$walletAddr' AND status = 'completed'
    ");
    $wd = $wd_res ? floatval(mysqli_fetch_assoc($wd_res)['total_wd']) : 0;

    // ── Current balance (same formula as dashboard) ──
    $joiningBonus   = $inv * 0.05;
    $remainingWD    = $wd;
    if ($remainingWD >= $joiningBonus) { $remainingWD -= $joiningBonus; }
    else { $remainingWD = 0; }
    $remainingProfit  = $roi - $remainingWD;
    $current_balance  = max(0, $inv + $remainingProfit);

    // ── Trade rate: reward tier ONLY (matches dashboard) ──
    $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;

    $penalty_rate   = $trade_rate * 2;
    $penalty_amount = round($current_balance * $penalty_rate / 100, 2);

    $did_trade    = isset($traded_accounts[$accId])    || isset($traded_wallets[$walletKey]);
    $is_penalized = isset($penalized_accounts[$accId]) || isset($penalized_wallets[$walletKey]);

    $entry = [
        'wallet'           => $walletAddr,
        'name'             => $user['name'],
        'account_id'       => $accId,
        'mobile'           => $user['mobile'] ?? '',
        'total_investment' => round($inv, 2),
        'current_balance'  => round($current_balance, 2),
        'trade_rate'       => $trade_rate,
        'penalty_rate'     => $penalty_rate,
        'penalty_amount'   => $penalty_amount,
        'roi_income'       => round($roi, 2)
    ];

    if ($did_trade) {
        $traded_users_list[] = $entry;
    } elseif (!$is_penalized) {
        $users_list[] = $entry;
    }
}

echo json_encode([
    'status'         => 'success',
    'date'           => $today,
    'total_active'   => $total_active,
    'traded_count'   => count($traded_users_list),
    'no_trade_count' => count($users_list),
    'penalized_count'=> count($penalty_list),
    'users'          => $users_list,
    'traded_users'   => $traded_users_list,
    'penalty_report' => $penalty_list
]);
?>