<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

include('config.php'); // DB connection

$response = [
    'success' => true,
    'total_clients' => 0,
    'clients' => []
];

// Fetch all clients
$userQuery = $conn->query("SELECT * FROM loginusers ORDER BY id DESC");

while ($user = $userQuery->fetch_assoc()) {
    $userId = $user['id'];
    $clientName = trim($user['first_name'] . ' ' . $user['last_name']);
    $clientEmail = $user['email'];
    $country = $user['country'];
    $phone = $user['phone'];
    $regDate = $user['reg_date'];
    $status = ($user['status'] == 1) ? "Active" : "Inactive";

    // Fetch trade IDs for this user
    $tradeQuery = $conn->query("SELECT trade_id FROM liveaccounts WHERE user_id = $userId");
    $tradeIds = [];
    while ($trade = $tradeQuery->fetch_assoc()) {
        $tradeIds[] = $trade['trade_id'];
    }

    // Get parent email from IB1
    $parentEmail = null;
    if (!empty($user['ib1']) && $user['ib1'] != 'noIB' && $user['ib1'] != 'noIBu') {
        $ib1Value = $conn->real_escape_string($user['ib1']);
        $ibQuery = $conn->query("SELECT email FROM loginusers WHERE uid='$ib1Value' OR email='$ib1Value' LIMIT 1");
        if ($ib = $ibQuery->fetch_assoc()) {
            $parentEmail = $ib['email'];
        }
    }

    /* ---------------- COMMISSION / REBATE EARNED ---------------- */
    $totalCommission = 0.00;
    $availableCommission = 0.00;
    $withdrawCommission = 0.00;

    $totalProfitCommission = 0.00;       // NEW: total profit commission
    $availableProfitCommission = 0.00;   // NEW: available profit commission
    $profitWithdrawn = 0.00;             // NEW: withdrawn profit commission

    $partners = [];

    // Fetch from ib_total_commission
    $commissionQuery = $conn->prepare("SELECT total_commission, available_commission FROM ib_total_commission WHERE ib_email = ?");
    $commissionQuery->bind_param("s", $clientEmail);
    $commissionQuery->execute();
    $commissionResult = $commissionQuery->get_result();
    if ($commissionRow = $commissionResult->fetch_assoc()) {
        $totalCommission = floatval($commissionRow['total_commission']);
        $availableCommission = floatval($commissionRow['available_commission']);
    }
    $commissionQuery->close();

    // Fetch from ib_total_profit_commission (NEW)
    $profitQuery = $conn->prepare("SELECT total_profit_commission, available_profit_commission FROM ib_total_profit_commission WHERE ib_email = ?");
    $profitQuery->bind_param("s", $clientEmail);
    $profitQuery->execute();
    $profitResult = $profitQuery->get_result();
    if ($profitRow = $profitResult->fetch_assoc()) {
        $totalProfitCommission = floatval($profitRow['total_profit_commission']);
        $availableProfitCommission = floatval($profitRow['available_profit_commission']);
    }
    $profitQuery->close();

    // 2️⃣ WITHDRAW COMMISSION (approved withdrawals)
    $withdrawQuery = $conn->prepare("SELECT SUM(total_commission) AS totalWithdraw FROM ib_withdraw_request WHERE email = ? AND status = 1");
    $withdrawQuery->bind_param("s", $clientEmail);
    $withdrawQuery->execute();
    $withdrawResult = $withdrawQuery->get_result();
    if ($withdrawRow = $withdrawResult->fetch_assoc()) {
        $withdrawCommission = floatval($withdrawRow['totalWithdraw']);
    }
    $withdrawQuery->close();

    // 2️⃣ WITHDRAW PROFIT COMMISSION (approved withdrawals) - NEW
    $profitWithdrawQuery = $conn->prepare("SELECT SUM(total_commission) AS totalProfitWithdraw FROM ib_withdraw_request WHERE email = ? AND status = 1 AND type='profit_commission'");
    $profitWithdrawQuery->bind_param("s", $clientEmail);
    $profitWithdrawQuery->execute();
    $profitWithdrawResult = $profitWithdrawQuery->get_result();
    if ($profitWithdrawRow = $profitWithdrawResult->fetch_assoc()) {
        $profitWithdrawn = floatval($profitWithdrawRow['totalProfitWithdraw']);
    }
    $profitWithdrawQuery->close();

    // 3️⃣ HIS PARTNERS (sub-IBs directly under this IB)
    $partnerEmails = [];
    $conditions = [];
    for ($i = 1; $i <= 20; $i++) {
        $conditions[] = "ib$i = '" . $conn->real_escape_string($clientEmail) . "'";
    }
    $partnerQuery = $conn->query("SELECT email FROM loginusers WHERE " . implode(" OR ", $conditions));
    while ($partner = $partnerQuery->fetch_assoc()) {
        $partnerEmails[] = $partner['email'];
    }
    $partners = $partnerEmails;

    /* ---------------- BUILD RESPONSE ---------------- */
    $response['clients'][] = [
        'client_name' => $clientName,
        'client_email' => $clientEmail,
        'country' => $country,
        'phone' => $phone,
        'reg_date' => $regDate,
        'status' => $status,
        'parent_email' => $parentEmail,
        'trade_ids' => $tradeIds,
        'commission_earned' => round($totalCommission, 2),
        'available_commission' => round($availableCommission, 2),
        'withdraw_commission' => round($withdrawCommission, 2),
        'profit_commission_earned' => round($totalProfitCommission, 2),        // NEW
        'profit_commission_available' => round($availableProfitCommission, 2),  // NEW
        // 'profit_withdrawn' => round($profitWithdrawn, 2),                       // NEW
        'partners' => $partners,
        'commission_status' => ($user['commission_status'] == 1) ? "Active" : "Stopped"
    ];
}

$response['total_clients'] = count($response['clients']);

echo json_encode($response, JSON_PRETTY_PRINT);
?>
