<?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) : [];
$email = trim($input['email'] ?? ($_GET['email'] ?? ''));
$trade_id = trim($input['trade_id'] ?? ($_GET['trade_id'] ?? ''));

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

$where = '';
$param = '';
$type = '';
if ($email !== '') { $where = 'email = ?'; $param = $email; $type = 's'; }
else { $where = 'trade_id = ?'; $param = $trade_id; $type = 's'; }

$stmt = $conn->prepare("SELECT IFNULL(SUM(amount),0) AS total FROM pamm_profit_distribution WHERE entity_type = 'user' AND $where");
$stmt->bind_param($type, $param);
$stmt->execute();
$total = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
$stmt->close();

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

echo json_encode(["success" => true, "total_user_profit" => round(floatval($total), 8), "logs" => $logs]);
?>
