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

if (!isset($_SESSION['super_admin_logged_in']) || $_SESSION['super_admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

$success_msg = '';
$error_msg = '';

// ==========================================
// 0. 自動建立與更新房市資料表
// ==========================================
try {
    $mysql_db->exec("CREATE TABLE IF NOT EXISTS estate_global_settings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        base_land_price INT DEFAULT 3000,
        daily_land_tax_rate DECIMAL(5,4) DEFAULT 0.005,  
        daily_value_growth_rate DECIMAL(5,4) DEFAULT 0.002, 
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    
    $chk_setting = $mysql_db->query("SELECT id FROM estate_global_settings LIMIT 1")->fetch();
    if (!$chk_setting) {
        $mysql_db->exec("INSERT INTO estate_global_settings (base_land_price) VALUES (3000)");
    }

    $mysql_db->exec("CREATE TABLE IF NOT EXISTS estate_cities (
        id INT PRIMARY KEY AUTO_INCREMENT,
        city_name VARCHAR(50) NOT NULL,
        price_multiplier DECIMAL(5,2) DEFAULT 1.0, 
        food_mult DECIMAL(5,2) DEFAULT 1.0,
        clothing_mult DECIMAL(5,2) DEFAULT 1.0,
        education_mult DECIMAL(5,2) DEFAULT 1.0,
        entertainment_mult DECIMAL(5,2) DEFAULT 1.0,
        housing_mult DECIMAL(5,2) DEFAULT 1.0,
        transport_mult DECIMAL(5,2) DEFAULT 1.0,
        is_active TINYINT(1) DEFAULT 1
    )");

    $mysql_db->exec("CREATE TABLE IF NOT EXISTS estate_buildings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        building_name VARCHAR(50) NOT NULL,
        industry_type VARCHAR(20) NOT NULL, 
        build_cost INT NOT NULL, 
        demolish_cost INT NOT NULL, 
        daily_fixed_cost INT NOT NULL, 
        daily_revenue_min INT NOT NULL, 
        daily_revenue_max INT NOT NULL, 
        is_active TINYINT(1) DEFAULT 1
    )");

    try { $mysql_db->exec("ALTER TABLE estate_buildings ADD COLUMN allow_new_build TINYINT(1) DEFAULT 1"); } catch(Exception $e) {}
    // ★ 自動擴充：建物等級標籤
    try { $mysql_db->exec("ALTER TABLE estate_buildings ADD COLUMN building_level INT DEFAULT 1"); } catch(Exception $e) {}

    $mysql_db->exec("CREATE TABLE IF NOT EXISTS estate_upgrade_paths (
        id INT PRIMARY KEY AUTO_INCREMENT,
        from_building_id INT NOT NULL,
        to_building_id INT NOT NULL,
        upgrade_cost INT NOT NULL
    )");
} catch (Exception $e) {
    die("資料庫建立失敗：" . $e->getMessage());
}

// ==========================================
// 1. 處理 POST 表單提交
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        if ($_POST['action'] === 'update_global') {
            $base_price = (int)$_POST['base_land_price'];
            $tax_rate = (float)$_POST['daily_land_tax_rate'] / 100;
            $growth_rate = (float)$_POST['daily_value_growth_rate'] / 100;

            $stmt = $mysql_db->prepare("UPDATE estate_global_settings SET base_land_price = ?, daily_land_tax_rate = ?, daily_value_growth_rate = ? WHERE id = 1");
            $stmt->execute([$base_price, $tax_rate, $growth_rate]);
            $success_msg = "🌍 全國房市大盤參數已更新！";
        }
        elseif ($_POST['action'] === 'save_city') {
            $cid = !empty($_POST['city_id']) ? (int)$_POST['city_id'] : null;
            $name = trim($_POST['city_name']);
            $mult = (float)$_POST['price_multiplier'];
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            $f = (float)$_POST['food_mult']; $c = (float)$_POST['clothing_mult']; $e = (float)$_POST['education_mult'];
            $ent = (float)$_POST['entertainment_mult']; $h = (float)$_POST['housing_mult']; $t = (float)$_POST['transport_mult'];

            if ($cid) {
                $stmt = $mysql_db->prepare("UPDATE estate_cities SET city_name=?, price_multiplier=?, food_mult=?, clothing_mult=?, education_mult=?, entertainment_mult=?, housing_mult=?, transport_mult=?, is_active=? WHERE id=?");
                $stmt->execute([$name, $mult, $f, $c, $e, $ent, $h, $t, $is_active, $cid]);
                $success_msg = "🏙️ 縣市地段【{$name}】已更新！";
            } else {
                $stmt = $mysql_db->prepare("INSERT INTO estate_cities (city_name, price_multiplier, food_mult, clothing_mult, education_mult, entertainment_mult, housing_mult, transport_mult, is_active) VALUES (?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$name, $mult, $f, $c, $e, $ent, $h, $t, $is_active]);
                $success_msg = "🏙️ 縣市地段【{$name}】已成功開發！";
            }
        }
        elseif ($_POST['action'] === 'save_building') {
            $bid = !empty($_POST['building_id']) ? (int)$_POST['building_id'] : null;
            $name = trim($_POST['building_name']);
            $ind = $_POST['industry_type'];
            $b_cost = (int)$_POST['build_cost'];
            $d_cost = (int)$_POST['demolish_cost'];
            $f_cost = (int)$_POST['daily_fixed_cost'];
            $r_min = (int)$_POST['daily_revenue_min'];
            $r_max = (int)$_POST['daily_revenue_max'];
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $allow_new = isset($_POST['allow_new_build']) ? 1 : 0;
            $level = (int)$_POST['building_level']; // ★ 接收等級

            if ($r_min > $r_max) {
                $error_msg = "營收最小區間不可大於最大區間！";
            } else {
                if ($bid) {
                    $stmt = $mysql_db->prepare("UPDATE estate_buildings SET building_name=?, industry_type=?, build_cost=?, demolish_cost=?, daily_fixed_cost=?, daily_revenue_min=?, daily_revenue_max=?, is_active=?, allow_new_build=?, building_level=? WHERE id=?");
                    $stmt->execute([$name, $ind, $b_cost, $d_cost, $f_cost, $r_min, $r_max, $is_active, $allow_new, $level, $bid]);
                    $success_msg = "🏗️ 建物型錄【{$name}】已更新！";
                } else {
                    $stmt = $mysql_db->prepare("INSERT INTO estate_buildings (building_name, industry_type, build_cost, demolish_cost, daily_fixed_cost, daily_revenue_min, daily_revenue_max, is_active, allow_new_build, building_level) VALUES (?,?,?,?,?,?,?,?,?,?)");
                    $stmt->execute([$name, $ind, $b_cost, $d_cost, $f_cost, $r_min, $r_max, $is_active, $allow_new, $level]);
                    $success_msg = "🏗️ 建物型錄【{$name}】已發布核准！";
                }
            }
        }
        elseif ($_POST['action'] === 'save_upgrade_path') {
            $from_id = (int)$_POST['from_building_id'];
            $to_id = (int)$_POST['to_building_id'];
            $cost = (int)$_POST['upgrade_cost'];
            if ($from_id == $to_id) {
                $error_msg = "升級目標不能與原建物相同！";
            } else {
                $stmt = $mysql_db->prepare("INSERT INTO estate_upgrade_paths (from_building_id, to_building_id, upgrade_cost) VALUES (?, ?, ?)");
                $stmt->execute([$from_id, $to_id, $cost]);
                $success_msg = "🔗 轉職升級路線已成功建立！";
            }
        }
        elseif ($_POST['action'] === 'delete_upgrade_path') {
            $path_id = (int)$_POST['path_id'];
            $stmt = $mysql_db->prepare("DELETE FROM estate_upgrade_paths WHERE id = ?");
            $stmt->execute([$path_id]);
            $success_msg = "🔗 轉職升級路線已移除！";
        }
    } catch (Exception $e) {
        $error_msg = "資料庫操作失敗：" . $e->getMessage();
    }
}

// ==========================================
// 2. 撈取顯示資料
// ==========================================
$global_settings = $mysql_db->query("SELECT * FROM estate_global_settings WHERE id = 1")->fetch();
$cities = $mysql_db->query("SELECT * FROM estate_cities ORDER BY is_active DESC, price_multiplier DESC")->fetchAll();
$buildings = $mysql_db->query("SELECT * FROM estate_buildings ORDER BY is_active DESC, build_cost ASC")->fetchAll();

$upgrade_paths = $mysql_db->query("
    SELECT p.*, b1.building_name as from_name, b2.building_name as to_name, b1.building_level as from_lvl, b2.building_level as to_lvl 
    FROM estate_upgrade_paths p 
    JOIN estate_buildings b1 ON p.from_building_id = b1.id 
    JOIN estate_buildings b2 ON p.to_building_id = b2.id 
    ORDER BY b1.build_cost ASC, p.upgrade_cost ASC
")->fetchAll();

$ind_map = ['food'=>'食 (餐飲/超市)','clothing'=>'衣 (百貨/服飾)','education'=>'育 (學校/補習)','entertainment'=>'樂 (飯店/遊樂)','housing'=>'住 (住宅/商辦)','transport'=>'行 (停車場/車站)'];

$edit_city = null;
if (isset($_GET['edit_city_id'])) {
    $stmt = $mysql_db->prepare("SELECT * FROM estate_cities WHERE id = ?");
    $stmt->execute([(int)$_GET['edit_city_id']]);
    $edit_city = $stmt->fetch();
}

$edit_building = null;
if (isset($_GET['edit_building_id'])) {
    $stmt = $mysql_db->prepare("SELECT * FROM estate_buildings WHERE id = ?");
    $stmt->execute([(int)$_GET['edit_building_id']]);
    $edit_building = $stmt->fetch();
}
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>房地產管理局 | 世界政府</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #1a1a2e; color: #e9ecef; margin: 0; padding: 40px 20px; }
        .container { max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        @media (max-width: 900px) { .container { grid-template-columns: 1fr; } }
        .card { background: #16213e; padding: 25px; border-radius: 12px; border: 1px solid #0f3460; box-shadow: 0 5px 15px rgba(0,0,0,0.3); margin-bottom: 20px;}
        h2 { color: #4facfe; margin-top: 0; font-size: 1.2rem; border-bottom: 1px solid #0f3460; padding-bottom: 10px;}
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 0.9rem; color: #bdc3c7; font-weight: bold;}
        input[type="text"], input[type="number"], select { width: 100%; padding: 10px; background: #1a1a2e; border: 1px solid #0f3460; color: #fff; border-radius: 6px; box-sizing: border-box; }
        .btn-save { background: #e94560; color: white; border: none; padding: 12px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.3s; margin-top:10px;}
        .btn-save:hover { background: #ff4d6d; }
        .btn-del { background: transparent; color: #e74c3c; border: none; cursor: pointer; font-size: 1.1rem; padding:0;}
        table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 0.9rem; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #0f3460; }
        th { color: #bdc3c7; }
        .badge { background: #8e44ad; color: #fff; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; }
        .badge-base { background: #2ecc71; }
        .badge-upgrade { background: #e67e22; }
        .alert { padding: 12px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: bold; }
        .alert-success { background: #27ae60; color: white; }
        .alert-error { background: #e74c3c; color: white; }
        .grid-6 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
        .lvl-tag { background: #34495e; color: #f1c40f; padding: 2px 6px; border-radius: 4px; font-size: 0.8rem; font-weight: bold; margin-right: 5px; }
    </style>
</head>
<body>

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

<div style="max-width: 1200px; margin: 0 auto;">
    <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>
    <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
</div>

<div class="container">
    <div>
        <div class="card" style="border-color: #f1c40f;">
            <h2 style="color: #f1c40f;">🌍 全國房市政策設定</h2>
            <form method="POST">
                <input type="hidden" name="action" value="update_global">
                <div class="form-group">
                    <label>全國公告基礎地價 (分鐘/筆)</label>
                    <input type="number" name="base_land_price" value="<?php echo $global_settings['base_land_price']; ?>" required>
                </div>
                <div class="form-group">
                    <label>每日土地持有稅率 (%) <span style="color:#e74c3c;">防囤地機制</span></label>
                    <input type="number" step="0.01" name="daily_land_tax_rate" value="<?php echo $global_settings['daily_land_tax_rate'] * 100; ?>" required>
                </div>
                <div class="form-group">
                    <label>每日房產保值增值率 (%) <span style="color:#2ecc71;">抗通膨機制</span></label>
                    <input type="number" step="0.01" name="daily_value_growth_rate" value="<?php echo $global_settings['daily_value_growth_rate'] * 100; ?>" required>
                </div>
                <button type="submit" class="btn-save" style="background: #f39c12;">發布政策</button>
            </form>
        </div>

        <div class="card">
            <h2>🏙️ <?php echo $edit_city ? '修改縣市地段' : '開發新縣市'; ?></h2>
            <form method="POST">
                <input type="hidden" name="action" value="save_city">
                <input type="hidden" name="city_id" value="<?php echo $edit_city['id'] ?? ''; ?>">
                
                <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:2;">
                        <label>縣市名稱</label>
                        <input type="text" name="city_name" value="<?php echo htmlspecialchars($edit_city['city_name'] ?? ''); ?>" placeholder="例: 台北市 信義區" required>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>地價權重(倍率)</label>
                        <input type="number" step="0.01" name="price_multiplier" value="<?php echo $edit_city['price_multiplier'] ?? '1.0'; ?>" required>
                    </div>
                </div>

                <label>🏬 六大產業營收加權 (預設 1.0 倍)</label>
                <div class="grid-6">
                    <div class="form-group"><label style="font-size:0.8rem;">食 (餐飲)</label><input type="number" step="0.01" name="food_mult" value="<?php echo $edit_city['food_mult'] ?? '1.0'; ?>" required></div>
                    <div class="form-group"><label style="font-size:0.8rem;">衣 (服飾)</label><input type="number" step="0.01" name="clothing_mult" value="<?php echo $edit_city['clothing_mult'] ?? '1.0'; ?>" required></div>
                    <div class="form-group"><label style="font-size:0.8rem;">育 (教育)</label><input type="number" step="0.01" name="education_mult" value="<?php echo $edit_city['education_mult'] ?? '1.0'; ?>" required></div>
                    <div class="form-group"><label style="font-size:0.8rem;">樂 (娛樂)</label><input type="number" step="0.01" name="entertainment_mult" value="<?php echo $edit_city['entertainment_mult'] ?? '1.0'; ?>" required></div>
                    <div class="form-group"><label style="font-size:0.8rem;">住 (住宅)</label><input type="number" step="0.01" name="housing_mult" value="<?php echo $edit_city['housing_mult'] ?? '1.0'; ?>" required></div>
                    <div class="form-group"><label style="font-size:0.8rem;">行 (交通)</label><input type="number" step="0.01" name="transport_mult" value="<?php echo $edit_city['transport_mult'] ?? '1.0'; ?>" required></div>
                </div>

                <div class="form-group">
                    <label style="cursor: pointer; display:flex; align-items:center; gap:5px; font-weight:normal;">
                        <input type="checkbox" name="is_active" <?php echo (!isset($edit_city) || $edit_city['is_active']) ? 'checked' : ''; ?> style="width:auto;"> 開放玩家購買此地段
                    </label>
                </div>
                <button type="submit" class="btn-save"><?php echo $edit_city ? '儲存變更' : '新增縣市'; ?></button>
                <?php if($edit_city): ?><a href="estate_super.php" style="display:block; text-align:center; color:#888; margin-top:10px;">取消修改</a><?php endif; ?>
            </form>

            <h3 style="margin-top:20px; font-size:1rem; color:#bdc3c7;">已開發縣市清單</h3>
            <div style="overflow-x:auto;">
                <table>
                    <thead><tr><th>縣市</th><th>地價</th><th>產業特色加權</th><th>操作</th></tr></thead>
                    <tbody>
                        <?php foreach($cities as $c): 
                            $price = $global_settings['base_land_price'] * $c['price_multiplier'];
                            $traits = [];
                            if($c['food_mult'] != 1) $traits[] = "食{$c['food_mult']}x";
                            if($c['clothing_mult'] != 1) $traits[] = "衣{$c['clothing_mult']}x";
                            if($c['education_mult'] != 1) $traits[] = "育{$c['education_mult']}x";
                            if($c['entertainment_mult'] != 1) $traits[] = "樂{$c['entertainment_mult']}x";
                            if($c['housing_mult'] != 1) $traits[] = "住{$c['housing_mult']}x";
                            if($c['transport_mult'] != 1) $traits[] = "行{$c['transport_mult']}x";
                            $trait_str = empty($traits) ? '無特別' : implode(', ', $traits);
                        ?>
                        <tr style="<?php echo $c['is_active'] ? '' : 'opacity:0.4;'; ?>">
                            <td><b><?php echo htmlspecialchars($c['city_name']); ?></b></td>
                            <td style="color:#4facfe;"><?php echo number_format($price); ?></td>
                            <td style="font-size:0.8rem;"><?php echo $trait_str; ?></td>
                            <td><a href="?edit_city_id=<?php echo $c['id']; ?>" style="color:#e94560;">編輯</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div>
        <div class="card">
            <h2>🏗️ <?php echo $edit_building ? '修改建物型錄' : '發布新建物型錄'; ?></h2>
            <form method="POST">
                <input type="hidden" name="action" value="save_building">
                <input type="hidden" name="building_id" value="<?php echo $edit_building['id'] ?? ''; ?>">
                
                <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:2;">
                        <label>建物名稱</label>
                        <input type="text" name="building_name" value="<?php echo htmlspecialchars($edit_building['building_name'] ?? ''); ?>" placeholder="例: 碎石停車場" required>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>所屬產業</label>
                        <select name="industry_type" required>
                            <?php foreach($ind_map as $key => $label): ?>
                                <option value="<?php echo $key; ?>" <?php echo (($edit_building['industry_type'] ?? '') == $key) ? 'selected' : ''; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>建物等級</label>
                        <input type="number" name="building_level" value="<?php echo $edit_building['building_level'] ?? '1'; ?>" min="1" required>
                    </div>
                </div>

                <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:1;">
                        <label>營建成本</label>
                        <input type="number" name="build_cost" value="<?php echo $edit_building['build_cost'] ?? ''; ?>" required>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>拆除花費</label>
                        <input type="number" name="demolish_cost" value="<?php echo $edit_building['demolish_cost'] ?? ''; ?>" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>每日固定營運成本 (水電/人事) <span style="color:#e74c3c;">負淨利會破產</span></label>
                    <input type="number" name="daily_fixed_cost" value="<?php echo $edit_building['daily_fixed_cost'] ?? ''; ?>" placeholder="例: 150" required>
                </div>

                <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:1;">
                        <label>最低每日營收</label>
                        <input type="number" name="daily_revenue_min" value="<?php echo $edit_building['daily_revenue_min'] ?? ''; ?>" placeholder="例: 100" required>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>最高每日營收</label>
                        <input type="number" name="daily_revenue_max" value="<?php echo $edit_building['daily_revenue_max'] ?? ''; ?>" placeholder="例: 300" required>
                    </div>
                </div>

                <div style="background: rgba(46, 204, 113, 0.1); padding: 10px; border-radius: 6px; border: 1px dashed #2ecc71; margin-bottom: 15px;">
                    <label style="cursor: pointer; display:flex; align-items:center; gap:8px; font-weight:normal; color:#2ecc71;">
                        <input type="checkbox" name="allow_new_build" <?php echo (!isset($edit_building) || $edit_building['allow_new_build']) ? 'checked' : ''; ?> style="width:auto;"> 
                        <b>✅ 允許直接在空地建造</b> (若為二級以上進階建物，請取消勾選)
                    </label>
                </div>

                <div class="form-group">
                    <label style="cursor: pointer; display:flex; align-items:center; gap:5px; font-weight:normal;">
                        <input type="checkbox" name="is_active" <?php echo (!isset($edit_building) || $edit_building['is_active']) ? 'checked' : ''; ?> style="width:auto;"> 開放玩家營建/升級此建物
                    </label>
                </div>
                
                <button type="submit" class="btn-save"><?php echo $edit_building ? '儲存變更' : '發布型錄'; ?></button>
                <?php if($edit_building): ?><a href="estate_super.php" style="display:block; text-align:center; color:#888; margin-top:10px;">取消修改</a><?php endif; ?>
            </form>

            <h3 style="margin-top:20px; font-size:1rem; color:#bdc3c7;">可建造型錄清單</h3>
            <div style="overflow-x:auto;">
                <table>
                    <thead><tr><th>名稱/產業</th><th>造價/拆除</th><th>營運成本</th><th>日營收區間</th><th>操作</th></tr></thead>
                    <tbody>
                        <?php foreach($buildings as $b): ?>
                        <tr style="<?php echo $b['is_active'] ? '' : 'opacity:0.4;'; ?>">
                            <td>
                                <span class="lvl-tag">LV.<?php echo $b['building_level']; ?></span><b><?php echo htmlspecialchars($b['building_name']); ?></b>
                                <div style="margin-top:4px;">
                                    <span class="badge"><?php echo $ind_map[$b['industry_type']]; ?></span>
                                    <?php if ($b['allow_new_build']): ?>
                                        <span class="badge badge-base">基礎</span>
                                    <?php else: ?>
                                        <span class="badge badge-upgrade">限升級</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td style="font-size:0.85rem; color:#f1c40f;">造 <?php echo number_format($b['build_cost']); ?><br>拆 <?php echo number_format($b['demolish_cost']); ?></td>
                            <td style="color:#e74c3c;">-<?php echo number_format($b['daily_fixed_cost']); ?></td>
                            <td style="color:#2ecc71;">+<?php echo number_format($b['daily_revenue_min']); ?> ~ <?php echo number_format($b['daily_revenue_max']); ?></td>
                            <td><a href="?edit_building_id=<?php echo $b['id']; ?>" style="color:#e94560;">編輯</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card" style="border-color: #9b59b6;">
            <h2 style="color: #9b59b6;">🚀 建物升級轉職路線設定</h2>
            
            <form method="POST">
                <input type="hidden" name="action" value="save_upgrade_path">
                <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:1;">
                        <label>原建物 (升級前)</label>
                        <select name="from_building_id" required>
                            <option value="">-- 請選擇 --</option>
                            <?php foreach($buildings as $b): ?>
                                <option value="<?php echo $b['id']; ?>">LV.<?php echo $b['building_level']; ?> <?php echo htmlspecialchars($b['building_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label>升級目標 (進化後)</label>
                        <select name="to_building_id" required>
                            <option value="">-- 請選擇 --</option>
                            <?php foreach($buildings as $b): ?>
                                <option value="<?php echo $b['id']; ?>">LV.<?php echo $b['building_level']; ?> <?php echo htmlspecialchars($b['building_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>升級工程費用 (分)</label>
                    <input type="number" name="upgrade_cost" placeholder="例: 1500" required>
                </div>
                <button type="submit" class="btn-save" style="background:#8e44ad;">建立進化連線</button>
            </form>

            <h3 style="margin-top:20px; font-size:1rem; color:#bdc3c7;">現有轉職路線</h3>
            <div style="overflow-x:auto;">
                <table>
                    <thead><tr><th>原建物</th><th>🔜 進化目標</th><th>升級花費</th><th>操作</th></tr></thead>
                    <tbody>
                        <?php if (count($upgrade_paths) == 0): ?>
                            <tr><td colspan="4" style="text-align:center; color:#7f8c8d;">尚無升級路線</td></tr>
                        <?php else: ?>
                            <?php foreach($upgrade_paths as $up): ?>
                            <tr>
                                <td style="color:#bdc3c7;">LV.<?php echo $up['from_lvl']; ?> <?php echo htmlspecialchars($up['from_name']); ?></td>
                                <td style="font-weight:bold; color:#2ecc71;">🔜 LV.<?php echo $up['to_lvl']; ?> <?php echo htmlspecialchars($up['to_name']); ?></td>
                                <td style="color:#f39c12; font-weight:bold;"><?php echo number_format($up['upgrade_cost']); ?></td>
                                <td>
                                    <form method="POST" style="margin:0;" onsubmit="return confirm('確定要移除這條升級路線嗎？');">
                                        <input type="hidden" name="action" value="delete_upgrade_path">
                                        <input type="hidden" name="path_id" value="<?php echo $up['id']; ?>">
                                        <button type="submit" class="btn-del">❌</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

</body>
</html>