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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'player') { header("Location: ../login.php"); exit; }

$player_id = $_SESSION['user_id'];
$success_msg = ''; $error_msg = '';

try {
    StockEngine::updateDailyPrices($mysql_db);

    $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);
    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS stock_portfolio (id INTEGER PRIMARY KEY AUTOINCREMENT, stock_id INTEGER UNIQUE, stock_code TEXT, stock_name TEXT, total_shares INTEGER DEFAULT 0, average_cost REAL DEFAULT 0.0)");
    try { $sqlite_db->exec("ALTER TABLE stock_portfolio ADD COLUMN total_dividends REAL DEFAULT 0.0"); } catch (Exception $e) {}

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        $action = $_POST['action'];
        $stock_id = (int)$_POST['stock_id'];
        $shares_input = $_POST['shares']; 
        
        $stmt_s = $mysql_db->prepare("SELECT * FROM global_stocks WHERE id = :id AND is_active = 1");
        $stmt_s->execute([':id' => $stock_id]);
        $stock_market_data = $stmt_s->fetch();
        
        $stmt_w = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1");
        $current_wallet = (int)$stmt_w->fetch()['balance_minutes'];

        if (!$stock_market_data) { 
            $error_msg = "該檔股票目前暫停交易或已下市！"; 
        } elseif (!is_numeric($shares_input) || $shares_input <= 0 || $shares_input > 100000) { 
            $error_msg = "🚨 交易異常：請輸入正確的股數（每次交易上限為 100,000 股）！"; 
        } else {
            $shares = (int)$shares_input;
            
            if ($action === 'buy') {
                $price = (float)$stock_market_data['current_price'];
                $total_cost = (int)round($shares * $price); 
                
                if ($total_cost <= 0) {
                    $error_msg = "🚨 交易計算異常，已被系統攔截！";
                } elseif ($current_wallet < $total_cost) { 
                    $error_msg = "餘額不足！購買 {$shares} 股需要 {$total_cost} 分鐘，你只有 {$current_wallet} 分鐘。"; 
                } else {
                    $sqlite_db->beginTransaction();
                    try {
                        $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $total_cost");
                        $stmt_port = $sqlite_db->prepare("SELECT * FROM stock_portfolio WHERE stock_id = :id");
                        $stmt_port->execute([':id' => $stock_id]);
                        $current_hold = $stmt_port->fetch();
                        
                        if ($current_hold) {
                            $old_shares = (int)$current_hold['total_shares']; 
                            $old_avg = (float)$current_hold['average_cost'];
                            
                            // ★ 終極防護：負數黑洞自我修復機制
                            if ($old_shares < 0) {
                                $old_shares = 0;
                                $old_avg = 0.0;
                            }
                            
                            $new_shares = $old_shares + $shares; 
                            $new_avg = (($old_shares * $old_avg) + ($shares * $price)) / $new_shares;
                            $sqlite_db->prepare("UPDATE stock_portfolio SET total_shares = :ts, average_cost = :ac WHERE stock_id = :id")->execute([':ts' => $new_shares, ':ac' => round($new_avg, 4), ':id' => $stock_id]);
                        } else {
                            $sqlite_db->prepare("INSERT INTO stock_portfolio (stock_id, stock_code, stock_name, total_shares, average_cost) VALUES (:id, :code, :name, :ts, :ac)")->execute([':id' => $stock_id, ':code' => $stock_market_data['stock_code'], ':name' => $stock_market_data['stock_name'], ':ts' => $shares, ':ac' => $price]);
                        }
                        $log_desc = "📈 買進股票：{$stock_market_data['stock_name']} ({$stock_market_data['stock_code']}) x{$shares}股，成交價: {$price}";
                        $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('stock_buy', :amt, :desc)")->execute([':amt' => -$total_cost, ':desc' => $log_desc]);
                        $sqlite_db->commit();
                        $success_msg = "🎉 買進成功！成功以均價 {$price} 買進 {$shares} 股 【{$stock_market_data['stock_name']}】！";
                    } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "交易失敗：" . $e->getMessage(); }
                }
            }
            elseif ($action === 'sell') {
                $stmt_port = $sqlite_db->prepare("SELECT * FROM stock_portfolio WHERE stock_id = :id");
                $stmt_port->execute([':id' => $stock_id]);
                $current_hold = $stmt_port->fetch();
                
                $hold_shares = $current_hold ? (int)$current_hold['total_shares'] : 0;
                // ★ 防護：賣出時也檢查黑洞
                if ($hold_shares < 0) { $hold_shares = 0; }

                if ($hold_shares < $shares) { 
                    $error_msg = "餘額不足！無法賣出 {$shares} 股！"; 
                } else {
                    $price = (float)$stock_market_data['current_price'];
                    $total_return = (int)round($shares * $price); 
                    
                    if ($total_return <= 0) {
                        $error_msg = "🚨 交易計算異常，已被系統攔截！";
                    } else {
                        $sqlite_db->beginTransaction();
                        try {
                            $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $total_return");
                            $new_shares = $hold_shares - $shares;
                            if ($new_shares == 0) { $sqlite_db->prepare("UPDATE stock_portfolio SET total_shares = 0, average_cost = 0.0 WHERE stock_id = :id")->execute([':id' => $stock_id]); } 
                            else { $sqlite_db->prepare("UPDATE stock_portfolio SET total_shares = :ts WHERE stock_id = :id")->execute([':ts' => $new_shares, ':id' => $stock_id]); }
                            $log_desc = "📉 賣出股票：{$stock_market_data['stock_name']} ({$stock_market_data['stock_code']}) x{$shares}股，成交價: {$price}";
                            $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('stock_sell', :amt, :desc)")->execute([':amt' => $total_return, ':desc' => $log_desc]);
                            $sqlite_db->commit();
                            $success_msg = "💰 賣出成功！回收 {$total_return} 分鐘！";
                        } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "交易失敗：" . $e->getMessage(); }
                    }
                }
            }
        }
    }

    $stmt_wallet = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1");
    $current_wallet = (int)$stmt_wallet->fetch()['balance_minutes'];

    $market_stocks = $mysql_db->query("SELECT * FROM global_stocks WHERE is_active = 1 ORDER BY stock_code ASC")->fetchAll();

    $portfolio_rows = $sqlite_db->query("SELECT * FROM stock_portfolio WHERE total_shares > 0")->fetchAll();
    $my_portfolio = []; foreach ($portfolio_rows as $row) { $my_portfolio[$row['stock_id']] = $row; }

    $total_investment_cost = 0; $total_market_value = 0;    
    foreach ($market_stocks as &$stock) {
        $sid = $stock['id'];
        if (isset($my_portfolio[$sid])) {
            $hold_shares = (int)$my_portfolio[$sid]['total_shares']; 
            $avg_cost = (float)$my_portfolio[$sid]['average_cost']; 
            $current_price = (float)$stock['current_price'];
            $total_div = (float)($my_portfolio[$sid]['total_dividends'] ?? 0.0);
            
            $total_investment_cost += ($hold_shares * $avg_cost); 
            $total_market_value += ($hold_shares * $current_price);
            $stock['my_shares'] = $hold_shares; 
            $stock['my_avg_cost'] = $avg_cost;
            $stock['my_total_dividends'] = $total_div;
        } else {
            $stock['my_shares'] = 0; $stock['my_avg_cost'] = 0.0; $stock['my_total_dividends'] = 0.0;
        }
    } unset($stock); 
    $unrealized_profit = $total_market_value - $total_investment_cost;

} catch (Exception $e) {
    die("證券戶系統載入失敗：" . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>個人時光證券戶 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding-bottom: 30px; }
        .container { padding: 15px; max-width: 600px; margin: 0 auto; }
        .stock-dashboard { background: linear-gradient(135deg, #1f4068 0%, #162447 100%); border-radius: 15px; padding: 20px; color: white; box-shadow: 0 4px 15px rgba(22, 36, 71, 0.4); margin-bottom: 20px; text-align: center; }
        .dashboard-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px; border-top: 1px solid rgba(255,255,255,0.1); padding-top: 15px; }
        .metrics-label { font-size: 0.8rem; opacity: 0.8; margin-bottom: 3px; }
        .metrics-val { font-size: 1.2rem; font-weight: bold; }
        .up { color: #ff4d4d !important; font-weight: bold; }
        .down { color: #2ecc71 !important; font-weight: bold; }
        .flat { color: #f1c40f !important; font-weight: bold; }
        .stock-card { background: white; border-radius: 12px; padding: 15px; margin-bottom: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); transition: 0.2s; }
        .stock-header { display: flex; justify-content: space-between; align-items: center; cursor: pointer; }
        .stock-title { flex: 1; }
        .stock-code-badge { background: #e1b12c; color: #fff; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; margin-right: 5px; }
        .stock-name { font-weight: bold; color: #2c3e50; font-size: 1.05rem; }
        .stock-market-price { text-align: right; margin-right: 15px; }
        .holding-badge { background: #34495e; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.75rem; display: inline-block; margin-top: 4px; }
        .trade-drawer { display: none; background: #f8f9fa; border-top: 1px dashed #ddd; margin-top: 12px; padding-top: 15px; animation: slideDown 0.2s ease-out; }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); } }
        .trade-tabs { display: flex; gap: 10px; margin-bottom: 12px; }
        .trade-tab-btn { flex:1; padding: 8px; border: 1px solid #ccc; background: white; border-radius: 6px; font-weight: bold; cursor: pointer; text-align: center; font-size: 0.9rem;}
        .trade-tab-btn.buy-active { background: #ff4d4d; color: white; border-color: #ff4d4d; }
        .trade-tab-btn.sell-active { background: #2ecc71; color: white; border-color: #2ecc71; }
        .form-row { display: flex; gap: 10px; align-items: center; margin-bottom: 10px; }
        input[type="number"] { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 1rem; text-align: center; }
        .btn-action-submit { color: white; border: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; font-size: 1rem; cursor: pointer; }
        .alert { padding: 12px; border-radius: 8px; margin-bottom: 15px; text-align: center; font-weight: bold; font-size: 0.9rem; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .rules-card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-top: 30px; border: 1px solid #eee; }
        .rules-title { font-size: 1.1rem; color: #8e44ad; margin: 0 0 15px 0; border-bottom: 2px solid #f0f0f0; padding-bottom: 8px;}
        .rules-list { padding-left: 20px; margin: 0; font-size: 0.9rem; color: #555; line-height: 1.6; }
        .rules-list li { margin-bottom: 8px; }
    </style>
</head>
<body>

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

<div class="container">

    <?php if ($error_msg): ?><script>setTimeout(() => { alert("❌ <?php echo str_replace(['"', "\r", "\n"], ['\"', '', ''], $error_msg); ?>"); }, 100);</script><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
    <?php if ($success_msg): ?><script>setTimeout(() => { alert("✅ <?php echo str_replace(['"', "\r", "\n"], ['\"', '', ''], $success_msg); ?>"); }, 100);</script><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>

    <div class="stock-dashboard">
        <p class="metrics-label">📈 證券帳戶未實現總損益</p>
        <?php 
            $profit_class = 'flat'; $sign = '';
            if ($unrealized_profit > 0) { $profit_class = 'up'; $sign = '+'; }
            elseif ($unrealized_profit < 0) { $profit_class = 'down'; }
        ?>
        <p class="metrics-val <?php echo $profit_class; ?>" style="font-size: 2.5rem; margin: 5px 0;">
            <?php echo $sign . number_format($unrealized_profit, 1); ?> <span style="font-size:1rem;">分</span>
        </p>
        
        <div class="dashboard-grid">
            <div>
                <p class="metrics-label">💰 股票目前總現值</p>
                <p class="metrics-val" style="color: #4facfe;"><?php echo number_format($total_market_value, 1); ?> 分</p>
            </div>
            <div>
                <p class="metrics-label">🧱 投資原始總成本</p>
                <p class="metrics-val"><?php echo number_format($total_investment_cost, 1); ?> 分</p>
            </div>
        </div>
        <div style="margin-top:12px; font-size:0.85rem; background:rgba(255,255,255,0.15); padding:6px; border-radius:20px;">
            👛 手邊可用現金（錢包）：<strong><?php echo number_format($current_wallet); ?></strong> 分鐘
        </div>
    </div>

    <h3 style="font-size:1.1rem; color:#2c3e50; margin: 20px 0 10px 0;">🏛️ 全球證券交易所大盤清單</h3>
    
    <?php if (count($market_stocks) > 0): ?>
        <?php foreach ($market_stocks as $s): 
            $change = $s['current_price'] - $s['base_price'];
            $percent = ($s['base_price'] > 0) ? ($change / $s['base_price']) * 100 : 0;
            
            $trend_class = 'flat'; $arrow = ' - ';
            if ($change > 0) { $trend_class = 'up'; $arrow = '▲'; }
            elseif ($change < 0) { $trend_class = 'down'; $arrow = '▼'; }
            
            $rating = $s['rating'] ?? 3;
            $stars_html = str_repeat('★', $rating) . str_repeat('☆', 5 - $rating);
        ?>
            <div class="stock-card" id="stock_row_<?php echo $s['id']; ?>">
                <div class="stock-header" onclick="toggleTradeDrawer(<?php echo $s['id']; ?>)">
                    <div class="stock-title">
                        <span class="stock-code-badge"><?php echo htmlspecialchars($s['stock_code']); ?></span>
                        <span class="stock-name"><?php echo htmlspecialchars($s['stock_name']); ?></span>
                        <span style="color: #f1c40f; font-size: 0.8rem; margin-left: 5px;"><?php echo $stars_html; ?></span>
                        <br>
                        <?php if ($s['my_shares'] > 0): ?>
                            <span class="holding-badge">🎒 持有 <?php echo number_format($s['my_shares']); ?> 股 (均價 <?php echo number_format($s['my_avg_cost'], 1); ?>)</span>
                            <?php if ($s['my_total_dividends'] > 0): ?>
                                <span class="holding-badge" style="background:#27ae60; margin-left:5px;">💰 累計領息 <?php echo number_format($s['my_total_dividends']); ?> 分</span>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <div class="stock-market-price">
                        <strong style="font-size:1.2rem; color:#2c3e50;"><?php echo number_format($s['current_price'], 2); ?></strong><br>
                        <span class="<?php echo $trend_class; ?>" style="font-size:0.8rem;">
                            <?php echo $arrow . ' ' . number_format(abs($change), 2) . ' (' . number_format(abs($percent), 2) . '%)'; ?>
                        </span>
                    </div>
                    <div style="color:#bdc3c7; font-size:1.1rem;">⚡</div>
                </div>

                <div class="trade-drawer" id="drawer_<?php echo $s['id']; ?>">
                    <div class="trade-tabs">
                        <div class="trade-tab-btn buy-active" id="btn_tab_buy_<?php echo $s['id']; ?>" onclick="setTradeMode(<?php echo $s['id']; ?>, 'buy')">買進</div>
                        <div class="trade-tab-btn" id="btn_tab_sell_<?php echo $s['id']; ?>" onclick="setTradeMode(<?php echo $s['id']; ?>, 'sell')">賣出</div>
                    </div>

                    <form method="POST" action="stocks.php">
                        <input type="hidden" name="action" id="action_input_<?php echo $s['id']; ?>" value="buy">
                        <input type="hidden" name="stock_id" value="<?php echo $s['id']; ?>">
                        
                        <div class="form-row">
                            <label style="font-size:0.9rem; color:#555;">交易股數：</label>
                            <input type="number" name="shares" min="1" max="100000" placeholder="最多10萬股" required id="shares_input_<?php echo $s['id']; ?>" oninput="calculateEstimate(<?php echo $s['id']; ?>, <?php echo $s['current_price']; ?>)">
                        </div>
                        
                        <div class="form-row" style="justify-content: space-between; background:#eee; padding:10px; border-radius:6px;">
                            <span style="font-size:0.85rem; color:#555;">💰 預估交易總價：</span>
                            <strong id="estimate_cost_<?php echo $s['id']; ?>" style="color:#2c3e50;">0 分鐘</strong>
                        </div>

                        <div style="text-align: right; margin-top: 10px;">
                            <button type="submit" class="btn-action-submit" id="submit_btn_<?php echo $s['id']; ?>" style="background-color:#ff4d4d;">確認買進股票</button>
                        </div>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="stock-card" style="text-align:center; color:#95a5a6; padding:30px;">市場上目前空空如也，請先去世界政府總部掛牌上市喔！</div>
    <?php endif; ?>

    <div class="rules-card">
        <h4 class="rules-title">💡 股市新手必讀：長期投資與現金流</h4>
        <ul class="rules-list">
            <li><strong>⭐ 基本面評等：</strong> 買股票前請留意公司名稱旁的「星等」，星等越高的優質公司，長期向上的動力越強勁。</li>
            <li><strong>📰 財經消息面：</strong> 請隨時留意首頁的「世界政府廣播頻道」。一旦有重大利多或利空新聞發布，隔天開盤必定會反映在股價上！</li>
            <li><strong>💸 每月初現金配息：</strong> 這是最棒的被動收入！如果公司經營良好 (股價>10)，每月第一天開盤時，會將利潤直接化為「現金股利」發放到你的錢包。</li>
            <li><strong>📉 除息機制：</strong> 為了讓新加入的朋友也買得起股票，發放股利後，股價會自動「除息」變便宜，讓大家都有上車的機會。</li>
        </ul>
    </div>

</div>

<script>
    function toggleTradeDrawer(id) {
        const drawer = document.getElementById('drawer_' + id);
        const isOpen = drawer.style.display === 'block';
        document.querySelectorAll('.trade-drawer').forEach(d => d.style.display = 'none');
        if (!isOpen) {
            drawer.style.display = 'block';
            setTradeMode(id, 'buy'); 
        }
    }

    function setTradeMode(id, mode) {
        const buyTab = document.getElementById('btn_tab_buy_' + id);
        const sellTab = document.getElementById('btn_tab_sell_' + id);
        const actionInput = document.getElementById('action_input_' + id);
        const submitBtn = document.getElementById('submit_btn_' + id);

        actionInput.value = mode;
        
        if (mode === 'buy') {
            buyTab.classList.add('buy-active'); sellTab.classList.remove('sell-active');
            submitBtn.style.backgroundColor = '#ff4d4d'; submitBtn.innerText = '確認買進股票';
        } else {
            buyTab.classList.remove('buy-active'); sellTab.classList.add('sell-active');
            submitBtn.style.backgroundColor = '#2ecc71'; submitBtn.innerText = '確認賣出股票';
        }
        
        const shares = document.getElementById('shares_input_' + id).value;
        if(shares > 0) { document.getElementById('shares_input_' + id).dispatchEvent(new Event('input')); }
    }

    function calculateEstimate(id, price) {
        let shares = document.getElementById('shares_input_' + id).value;
        const display = document.getElementById('estimate_cost_' + id);
        if (shares <= 0 || isNaN(shares)) { display.innerText = "0 分鐘"; return; }
        if (shares > 100000) { display.innerText = "⚠️ 超出交易上限"; display.style.color = 'red'; return; }
        display.style.color = '#2c3e50';
        const estMinutes = Math.round(shares * price);
        display.innerText = estMinutes.toLocaleString() + " 分鐘";
    }
</script>

</body>
</html>