<?php
require_once '../config.php';

// 權限檢查 (僅限家長/管理者)
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$family_id = $_SESSION['family_id'];
$error_msg = '';

$report_data = [];

try {
    $today_date = date('Y-m-d');

    // 0. 撈取目前全服最新的股價，用來結算股市未實現損益
    $global_prices = [];
    try {
        $stmt_prices = $mysql_db->query("SELECT id, current_price FROM global_stocks");
        foreach ($stmt_prices->fetchAll() as $r) {
            $global_prices[$r['id']] = (float)$r['current_price'];
        }
    } catch (Exception $e) {}

    // ★ 撈取房市全局抗通膨增值率
    $growth_rate = 0.002; // 預設 0.2%
    try {
        $global_estate = $mysql_db->query("SELECT daily_value_growth_rate FROM estate_global_settings WHERE id = 1")->fetch();
        if ($global_estate) $growth_rate = (float)$global_estate['daily_value_growth_rate'];
    } catch (Exception $e) {}

    // 1. 撈取本家庭的所有小孩(玩家)
    $stmt_players = $mysql_db->prepare("SELECT id, display_name, sqlite_file FROM users WHERE family_id = :family_id AND role = 'player' ORDER BY created_at ASC");
    $stmt_players->execute([':family_id' => $family_id]);
    $players = $stmt_players->fetchAll();

    // 2. 輪流進入每個小孩的 SQLite 撈取統計數據
    foreach ($players as $p) {
        $kid_stat = [
            'name' => $p['display_name'],
            'wallet_balance' => 0,
            'bank_balance' => 0,
            'stock_cost' => 0,     
            'stock_value' => 0,    
            'stock_profit' => 0,   
            // ★ 新增房市數據
            'estate_cost' => 0,
            'estate_value' => 0,
            'estate_profit' => 0,
            'total_tasks' => 0,
            'total_earned' => 0,
            'star_3' => 0, 
            'star_2' => 0, 
            'star_1' => 0
        ];

        if (!empty($p['sqlite_file']) && file_exists('../' . $p['sqlite_file'])) {
            $p_db = getPlayerSQLiteConnection($p['sqlite_file']);

            // A. 錢包餘額
            $wallet_row = $p_db->query("SELECT balance_minutes FROM wallet LIMIT 1")->fetch();
            if ($wallet_row) $kid_stat['wallet_balance'] = (int)$wallet_row['balance_minutes'];

            // B. 銀行存款
            $table_check_bank = $p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='time_bank'")->fetch();
            if ($table_check_bank) {
                $bank_row = $p_db->query("SELECT balance_minutes FROM time_bank LIMIT 1")->fetch();
                if ($bank_row) $kid_stat['bank_balance'] = (int)$bank_row['balance_minutes'];
            }

            // C. 股市資產與未實現損益
            $table_check_stock = $p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='stock_portfolio'")->fetch();
            if ($table_check_stock) {
                $port_rows = $p_db->query("SELECT * FROM stock_portfolio WHERE total_shares > 0")->fetchAll();
                foreach ($port_rows as $row) {
                    $sid = $row['stock_id'];
                    $shares = (int)$row['total_shares'];
                    $avg_cost = (float)$row['average_cost'];
                    $current_price = isset($global_prices[$sid]) ? $global_prices[$sid] : $avg_cost; 
                    
                    $kid_stat['stock_cost'] += ($shares * $avg_cost);
                    $kid_stat['stock_value'] += ($shares * $current_price);
                }
                $kid_stat['stock_profit'] = $kid_stat['stock_value'] - $kid_stat['stock_cost'];
            }

            // ★ D. 房市資產與未實現增值
            $table_check_estate = $p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='estate_properties'")->fetch();
            if ($table_check_estate) {
                $estate_rows = $p_db->query("SELECT * FROM estate_properties")->fetchAll();
                foreach ($estate_rows as $prop) {
                    $d1 = new DateTime($prop['purchase_date']);
                    $d2 = new DateTime($today_date);
                    $days = (int)$d1->diff($d2)->format('%a');
                    
                    $principal = (int)$prop['land_purchase_price'] + (int)$prop['build_cost'];
                    $current_val = (int)round($principal * (1 + ($growth_rate * $days)));

                    $kid_stat['estate_cost'] += $principal;
                    $kid_stat['estate_value'] += $current_val;
                }
                $kid_stat['estate_profit'] = $kid_stat['estate_value'] - $kid_stat['estate_cost'];
            }

            // E. 任務歷史與星等加總
            $stmt_history = $p_db->query("SELECT stars, earned_minutes FROM task_history WHERE stars IS NOT NULL");
            if ($stmt_history) {
                $history_rows = $stmt_history->fetchAll(PDO::FETCH_ASSOC);
                foreach ($history_rows as $row) {
                    if (trim($row['stars']) === '') continue;

                    $kid_stat['total_tasks'] += 1;
                    $kid_stat['total_earned'] += (int)$row['earned_minutes'];
                    
                    $star_val = (int)$row['stars'];
                    if ($star_val === 3) { $kid_stat['star_3'] += 1; } 
                    elseif ($star_val === 2) { $kid_stat['star_2'] += 1; } 
                    elseif ($star_val === 1) { $kid_stat['star_1'] += 1; }
                }
            }
        }
        $report_data[] = $kid_stat;
    }

} catch (Exception $e) {
    $error_msg = "報表資料讀取失敗：" . $e->getMessage();
}

