<?php
// 데이터 호출 & AJAX 초 응답 처리
// 출력 버퍼링 시작 (AJAX 응답 오염 방지)
ob_start();
// --- JSON 응답 엔드포인트 시작 ---
if (isset($_GET['ajax_mode']) && $_GET['ajax_mode'] == 'get_json') {
ob_end_clean();
header('Content-Type: application/json');
// [기존 연산 로직 유지]
$cur_av = 0; $cur_cv = 0; $cur_iv = 0; $cur_pv = 0;
try {
$stmt = $pdo->query("SELECT total_asset_value, cash_balance, total_profit_amount FROM daemon_upbit_Ticker_user ORDER BY collected_at DESC LIMIT 1");
$r = $stmt->fetch(PDO::FETCH_ASSOC);
if ($r) { $cur_av = (float)$r['total_asset_value']; $cur_cv = (float)$r['cash_balance']; $cur_iv = $cur_av - $cur_cv; $cur_pv = (float)$r['total_profit_amount']; }
} catch (Throwable $e) {}
$base_date = "2026-02-26"; $write_table = "g5_write_moving_assets"; $base_asset = 0;
try {
$stmt = $pdo->prepare("SELECT total_asset_value FROM daemon_upbit_user_1m WHERE collected_at >= :d ORDER BY collected_at ASC LIMIT 1");
$stmt->execute([':d' => $base_date . ' 00:00:00']);
$r = $stmt->fetch(PDO::FETCH_ASSOC); if ($r) $base_asset = (float)$r['total_asset_value'];
} catch (Throwable $e) {}
$row_base = sql_fetch("SELECT x2_total_bank_in, x2_total_bank_out FROM {$write_table} WHERE wr_datetime <= '{$base_date} 23:59:59' ORDER BY wr_datetime DESC LIMIT 1");
if ($row_base) { $base_in = (float)$row_base['x2_total_bank_in']; $base_out = (float)$row_base['x2_total_bank_out']; }
$io = sql_fetch("SELECT x2_total_bank_in, x2_total_bank_out FROM {$write_table} ORDER BY wr_datetime DESC LIMIT 1");
$cur_in = $io ? (float)$io['x2_total_bank_in'] : $base_in; $cur_out = $io ? (float)$io['x2_total_bank_out'] : $base_out;
$should_have_latest = $base_asset + ($cur_in - $base_in) - ($cur_out - $base_out);
$cost_basis = $cur_iv - $cur_pv; $total_asset = $cost_basis + $cur_cv;
$pure_profit = $cur_av - $should_have_latest;
$pure_roi = $should_have_latest ? ($pure_profit / $should_have_latest * 100) : 0;
$buy_ratio = $total_asset ? ($cost_basis / $total_asset * 100) : 0;
$total_roi = $total_asset ? ($cur_pv / $total_asset * 100) : 0;
$days = (new DateTime())->diff(new DateTime($base_date))->days;
$current_roi = $cost_basis ? ($cur_iv * 100 / $cost_basis - 100) : 0;
$avg_pnl = $days ? ($pure_profit / $days) : 0;
$avg_roi = $days ? ($pure_roi / $days) : 0;
$buy_av = $cost_basis + $cur_cv;
echo json_encode([
'cur_av' => $cur_av, 'should_have_latest' => $should_have_latest, 'pure_profit' => $pure_profit,
'pure_roi' => $pure_roi, 'total_asset' => $total_asset, 'cost_basis' => $cost_basis,
'cur_cv' => $cur_cv, 'buy_ratio' => $buy_ratio, 'cur_pv' => $cur_pv, 'total_roi' => $total_roi,
'current_roi' => $current_roi, 'avg_pnl' => $avg_pnl, 'avg_roi' => $avg_roi, 'buy_av' => $buy_av,
'avg_pnl_m' => $avg_pnl * 30, 'avg_roi_m' => $avg_roi * 30, // 월간 데이터 추가
'avg_pnl_y' => $avg_pnl * 365, 'avg_roi_y' => $avg_roi * 365 // 년간 데이터 추가
]);
exit;
}
if (ob_get_level() > 0) ob_end_flush();
?>