<?php
// ... (與原檔完全相同，只修改了最後幾行的 HTML 顯示)
require_once '../config.php';
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'player') { header("Location: ../login.php"); exit; }
$display_name = $_SESSION['display_name'];
$success_msg = ''; $error_msg = '';

try {
    $stmt_global = $mysql_db->query("SELECT * FROM global_settings WHERE id = 1");
    $global_data = $stmt_global->fetch();
    $interest_rate = $global_data ? (float)$global_data['global_interest_rate'] : 0.05;
    $interest_freq = (isset($global_data['interest_frequency']) && $global_data['interest_frequency'] === 'daily') ? 'daily' : 'weekly';

    $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);
    $sqlite_setup = "CREATE TABLE IF NOT EXISTS time_bank (id INTEGER PRIMARY KEY, balance_minutes INTEGER DEFAULT 0, last_interest_calc DATETIME DEFAULT CURRENT_TIMESTAMP);
        INSERT INTO time_bank (balance_minutes) SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM time_bank);";
    $sqlite_db->exec($sqlite_setup);

    $stmt_bank = $sqlite_db->query("SELECT * FROM time_bank LIMIT 1");
    $bank_info = $stmt_bank->fetch();
    $bank_balance = $bank_info['balance_minutes'];
    
    $last_date_str = substr($bank_info['last_interest_calc'], 0, 10);
    if (empty($last_date_str) || $last_date_str == '0000-00-00') { $last_date_str = date('Y-m-d'); }
    
    $last_dt = new DateTime($last_date_str);
    $now_dt = new DateTime(date('Y-m-d'));
    $periods_passed = 0;

    if ($interest_freq === 'daily') {
        $interval = $last_dt->diff($now_dt);
        $periods_passed = $interval->invert ? 0 : $interval->days;
    } else {
        $last_y = (int)$last_dt->format('o'); $last_w = (int)$last_dt->format('W');
        $now_y = (int)$now_dt->format('o'); $now_w = (int)$now_dt->format('W');
        $last_monday = new DateTime(); $last_monday->setISODate($last_y, $last_w);
        $now_monday = new DateTime(); $now_monday->setISODate($now_y, $now_w);
        $interval = $last_monday->diff($now_monday);
        $periods_passed = $interval->invert ? 0 : floor($interval->days / 7);
    }

    if ($periods_passed >= 1) {
        $interest_earned = 0;
        if ($bank_balance > 0) { $interest_earned = floor($bank_balance * $interest_rate * $periods_passed); }

        $sqlite_db->beginTransaction();
        $new_local_time = date('Y-m-d H:i:s'); 
        
        if ($interest_earned > 0) {
            $sqlite_db->exec("UPDATE time_bank SET balance_minutes = balance_minutes + $interest_earned, last_interest_calc = '$new_local_time'");
            $stmt_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('bank_interest', :amt, '🏦 央行發放利息')");
            $stmt_log->execute([':amt' => $interest_earned]);
            $success_msg = "🎉 恭喜！世界銀行剛剛為您發放了 {$interest_earned} 分鐘的利息！";
            $bank_balance += $interest_earned; 
        } else {
            $sqlite_db->exec("UPDATE time_bank SET last_interest_calc = '$new_local_time'");
        }
        $sqlite_db->commit();
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        // ... (與您原檔提款存款邏輯相同，省略防佔版面) ...
        $action = $_POST['action'];
        $amount = isset($_POST['amount']) ? (int)$_POST['amount'] : 0;
        $stmt_wallet = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1");
        $wallet_balance = $stmt_wallet->fetch()['balance_minutes'];

        if ($action === 'deposit' && $amount > 0) {
            if ($wallet_balance >= $amount) {
                $sqlite_db->beginTransaction();
                $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $amount");
                $sqlite_db->exec("UPDATE time_bank SET balance_minutes = balance_minutes + $amount");
                $stmt_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('bank_deposit', :amt, '💰 存入銀行')");
                $stmt_log->execute([':amt' => -$amount]); 
                $sqlite_db->commit();
                $success_msg = "成功存入 {$amount} 分鐘！";
            } else { $error_msg = "錢包餘額不足，無法存入！"; }
        } elseif ($action === 'withdraw' && $amount > 0) {
            if ($bank_balance >= $amount) {
                $sqlite_db->beginTransaction();
                $sqlite_db->exec("UPDATE time_bank SET balance_minutes = balance_minutes - $amount");
                $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $amount");
                $stmt_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('bank_withdraw', :amt, '🏧 從銀行提款')");
                $stmt_log->execute([':amt' => $amount]);
                $sqlite_db->commit();
                $success_msg = "成功提領 {$amount} 分鐘！";
            } else { $error_msg = "銀行存款不足，無法提領！"; }
        }
    } 

    $stmt_wallet = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1");
    $wallet_balance = $stmt_wallet->fetch()['balance_minutes'];
    $stmt_bank = $sqlite_db->query("SELECT balance_minutes FROM time_bank LIMIT 1");
    $bank_balance = $stmt_bank->fetch()['balance_minutes'];

    $wallet_str = "";
    if ($wallet_balance >= 60) {
        $d = floor($wallet_balance / 1440); $h = floor(($wallet_balance % 1440) / 60); $m = $wallet_balance % 60;
        $parts = []; if ($d>0) $parts[]="{$d}天"; if ($h>0) $parts[]="{$h}小時"; if ($m>0) $parts[]="{$m}分";
        $wallet_str = "≈ " . implode(' ', $parts);
    }
    $bank_str = "";
    if ($bank_balance >= 60) {
        $d = floor($bank_balance / 1440); $h = floor(($bank_balance % 1440) / 60); $m = $bank_balance % 60;
        $parts = []; if ($d>0) $parts[]="{$d}天"; if ($h>0) $parts[]="{$h}小時"; if ($m>0) $parts[]="{$m}分";
        $bank_str = "≈ " . implode(' ', $parts);
    }

    $freq_title = ($interest_freq === 'daily') ? '全球日利率' : '全球週利率';
    $freq_desc  = ($interest_freq === 'daily') ? '每天凌晨' : '每週一凌晨';

} catch (PDOException $e) {
    if (isset($sqlite_db) && $sqlite_db->inTransaction()) $sqlite_db->rollBack();
    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', sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding-bottom: 30px; }
        .container { padding: 15px; max-width: 500px; margin: 20px auto 0 auto; }
        .balance-cards { display: flex; gap: 10px; margin-bottom: 20px; }
        .card-wallet, .card-bank { flex: 1; border-radius: 15px; padding: 20px 10px; text-align: center; color: white; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        .card-wallet { background: linear-gradient(135deg, #f6d365 0%, #fda085 100%); }
        .card-bank { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .card-title { font-size: 0.85rem; opacity: 0.9; margin: 0 0 5px 0; }
        .card-val { font-size: 2.2rem; font-weight: bold; margin: 0; text-shadow: 1px 1px 2px rgba(0,0,0,0.1); }
        .card-convert { font-size: 0.75rem; background: rgba(0,0,0,0.15); display: inline-block; padding: 2px 8px; border-radius: 20px; margin-top: 5px;}
        .trade-box { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 20px; }
        .trade-title { font-size: 1.1rem; color: #2c3e50; margin: 0 0 15px 0; border-bottom: 2px solid #eee; padding-bottom: 10px;}
        .form-group { display: flex; gap: 10px; margin-bottom: 15px; }
        input[type="number"] { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 1.1rem; text-align: center; box-sizing: border-box; width: 100%;}
        .btn-deposit { background-color: #3498db; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; cursor: pointer; flex: 1; }
        .btn-withdraw { background-color: #e67e22; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; cursor: pointer; flex: 1; }
        .alert { padding: 10px; border-radius: 6px; margin-bottom: 15px; text-align: center; font-size: 0.9rem; font-weight: bold; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container">
    <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
    <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>

    <div class="balance-cards">
        <div class="card-wallet">
            <p class="card-title">👛 錢包餘額</p>
            <p class="card-val"><?php echo $wallet_balance; ?></p>
            <?php if ($wallet_str): ?><div class="card-convert"><?php echo $wallet_str; ?></div><?php endif; ?>
        </div>
        <div class="card-bank">
            <p class="card-title">🏦 銀行存款</p>
            <p class="card-val"><?php echo $bank_balance; ?></p>
            <?php if ($bank_str): ?><div class="card-convert"><?php echo $bank_str; ?></div><?php endif; ?>
            <p class="card-title" style="margin-top: 5px;">(<?php echo $freq_title; ?> <?php echo number_format($interest_rate * 100, 1); ?>%)</p>
        </div>
    </div>

    <div class="trade-box">
        <h3 class="trade-title">📝 辦理業務</h3>
        <form method="POST" action="bank.php">
            <div class="form-group">
                <input type="number" name="amount" min="1" placeholder="請輸入分鐘數" required>
            </div>
            <div class="form-group">
                <button type="submit" name="action" value="deposit" class="btn-deposit">📥 存入</button>
                <button type="submit" name="action" value="withdraw" class="btn-withdraw">📤 領回</button>
            </div>
        </form>
        <p style="font-size: 0.8rem; color: #7f8c8d; text-align: center; margin: 0;">※ 存入銀行的時間，<?php echo $freq_desc; ?>會自動產生 <?php echo number_format($interest_rate * 100, 1); ?>% 利息喔！</p>
    </div>
</div>
</body>
</html>