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

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

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

$stmt = $conn->prepare("SELECT IFNULL(SUM(amount),0) AS total FROM pamm_profit_distribution WHERE entity_type = 'master' 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 = 'master' 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_earnings" => round(floatval($total), 8), "logs" => $logs]);
?>