$report_json = json_encode($report_data, JSON_UNESCAPED_UNICODE);
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>家長統計報表 | 時間大富翁</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #f4f7f6; margin: 0; padding: 0; color: #333; }
        .container { max-width: 1200px; margin: 20px auto; padding: 0 20px; }
        .alert-error { background: #f8d7da; color: #721c24; padding: 10px; border-radius: 4px; margin-bottom: 15px; border: 1px solid #f5c6cb; }
        
        .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
        .summary-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); text-align: center; border-bottom: 4px solid #3498db;}
        .summary-title { font-size: 0.9rem; color: #7f8c8d; margin-bottom: 5px; font-weight: bold;}
        .summary-value { font-size: 1.8rem; font-weight: bold; color: #2c3e50; margin: 0;}
        
        .chart-section { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 20px; }
        .chart-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .chart-card h3 { margin-top: 0; color: #34495e; font-size: 1.1rem; border-bottom: 1px solid #eee; padding-bottom: 10px; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 0.95rem; }
        th, td { padding: 10px; text-align: center; border-bottom: 1px solid #eee; }
        th { background-color: #f8f9fa; color: #2c3e50; }
        td:first-child, th:first-child { text-align: left; }
        
        .up { color: #e74c3c; font-weight: bold; } 
        .down { color: #2ecc71; font-weight: bold; }
        .flat { color: #7f8c8d; font-weight: bold; }

        @media (max-width: 768px) {
            .chart-section { grid-template-columns: 1fr; }
            .summary-grid { grid-template-columns: 1fr 1fr; }
        }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container">
    <?php if ($error_msg): ?><div class="alert-error"><?php echo $error_msg; ?></div><?php endif; ?>

    <?php if (empty($report_data)): ?>
        <div style="background: white; padding: 30px; text-align: center; border-radius: 8px;">
            <h3>📊 目前還沒有任何玩家資料</h3>
            <p style="color: #7f8c8d;">請先至「成員管理」新增小孩帳號，並開始指派與驗收任務。</p>
        </div>
    <?php else: ?>
        
        <?php 
            $total_family_wallet = 0;
            $total_family_bank = 0;
            $total_family_stock = 0;
            $total_family_estate = 0;
            $total_family_tasks = 0;
            foreach ($report_data as $d) {
                $total_family_wallet += $d['wallet_balance'];
                $total_family_bank += $d['bank_balance'];
                $total_family_stock += $d['stock_value'];
                $total_family_estate += $d['estate_value'];
                $total_family_tasks += $d['total_tasks'];
            }
        ?>

        <div class="summary-grid">
            <div class="summary-card" style="border-color: #e74c3c;">
                <div class="summary-title">任務完成總數</div>
                <div class="summary-value"><?php echo $total_family_tasks; ?> <span style="font-size:1rem;">次</span></div>
            </div>
            <div class="summary-card" style="border-color: #27ae60;">
                <div class="summary-title">流動現金 (錢包)</div>
                <div class="summary-value"><?php echo number_format($total_family_wallet); ?> <span style="font-size:1rem;">分</span></div>
            </div>
            <div class="summary-card" style="border-color: #2980b9;">
                <div class="summary-title">定存資產 (銀行)</div>
                <div class="summary-value"><?php echo number_format($total_family_bank); ?> <span style="font-size:1rem;">分</span></div>
            </div>
            <div class="summary-card" style="border-color: #f39c12;">
                <div class="summary-title">大盤資產 (股市)</div>
                <div class="summary-value"><?php echo number_format($total_family_stock); ?> <span style="font-size:1rem;">分</span></div>
            </div>
            <div class="summary-card" style="border-color: #8e44ad;">
                <div class="summary-title">實體資產 (房市)</div>
                <div class="summary-value"><?php echo number_format($total_family_estate); ?> <span style="font-size:1rem;">分</span></div>
            </div>
        </div>

        <div class="chart-section">
            <div class="chart-card">
                <h3>💰 玩家四維資產分佈長條圖</h3>
                <canvas id="wealthChart"></canvas>
            </div>
            <div class="chart-card">
                <h3>⭐ 家庭整體任務品質</h3>
                <canvas id="starChart"></canvas>
            </div>
        </div>

        <div class="chart-card" style="overflow-x: auto;">
            <h3>📑 玩家詳細戰力與理財分析表</h3>
            <table>
                <thead>
                    <tr>
                        <th>玩家暱稱</th>
                        <th>錢包現金</th>
                        <th>銀行存款</th>
                        <th>股市現值</th>
                        <th>股市損益</th>
                        <th>房產現值</th>
                        <th>房產增值</th>
                        <th>總任務數</th>
                        <th>★★★ 優秀</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($report_data as $d): 
                        $s_class = 'flat'; $s_sign = '';
                        if ($d['stock_profit'] > 0) { $s_class = 'up'; $s_sign = '+'; }
                        elseif ($d['stock_profit'] < 0) { $s_class = 'down'; }

                        $e_class = 'flat'; $e_sign = '';
                        if ($d['estate_profit'] > 0) { $e_class = 'up'; $e_sign = '+'; }
                        elseif ($d['estate_profit'] < 0) { $e_class = 'down'; }
                    ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($d['name']); ?></strong></td>
                        <td style="color: #27ae60; font-weight: bold;"><?php echo number_format($d['wallet_balance']); ?></td>
                        <td style="color: #2980b9; font-weight: bold;"><?php echo number_format($d['bank_balance']); ?></td>
                        <td style="color: #f39c12; font-weight: bold;"><?php echo number_format($d['stock_value'], 1); ?></td>
                        <td class="<?php echo $s_class; ?>"><?php echo $s_sign . number_format($d['stock_profit'], 1); ?></td>
                        <td style="color: #8e44ad; font-weight: bold;"><?php echo number_format($d['estate_value']); ?></td>
                        <td class="<?php echo $e_class; ?>"><?php echo $e_sign . number_format($d['estate_profit']); ?></td>
                        <td><?php echo $d['total_tasks']; ?></td>
                        <td style="color: #f39c12; font-weight: bold;"><?php echo $d['star_3']; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

    <?php endif; ?>
</div>

<script>
    const rawData = <?php echo $report_json; ?>;
    
    if (rawData.length > 0) {
        const names = rawData.map(d => d.name);
        const wallets = rawData.map(d => d.wallet_balance);
        const banks = rawData.map(d => d.bank_balance);
        const stocks = rawData.map(d => d.stock_value);
        const estates = rawData.map(d => d.estate_value);

        const ctxWealth = document.getElementById('wealthChart').getContext('2d');
        new Chart(ctxWealth, {
            type: 'bar',
            data: {
                labels: names,
                datasets: [
                    {
                        label: '錢包現金',
                        data: wallets,
                        backgroundColor: 'rgba(39, 174, 96, 0.7)',
                        borderColor: 'rgba(39, 174, 96, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '銀行存款',
                        data: banks,
                        backgroundColor: 'rgba(41, 128, 185, 0.7)',
                        borderColor: 'rgba(41, 128, 185, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '大盤股市',
                        data: stocks,
                        backgroundColor: 'rgba(243, 156, 18, 0.7)',
                        borderColor: 'rgba(243, 156, 18, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '實體房產',
                        data: estates,
                        backgroundColor: 'rgba(142, 68, 173, 0.7)',
                        borderColor: 'rgba(142, 68, 173, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    x: { stacked: true },
                    y: { stacked: true, beginAtZero: true }
                }
            }
        });

        let total3 = 0, total2 = 0, total1 = 0;
        rawData.forEach(d => {
            total3 += parseInt(d.star_3) || 0;
            total2 += parseInt(d.star_2) || 0;
            total1 += parseInt(d.star_1) || 0;
        });

        const ctxStar = document.getElementById('starChart').getContext('2d');
        new Chart(ctxStar, {
            type: 'doughnut',
            data: {
                labels: ['★★★ 優秀', '★★ 滿意', '★ 待加強'],
                datasets: [{
                    data: [total3, total2, total1],
                    backgroundColor: [
                        'rgba(241, 196, 15, 0.8)',
                        'rgba(52, 152, 219, 0.8)',
                        'rgba(231, 76, 60, 0.8)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });
    }
</script>

</body>
</html>