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

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

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

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

try {
    EstateEngine::processDailySettlement($mysql_db);

    $global_settings = $mysql_db->query("SELECT * FROM estate_global_settings WHERE id = 1")->fetch();
    $base_land_price = (int)$global_settings['base_land_price'];
    $growth_rate = (float)$global_settings['daily_value_growth_rate']; 
    $tax_rate = (float)$global_settings['daily_land_tax_rate']; 

    $cities_raw = $mysql_db->query("SELECT * FROM estate_cities WHERE is_active = 1 ORDER BY price_multiplier DESC")->fetchAll();
    $cities = []; foreach($cities_raw as $c) $cities[$c['id']] = $c;

    $buildings_raw = $mysql_db->query("SELECT * FROM estate_buildings WHERE is_active = 1 ORDER BY build_cost ASC")->fetchAll();
    $buildings = []; foreach($buildings_raw as $b) $buildings[$b['id']] = $b;
    $ind_map = ['food'=>'食', 'clothing'=>'衣', 'education'=>'育', 'entertainment'=>'樂', 'housing'=>'住', 'transport'=>'行'];

    $upgrade_paths_raw = $mysql_db->query("SELECT * FROM estate_upgrade_paths")->fetchAll();
    $upgrade_map = [];
    foreach ($upgrade_paths_raw as $up) {
        $fid = $up['from_building_id'];
        if (!isset($upgrade_map[$fid])) $upgrade_map[$fid] = [];
        $upgrade_map[$fid][] = $up;
    }

    $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);
    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS estate_properties (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        city_id INTEGER,
        city_name TEXT,
        land_purchase_price INTEGER,
        building_id INTEGER DEFAULT 0,
        building_name TEXT DEFAULT '',
        build_cost INTEGER DEFAULT 0,
        demolish_cost INTEGER DEFAULT 0,
        purchase_date TEXT,
        total_revenue INTEGER DEFAULT 0
    )");
    
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN custom_name TEXT DEFAULT ''"); } catch (Exception $e) {}
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN last_revenue INTEGER DEFAULT 0"); } catch (Exception $e) {}
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN last_cost INTEGER DEFAULT 0"); } catch (Exception $e) {}
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN last_profit INTEGER DEFAULT 0"); } catch (Exception $e) {}
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN total_profit INTEGER DEFAULT 0"); } catch (Exception $e) {}

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        $action = $_POST['action'];
        $wallet_data = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1")->fetch();
        $current_wallet = $wallet_data ? (int)$wallet_data['balance_minutes'] : 0;

        if ($action === 'buy_land') {
            $cid = (int)$_POST['city_id'];
            if (!isset($cities[$cid])) { $error_msg = "該地段不存在或已停售！"; } 
            else {
                $city = $cities[$cid];
                $land_price = (int)round($base_land_price * $city['price_multiplier']);
                if ($current_wallet < $land_price) { $error_msg = "餘額不足！購買這塊土地需要 {$land_price} 分鐘！"; } 
                else {
                    $sqlite_db->beginTransaction();
                    try {
                        $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $land_price");
                        $stmt_ins = $sqlite_db->prepare("INSERT INTO estate_properties (city_id, city_name, land_purchase_price, purchase_date) VALUES (?, ?, ?, ?)");
                        $stmt_ins->execute([$cid, $city['city_name'], $land_price, $today_date]);
                        $desc = "🏘️ 房市交易：購買了【{$city['city_name']}】的土地，花費 {$land_price} 分鐘。";
                        $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('buy_land', ?, ?)")->execute([-$land_price, $desc]);
                        $sqlite_db->commit();
                        $success_msg = "🎉 恭喜成為地主！成功買下【{$city['city_name']}】的土地！";
                    } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "交易失敗：".$e->getMessage(); }
                }
            }
        }
        elseif ($action === 'build') {
            $pid = (int)$_POST['property_id'];
            $bid = (int)$_POST['building_id'];
            $custom_name = trim($_POST['custom_name']);
            
            $prop = $sqlite_db->prepare("SELECT * FROM estate_properties WHERE id = ?");
            $prop->execute([$pid]);
            $my_prop = $prop->fetch();

            if (!$my_prop || $my_prop['building_id'] > 0) { 
                $error_msg = "這塊土地已經有蓋東西了，或者土地不存在！"; 
            } elseif (!isset($buildings[$bid])) { 
                $error_msg = "該建物不存在或已下架！"; 
            } elseif ($buildings[$bid]['allow_new_build'] == 0) { 
                $error_msg = "此為進階建物，無法直接在空地建造，必須透過「產業升級」取得！";
            } else {
                $b = $buildings[$bid];
                $cost = (int)$b['build_cost'];
                if (empty($custom_name)) $custom_name = $b['building_name']; 
                
                if ($current_wallet < $cost) { $error_msg = "餘額不足！營建需要 {$cost} 分鐘！"; } 
                else {
                    $sqlite_db->beginTransaction();
                    try {
                        $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $cost");
                        $stmt_up = $sqlite_db->prepare("UPDATE estate_properties SET building_id=?, building_name=?, custom_name=?, build_cost=?, demolish_cost=? WHERE id=?");
                        $stmt_up->execute([$bid, $b['building_name'], $custom_name, $cost, $b['demolish_cost'], $pid]);
                        $desc = "🏗️ 營建發包：在【{$my_prop['city_name']}】蓋了【{$custom_name}】，花費 {$cost} 分鐘。";
                        $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('build', ?, ?)")->execute([-$cost, $desc]);
                        $sqlite_db->commit();
                        $success_msg = "🏗️ 完工大吉！【{$custom_name}】已成功落成！";
                    } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "營建失敗：".$e->getMessage(); }
                }
            }
        }
        elseif ($action === 'upgrade') {
            $pid = (int)$_POST['property_id'];
            $path_id = (int)$_POST['path_id'];
            
            $path_stmt = $mysql_db->prepare("SELECT * FROM estate_upgrade_paths WHERE id = ?");
            $path_stmt->execute([$path_id]);
            $path = $path_stmt->fetch();

            $prop = $sqlite_db->prepare("SELECT * FROM estate_properties WHERE id = ?");
            $prop->execute([$pid]);
            $my_prop = $prop->fetch();

            if ($path && $my_prop && $my_prop['building_id'] == $path['from_building_id']) {
                $cost = (int)$path['upgrade_cost'];
                if ($current_wallet < $cost) {
                    $error_msg = "餘額不足！升級工程需要 {$cost} 分鐘！";
                } else {
                    $new_b = $buildings[$path['to_building_id']] ?? null;
                    if ($new_b) {
                        $sqlite_db->beginTransaction();
                        try {
                            $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $cost");
                            $new_total_build_cost = $my_prop['build_cost'] + $cost;
                            $stmt_up = $sqlite_db->prepare("UPDATE estate_properties SET building_id=?, building_name=?, build_cost=?, demolish_cost=? WHERE id=?");
                            $stmt_up->execute([$new_b['id'], $new_b['building_name'], $new_total_build_cost, $new_b['demolish_cost'], $pid]);
                            
                            $desc = "🚀 產業升級：將【{$my_prop['custom_name']}】進化升級為【{$new_b['building_name']}】，花費 {$cost} 分鐘。";
                            $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('upgrade_building', ?, ?)")->execute([-$cost, $desc]);
                            $sqlite_db->commit();
                            $success_msg = "🚀 升級成功！您的產業已進化為【{$new_b['building_name']}】！";
                        } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "升級失敗：".$e->getMessage(); }
                    }
                }
            } else {
                $error_msg = "升級路徑錯誤或條件不符！";
            }
        }
        // ★ 核心升級：完美的降級/拆除邏輯
        elseif ($action === 'demolish') {
            $pid = (int)$_POST['property_id'];
            $prop = $sqlite_db->prepare("SELECT * FROM estate_properties WHERE id = ?");
            $prop->execute([$pid]);
            $my_prop = $prop->fetch();

            if (!$my_prop || $my_prop['building_id'] == 0) { 
                $error_msg = "這塊土地上沒有建築物可以操作！"; 
            } else {
                $d_cost = (int)$my_prop['demolish_cost'];
                if ($current_wallet < $d_cost) { 
                    $error_msg = "餘額不足！工程需要 {$d_cost} 分鐘！"; 
                } else {
                    $sqlite_db->beginTransaction();
                    try {
                        $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $d_cost");
                        
                        // 檢查是否有上一階建築可以退回
                        $prev_stmt = $mysql_db->prepare("SELECT from_building_id FROM estate_upgrade_paths WHERE to_building_id = ? LIMIT 1");
                        $prev_stmt->execute([$my_prop['building_id']]);
                        $prev_id = $prev_stmt->fetchColumn();

                        if ($prev_id && isset($buildings[$prev_id])) {
                            // 有上一階 -> 執行降級
                            $new_b = $buildings[$prev_id];
                            $stmt_up = $sqlite_db->prepare("UPDATE estate_properties SET building_id=?, building_name=?, build_cost=?, demolish_cost=?, last_revenue=0, last_cost=0, last_profit=0 WHERE id=?");
                            $stmt_up->execute([$prev_id, $new_b['building_name'], $new_b['build_cost'], $new_b['demolish_cost'], $pid]);
                            
                            $desc = "🔨 建物降級：支付 {$d_cost} 分鐘將【{$my_prop['custom_name']}】拆除降級回【{$new_b['building_name']}】。";
                            $success_msg = "🔨 降級完畢！建物已退回至【{$new_b['building_name']}】狀態！";
                        } else {
                            // 無上一階 (LV1) -> 夷為平地
                            $stmt_up = $sqlite_db->prepare("UPDATE estate_properties SET building_id=0, building_name='', custom_name='', build_cost=0, demolish_cost=0, last_revenue=0, last_cost=0, last_profit=0 WHERE id=?");
                            $stmt_up->execute([$pid]);
                            
                            $desc = "🧨 拆除工程：移平了【{$my_prop['custom_name']}】，花費 {$d_cost} 分鐘。";
                            $success_msg = "🧨 拆除完畢！土地已重新空出，可以蓋新大樓了！";
                        }

                        $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('demolish', ?, ?)")->execute([-$d_cost, $desc]);
                        $sqlite_db->commit();
                    } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "操作失敗：".$e->getMessage(); }
                }
            }
        }
        elseif ($action === 'sell_property') {
            $pid = (int)$_POST['property_id'];
            $prop = $sqlite_db->prepare("SELECT * FROM estate_properties WHERE id = ?");
            $prop->execute([$pid]);
            $my_prop = $prop->fetch();

            if ($my_prop) {
                $d1 = new DateTime($my_prop['purchase_date']);
                $d2 = new DateTime($today_date);
                $holding_days = (int)$d1->diff($d2)->format('%a');
                
                $principal = $my_prop['land_purchase_price'] + $my_prop['build_cost'];
                $sell_price = (int)round($principal * (1 + ($growth_rate * $holding_days)));

                $sqlite_db->beginTransaction();
                try {
                    $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $sell_price");
                    $sqlite_db->prepare("DELETE FROM estate_properties WHERE id = ?")->execute([$pid]);
                    
                    $name_str = !empty($my_prop['custom_name']) ? $my_prop['custom_name'] : "空地";
                    $desc = "🤝 房產售出：賣掉【{$my_prop['city_name']} - {$name_str}】，持有 {$holding_days} 天，增值售出得 {$sell_price} 分鐘。";
                    $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('sell_estate', ?, ?)")->execute([$sell_price, $desc]);
                    
                    $sqlite_db->commit();
                    $profit = $sell_price - $principal;
                    $success_msg = "🤝 成交！房產已售出獲得 {$sell_price} 分鐘！（淨賺差價 {$profit} 分）";
                } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "售出失敗：".$e->getMessage(); }
            }
        }
    }

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

    $my_properties = $sqlite_db->query("SELECT * FROM estate_properties ORDER BY purchase_date ASC")->fetchAll();
    
    $total_property_value = 0;
    $built_properties = [];
    foreach ($my_properties as $p) {
        $d1 = new DateTime($p['purchase_date']);
        $d2 = new DateTime($today_date);
        $days = (int)$d1->diff($d2)->format('%a');
        $principal = $p['land_purchase_price'] + $p['build_cost'];
        $total_property_value += (int)round($principal * (1 + ($growth_rate * $days)));
        
        if ($p['building_id'] > 0) {
            $built_properties[] = $p;
        }
    }
    
    usort($built_properties, function($a, $b) { return $b['total_profit'] <=> $a['total_profit']; });
    $top_properties = array_slice($built_properties, 0, 3);

} 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, maximum-scale=1.0, user-scalable=no">
    <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; }
        .wallet-card { background: linear-gradient(135deg, #16a085 0%, #2ecc71 100%); border-radius: 15px; padding: 20px; text-align: center; color: white; box-shadow: 0 4px 10px rgba(46, 204, 113, 0.3); margin-bottom: 20px; }
        .wallet-balance { font-size: 2.5rem; font-weight: bold; margin: 5px 0; line-height: 1; }
        .tabs { display: flex; background: #e0e0e0; border-radius: 10px; overflow: hidden; margin-bottom: 20px; }
        .tab-btn { flex: 1; padding: 12px 0; text-align: center; font-weight: bold; cursor: pointer; color: #7f8c8d; transition: 0.3s; font-size: 0.95rem; }
        .tab-btn.active { background: #2c3e50; color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .card { background: white; border-radius: 12px; padding: 20px 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); margin-bottom: 25px; position: relative; border-bottom: 4px solid #bdc3c7;}
        .card-title { font-weight: bold; font-size: 1.1rem; color: #2c3e50; margin-bottom: 12px; border-bottom: 1px dashed #eee; padding-bottom: 8px; }
        .info-row { display: flex; justify-content: space-between; font-size: 0.9rem; margin-bottom: 5px; color: #555; }
        .highlight { font-weight: bold; color: #e67e22; }
        .btn-action { display: flex; flex-direction: column; justify-content: center; align-items: center; border: none; padding: 10px; border-radius: 6px; font-weight: bold; cursor: pointer; width: 100%; transition: 0.2s; line-height: 1.4; color: white;}
        .btn-action:hover { opacity: 0.9; }
        .btn-danger { background: #e74c3c; }
        .btn-warning { background: #f39c12; }
        .btn-success { background: #27ae60; }
        .btn-upgrade { background: #8e44ad; }
        .action-row { display: flex; gap: 10px; margin-top: 15px; }
        .action-row form { flex: 1; margin: 0; }
        .action-row .btn-action { height: 100%; }
        .input-custom { width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 0.95rem; box-sizing:border-box;}
        select.build-select { width: 100%; padding: 8px; margin-top: 8px; border: 1px solid #ccc; border-radius: 6px; font-size: 0.95rem; box-sizing:border-box;}
        .badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: bold; color: white; }
        .badge-empty { background: #95a5a6; }
        .badge-built { background: #8e44ad; }
        .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; }
        .empty-hint { text-align: center; color: #95a5a6; padding: 20px; font-size: 0.9rem; background: #fff; border-radius: 10px; border: 1px dashed #ccc;}
        .report-box-empty { background:#fef9e7; padding:10px; border-radius:8px; margin:10px 0; border:1px dashed #f39c12; font-size:0.85rem; }
        .report-box-built { background:#e8f8f5; padding:10px; border-radius:8px; margin:10px 0; border:1px dashed #1abc9c; font-size:0.85rem; }
        .rank-card { background: linear-gradient(to right, #fff, #fef9e7); border-radius: 10px; padding: 15px; margin-bottom: 25px; border: 1px solid #f39c12; }
        .rank-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px dashed #eee; font-size: 0.9rem;}
        .rank-item:last-child { border-bottom: none; padding-bottom: 0; }
        .medal-1 { font-size: 1.2rem; margin-right: 5px; }
        .upgrade-section { background:#f4ecf7; padding:12px; border-radius:8px; margin-top:15px; border:1px dashed #9b59b6; }
    </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="wallet-card">
        <p style="margin:0; font-size: 0.9rem; opacity:0.9;">我的不動產總現值</p>
        <p class="wallet-balance"><?php echo number_format($total_property_value); ?> <span style="font-size:1rem;">分</span></p>
        <div style="background: rgba(0,0,0,0.2); border-radius: 20px; padding: 5px 15px; display: inline-block; font-size: 0.85rem; margin-top: 5px;">
            👛 錢包可用現金：<strong><?php echo number_format($current_wallet); ?></strong> 分
        </div>
    </div>

    <div class="tabs">
        <div class="tab-btn active" onclick="switchTab('tab-my')">🏘️ 我的地產</div>
        <div class="tab-btn" onclick="switchTab('tab-market')">🗺️ 開發新土地</div>
    </div>

    <div id="tab-my" class="tab-content active">
        
        <?php if (count($top_properties) > 0): ?>
            <div class="rank-card">
                <div style="font-weight:bold; color:#d35400; margin-bottom:10px; font-size:1rem;">🏆 旗下金雞母排行榜</div>
                <?php foreach($top_properties as $idx => $rp): 
                    $medal = ($idx == 0) ? '🥇' : (($idx == 1) ? '🥈' : '🥉');
                ?>
                    <div class="rank-item">
                        <div><span class="medal-1"><?php echo $medal; ?></span> <b><?php echo htmlspecialchars($rp['custom_name']); ?></b> <span style="font-size:0.75rem; color:#7f8c8d;">(<?php echo htmlspecialchars($rp['city_name']); ?>)</span></div>
                        <div style="color:#27ae60; font-weight:bold;">累計賺 <?php echo number_format($rp['total_profit']); ?> 分</div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (count($my_properties) === 0): ?>
            <div class="empty-hint">您還沒有任何房地產，趕快去隔壁的「開發新土地」買一塊地吧！</div>
        <?php else: ?>
            <?php foreach ($my_properties as $p): 
                $d1 = new DateTime($p['purchase_date']);
                $d2 = new DateTime($today_date);
                $holding_days = (int)$d1->diff($d2)->format('%a');
                $principal = $p['land_purchase_price'] + $p['build_cost'];
                $current_value = (int)round($principal * (1 + ($growth_rate * $holding_days)));
                
                $bid = $p['building_id'];
                $has_upgrade = isset($upgrade_map[$bid]);
            ?>
                <div class="card">
                    <div class="card-title">
                        <?php if ($p['building_id'] > 0): 
                            // ★ 取得當前建物的等級
                            $curr_b = $buildings[$bid] ?? null;
                            $lvl_str = $curr_b ? "LV.{$curr_b['building_level']} " : "";
                        ?>
                            🏢 <?php echo htmlspecialchars($p['custom_name']); ?>
                            <div style="font-size:0.8rem; color:#7f8c8d; margin-top:4px; font-weight:normal;">
                                (<?php echo $lvl_str . htmlspecialchars($p['building_name']); ?>) -📍 <?php echo htmlspecialchars($p['city_name']); ?>
                            </div>
                            <span class="badge badge-built" style="position:absolute; top:15px; right:15px;">營運中</span>
                        <?php else: ?>
                            📍 <?php echo htmlspecialchars($p['city_name']); ?> - <span style="color:#95a5a6;">空地</span>
                            <span class="badge badge-empty" style="position:absolute; top:15px; right:15px;">尚未開發</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="info-row" style="margin-top:10px;"><span>持有天數：</span><span><?php echo $holding_days; ?> 天</span></div>
                    <div class="info-row"><span>累積投入本金：</span><span><?php echo number_format($principal); ?> 分</span></div>
                    <div class="info-row"><span>抗通膨現值：</span><span class="highlight"><?php echo number_format($current_value); ?> 分</span></div>
                    
                    <?php if ($p['building_id'] > 0): ?>
                        <div class="report-box-built">
                            <div style="margin-bottom:5px;">📊 <b>昨日財報：</b></div>
                            <div>
                                營收 <span style="color:#27ae60;">+<?php echo $p['last_revenue']; ?></span> | 
                                成本 <span style="color:#e74c3c;">-<?php echo $p['last_cost']; ?></span> ➔ 
                                淨利 <strong style="color:<?php echo $p['last_profit']>=0?'#27ae60':'#e74c3c'; ?>;">
                                    <?php echo ($p['last_profit']>0?'+':'').$p['last_profit']; ?> 分
                                </strong>
                            </div>
                        </div>

                        <?php if ($has_upgrade): ?>
                            <div class="upgrade-section">
                                <div style="font-weight:bold; color:#8e44ad; margin-bottom:8px; font-size:0.95rem;">🚀 產業升級藍圖</div>
                                <?php foreach ($upgrade_map[$bid] as $up): 
                                    $target_b = $buildings[$up['to_building_id']] ?? null;
                                    if ($target_b):
                                ?>
                                    <form method="POST" onsubmit="return confirm('確定要花費 <?php echo $up['upgrade_cost']; ?> 分鐘，將產業進化為【<?php echo $target_b['building_name']; ?>】嗎？');" style="margin-bottom:8px;">
                                        <input type="hidden" name="action" value="upgrade">
                                        <input type="hidden" name="property_id" value="<?php echo $p['id']; ?>">
                                        <input type="hidden" name="path_id" value="<?php echo $up['id']; ?>">
                                        <button type="submit" class="btn-action btn-upgrade" style="flex-direction:row; justify-content:space-between; padding:8px 12px;">
                                            <span>🔜 升級為 LV.<?php echo $target_b['building_level']; ?> - <?php echo htmlspecialchars($target_b['building_name']); ?></span>
                                            <span style="background:rgba(0,0,0,0.2); padding:2px 8px; border-radius:10px;">需 <?php echo number_format($up['upgrade_cost']); ?> 分</span>
                                        </button>
                                    </form>
                                <?php endif; endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <div class="action-row">
                            <?php 
                            // ★ 判斷目前是否有上一階可以降級
                            $has_prev = false;
                            foreach($upgrade_paths_raw as $up_path) {
                                if ($up_path['to_building_id'] == $p['building_id']) { $has_prev = true; break; }
                            }
                            $demolish_text = $has_prev ? '🔨 降級建物' : '🧨 拆除建物';
                            $demolish_action = $has_prev ? '確定要付費將建物降級嗎？' : '確定要付拆除費把它推平嗎？';
                            ?>
                            <form method="POST" onsubmit="return confirm('<?php echo $demolish_action; ?>');">
                                <input type="hidden" name="action" value="demolish">
                                <input type="hidden" name="property_id" value="<?php echo $p['id']; ?>">
                                <button type="submit" class="btn-action btn-danger">
                                    <?php echo $demolish_text; ?><br><span style="font-size:0.75rem; font-weight:normal; margin-top:2px;">(支付 <?php echo number_format($p['demolish_cost']); ?> 分)</span>
                                </button>
                            </form>
                            <form method="POST" onsubmit="return confirm('確定要把這個地產變現賣掉嗎？系統會用加上通膨增值的價格收購！');">
                                <input type="hidden" name="action" value="sell_property">
                                <input type="hidden" name="property_id" value="<?php echo $p['id']; ?>">
                                <button type="submit" class="btn-action btn-warning">
                                    🤝 整包售出<br><span style="font-size:0.75rem; font-weight:normal; margin-top:2px;">(回收 <?php echo number_format($current_value); ?> 分)</span>
                                </button>
                            </form>
                        </div>
                    <?php else: ?>
                        <div class="report-box-empty">
                            📊 <b>昨日財報：</b> 未開發空地稅 <span style="color:#e74c3c;">-<?php echo round($p['land_purchase_price'] * $tax_rate); ?> 分</span>
                        </div>

                        <form method="POST" style="margin-top:10px; background:#e8f8f5; padding:10px; border-radius:6px; border:1px solid #1abc9c;">
                            <input type="hidden" name="action" value="build">
                            <input type="hidden" name="property_id" value="<?php echo $p['id']; ?>">
                            <strong style="color:#16a085; font-size:0.9rem;">🛠️ 營建發包中心</strong>
                            <input type="text" name="custom_name" class="input-custom" placeholder="為您的產業命名 (例如: 大船頭停車場)" required>
                            <select name="building_id" class="build-select" required>
                                <option value="">-- 選擇要蓋的建物範本 --</option>
                                <?php foreach($buildings as $b): ?>
                                    <?php if ($b['allow_new_build'] == 1): ?>
                                        <option value="<?php echo $b['id']; ?>">LV.<?php echo $b['building_level']; ?> <?php echo $b['building_name']; ?> (造價: <?php echo number_format($b['build_cost']); ?> 分)</option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn-action btn-success" onclick="return confirm('確定要發包建造嗎？');" style="margin-top:10px; padding:10px;">開始建造</button>
                        </form>
                        
                        <div style="margin-top: 15px;">
                            <form method="POST" onsubmit="return confirm('確定要把這塊空地賣掉嗎？');">
                                <input type="hidden" name="action" value="sell_property">
                                <input type="hidden" name="property_id" value="<?php echo $p['id']; ?>">
                                <button type="submit" class="btn-action btn-warning">
                                    🤝 空地售出<br><span style="font-size:0.75rem; font-weight:normal; margin-top:2px;">(回收 <?php echo number_format($current_value); ?> 分)</span>
                                </button>
                            </form>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <div id="tab-market" class="tab-content">
        <div style="background: #fff3e0; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 0.85rem; color: #e67e22; border: 1px dashed #f39c12; line-height: 1.5;">
            💡 <b>置產訣竅：</b> 各縣市有不同的地價與「產業加權」，請選擇潛力地段買下空地。<br>
            ⚠️ <b>注意：</b> 若土地未開發，每日需繳納「未開發空地稅」，請盡速蓋房創造現金流！
        </div>

        <?php foreach ($cities as $c): 
            $land_price = (int)round($base_land_price * $c['price_multiplier']);
            $base_mult = (float)$c['price_multiplier'];
            $industries = [
                '食' => (float)$c['food_mult'],
                '衣' => (float)$c['clothing_mult'],
                '育' => (float)$c['education_mult'],
                '樂' => (float)$c['entertainment_mult'],
                '住' => (float)$c['housing_mult'],
                '行' => (float)$c['transport_mult']
            ];
            
            $strong = []; $weak = []; $avg = [];
            foreach ($industries as $name => $val) {
                if ($val > $base_mult) { $strong[] = "{$name}(" . number_format($val, 2) . "x)"; }
                elseif ($val < $base_mult) { $weak[] = "{$name}(" . number_format($val, 2) . "x)"; }
                else { $avg[] = $name; }
            }
            
            $trait_str = "";
            if (!empty($strong)) $trait_str .= "<div style='color:#e67e22; margin-bottom:3px;'>🌟 <b>推薦產業：</b>" . implode(', ', $strong) . "</div>";
            if (!empty($weak)) $trait_str .= "<div style='color:#7f8c8d; margin-bottom:3px;'>⚠️ <b>利潤較弱：</b>" . implode(', ', $weak) . "</div>";
            if (!empty($avg) && empty($strong) && empty($weak)) $trait_str = "<div style='color:#3498db;'>⚖️ 依地價基準 ({$base_mult}x) 發展</div>";
        ?>
            <div class="card" style="border-left: 5px solid #3498db;">
                <div class="card-title">📍 <?php echo htmlspecialchars($c['city_name']); ?></div>
                <div class="info-row"><span>土地公告價：</span><span class="highlight"><?php echo number_format($land_price); ?> 分</span></div>
                <div class="info-row"><span>未開發空地稅：</span><span style="color:#e74c3c;">-<?php echo round($land_price * $tax_rate); ?> 分/日</span></div>
                <div class="info-row" style="display:block; margin-top:8px;">
                    <div style="margin-bottom:3px; color:#555;">當地產業特色分析：</div>
                    <div style="font-size:0.85rem; background:#f9f9f9; padding:8px; border-radius:4px; border:1px solid #eee;">
                        <?php echo $trait_str; ?>
                    </div>
                </div>
                
                <form method="POST" style="margin-top:10px;" onsubmit="return confirm('確定要買下這塊土地嗎？買下後若不開發，每天都要繳空地稅喔！');">
                    <input type="hidden" name="action" value="buy_land">
                    <input type="hidden" name="city_id" value="<?php echo $c['id']; ?>">
                    <button type="submit" class="btn-action" style="background:#3498db; padding:12px;">🎯 買下空地 (付 <?php echo number_format($land_price); ?> 分)</button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    function switchTab(tabId) {
        document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
        document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
        document.getElementById(tabId).classList.add('active');
        document.querySelector(`.tab-btn[onclick="switchTab('${tabId}')"]`).classList.add('active');
    }
</script>

</body>
</html>