<?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');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/config.php';

$payload = file_get_contents('php://input');
$input = $payload ? json_decode($payload, true) : [];
$ib_email = trim($input['ib_email'] ?? ($_GET['ib_email'] ?? ''));

if ($ib_email === '') {
    echo json_encode(["success" => false, "message" => "ib_email required"]);
    exit;
}

$stmt = $conn->prepare("SELECT level, SUM(amount) AS total FROM pamm_profit_distribution WHERE entity_type = 'ib' AND email = ? GROUP BY level ORDER BY level ASC");
$stmt->bind_param("s", $ib_email);
$stmt->execute();
$levels = [];
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) { $levels[] = ["level" => intval($r['level']), "total" => round(floatval($r['total']), 8)]; }
$stmt->close();

$stmt = $conn->prepare("SELECT event_uid, level, amount, credited_at FROM pamm_profit_distribution WHERE entity_type = 'ib' AND email = ? ORDER BY credited_at DESC LIMIT 500");
$stmt->bind_param("s", $ib_email);
$stmt->execute();
$logs = [];
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) { $logs[] = $r; }
$stmt->close();

$stmt = $conn->prepare("SELECT total_profit_commission, available_profit_commission FROM ib_total_profit_commission WHERE ib_email = ? LIMIT 1");
$stmt->bind_param("s", $ib_email);
$stmt->execute();
$agg = $stmt->get_result()->fetch_assoc();
$stmt->close();

echo json_encode([
    "success" => true,
    "ib_email" => $ib_email,
    "levels" => $levels,
    "logs" => $logs,
    "aggregates" => $agg ? [
        "total_profit_commission" => round(floatval($agg['total_profit_commission']), 8),
        "available_profit_commission" => round(floatval($agg['available_profit_commission']), 8)
    ] : ["total_profit_commission" => 0, "available_profit_commission" => 0]
]);
?>
