<?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 = '';

// ==========================================
// 1. 處理 POST 動作
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'save_item') {
        $id = !empty($_POST['item_id']) ? (int)$_POST['item_id'] : null;
        $name = trim($_POST['item_name']);
        $price = (int)$_POST['price_minutes'];
        $category = trim($_POST['category']);
        $type = trim($_POST['effect_type']);
        $val = (float)$_POST['effect_value']; 
        $desc = trim($_POST['description']);
        $active = isset($_POST['is_active']) ? 1 : 0;
        
        $image_path = null;
        if (isset($_FILES['card_image']) && $_FILES['card_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/cards/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $filename = uniqid() . '_' . basename($_FILES['card_image']['name']);
            $target_file = $upload_dir . $filename;
            if (move_uploaded_file($_FILES['card_image']['tmp_name'], $target_file)) {
                $image_path = 'uploads/cards/' . $filename; 
            }
        }

        try {
            if ($id) {
                if ($image_path) {
                    $sql = "UPDATE global_items SET item_name=:n, price_minutes=:p, category=:c, effect_type=:t, effect_value=:v, image_path=:img, description=:d, is_active=:a WHERE id=:id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':n'=>$name, ':p'=>$price, ':c'=>$category, ':t'=>$type, ':v'=>$val, ':img'=>$image_path, ':d'=>$desc, ':a'=>$active, ':id'=>$id]);
                } else {
                    $sql = "UPDATE global_items SET item_name=:n, price_minutes=:p, category=:c, effect_type=:t, effect_value=:v, description=:d, is_active=:a WHERE id=:id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':n'=>$name, ':p'=>$price, ':c'=>$category, ':t'=>$type, ':v'=>$val, ':d'=>$desc, ':a'=>$active, ':id'=>$id]);
                }
                $success_msg = "卡牌「{$name}」已更新！";
            } else {
                $sql = "INSERT INTO global_items (item_name, price_minutes, category, effect_type, effect_value, image_path, description, is_active) VALUES (:n, :p, :c, :t, :v, :img, :d, :a)";
                $stmt = $mysql_db->prepare($sql);
                $stmt->execute([':n'=>$name, ':p'=>$price, ':c'=>$category, ':t'=>$type, ':v'=>$val, ':img'=>$image_path, ':d'=>$desc, ':a'=>$active]);
                $success_msg = "新卡牌「{$name}」已上架！";
            }
        } catch (PDOException $e) {
            $error_msg = "儲存失敗：" . $e->getMessage();
        }
    } elseif ($action === 'delete_item') {
        try {
            $stmt = $mysql_db->prepare("DELETE FROM global_items WHERE id = :id");
            $stmt->execute([':id' => $_POST['item_id']]);
            $success_msg = "卡牌已移除。";
        } catch (PDOException $e) {
            $error_msg = "刪除失敗。";
        }
    }
}

$edit_item = null;
if (isset($_GET['edit_id'])) {
    $stmt = $mysql_db->prepare("SELECT * FROM global_items WHERE id = :id");
    $stmt->execute([':id' => $_GET['edit_id']]);
    $edit_item = $stmt->fetch();
}

$items = $mysql_db->query("SELECT * FROM global_items ORDER BY category ASC, created_at DESC")->fetchAll();
?>

<!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: 1100px; margin: 0 auto; display: grid; grid-template-columns: 380px 1fr; gap: 20px; box-sizing: border-box; }
        .card { background: #16213e; padding: 20px; border-radius: 12px; border: 1px solid #0f3460; box-shadow: 0 5px 15px rgba(0,0,0,0.3);}
        h2 { color: #f1c40f; 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: #4facfe; font-weight: bold;}
        input[type="text"], input[type="number"], textarea, select { width: 100%; padding: 10px; background: #1a1a2e; border: 1px solid #0f3460; color: #fff; border-radius: 6px; box-sizing: border-box; }
        input[type="file"] { width: 100%; padding: 8px; background: #1a1a2e; color: #ccc; border: 1px dashed #4facfe; border-radius: 6px; box-sizing: border-box; cursor: pointer;}
        .btn-save { background: #e94560; color: white; border: none; padding: 12px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.3s;}
        .btn-save:hover { background: #ff4d6d; }
        .btn-del { background: transparent; color: #e74c3c; border: none; cursor: pointer; font-size: 1.1rem; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; vertical-align: middle;}
        th { color: #4facfe; font-size: 0.9rem; }
        .status-on { background: #27ae60; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; }
        .status-off { background: #7f8c8d; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; }
        .alert { background: #27ae60; color: white; padding: 10px; border-radius: 6px; margin-bottom: 15px; text-align: center; }
        .card-thumb { width: 60px; height: 80px; object-fit: cover; border-radius: 6px; border: 2px solid #4facfe; background-color: #1a1a2e;}
        .card-preview { width: 100%; max-width: 150px; height: auto; border-radius: 8px; border: 2px dashed #4facfe; margin-top: 10px; display: block;}
        .cat-badge { padding: 3px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; }
        .cat-daily { background: #2ecc71; color: white; }
        .cat-stock { background: #e74c3c; color: white; }
        .cat-estate { background: #9b59b6; color: white; }
    </style>
</head>
<body>

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

<div class="container">
    <div class="card">
        <h2><?php echo $edit_item ? '✏️ 修改卡牌' : '🃏 發行新卡牌'; ?></h2>
        <?php if ($success_msg): ?><div class="alert"><?php echo $success_msg; ?></div><?php endif; ?>
        <?php if ($error_msg): ?><div class="alert" style="background:#e74c3c;"><?php echo $error_msg; ?></div><?php endif; ?>
        
        <form method="POST" action="items.php" enctype="multipart/form-data">
            <input type="hidden" name="action" value="save_item">
            <input type="hidden" name="item_id" value="<?php echo $edit_item['id'] ?? ''; ?>">
            
            <div class="form-group">
                <label>卡牌名稱</label>
                <input type="text" name="item_name" value="<?php echo htmlspecialchars($edit_item['item_name'] ?? ''); ?>" required>
            </div>
            
            <div style="display: flex; gap: 10px;">
                <div class="form-group" style="flex: 1;">
                    <label>發行售價 (分)</label>
                    <input type="number" name="price_minutes" value="<?php echo $edit_item['price_minutes'] ?? ''; ?>" required>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>適用領域 (Category)</label>
                    <select name="category" required>
                        <option value="daily" <?php echo ($edit_item['category'] ?? '') == 'daily' ? 'selected' : ''; ?>>🏃 日常任務</option>
                        <option value="stock" <?php echo ($edit_item['category'] ?? '') == 'stock' ? 'selected' : ''; ?>>📈 股市干涉</option>
                        <option value="estate" <?php echo ($edit_item['category'] ?? '') == 'estate' ? 'selected' : ''; ?>>🏘️ 房地產專用</option>
                    </select>
                </div>
            </div>

            <div class="form-group" style="display: flex; gap: 10px; background: rgba(0,0,0,0.2); padding: 10px; border-radius: 6px;">
                <div style="flex: 2;">
                    <label>卡牌核心屬性 (Type)</label>
                    <select name="effect_type">
                        <option value="multiplier" <?php echo ($edit_item['effect_type'] ?? '') == 'multiplier' ? 'selected' : ''; ?>>任務: 🧪 倍率卡 (需設倍數)</option>
                        <option value="fixed_time" <?php echo ($edit_item['effect_type'] ?? '') == 'fixed_time' ? 'selected' : ''; ?>>任務: ⏳ 增減卡 (需設分鐘)</option>
                        <option value="shield" <?php echo ($edit_item['effect_type'] ?? '') == 'shield' ? 'selected' : ''; ?>>任務: 🛡️ 防禦卡 (無視數值)</option>
                        <option value="stock_single" <?php echo ($edit_item['effect_type'] ?? '') == 'stock_single' ? 'selected' : ''; ?>>股市: 🎯 單檔強制漲跌 (需選目標)</option>
                        <option value="stock_all" <?php echo ($edit_item['effect_type'] ?? '') == 'stock_all' ? 'selected' : ''; ?>>股市: 🌍 大盤強制漲跌 (全體生效)</option>
                        <option value="estate_boost" <?php echo ($edit_item['effect_type'] ?? '') == 'estate_boost' ? 'selected' : ''; ?>>房市: 🌟 財神降臨 (指定自己建物，獲參數倍營收)</option>
                        <option value="estate_demolish" <?php echo ($edit_item['effect_type'] ?? '') == 'estate_demolish' ? 'selected' : ''; ?>>房市: 🌪️ 天災降臨 (指定對手建物夷為平地，參數無效)</option>
                        <option value="collectible" <?php echo ($edit_item['effect_type'] ?? '') == 'collectible' ? 'selected' : ''; ?>>通用: ✨ 典藏卡 (無效果)</option>
                    </select>
                </div>
                <div style="flex: 1;">
                    <label>參數值</label>
                    <input type="number" step="0.01" name="effect_value" value="<?php echo $edit_item['effect_value'] ?? '1.0'; ?>" title="例如倍率卡填2.0，漲跌幅填0.05">
                </div>
            </div>

            <div class="form-group">
                <label>上傳卡牌立繪 (圖檔)</label>
                <input type="file" name="card_image" accept="image/jpeg, image/png, image/gif, image/webp">
                <?php if (!empty($edit_item['image_path'])): ?>
                    <img src="../<?php echo $edit_item['image_path']; ?>" class="card-preview">
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label>卡牌故事與說明</label>
                <textarea name="description" rows="3"><?php echo htmlspecialchars($edit_item['description'] ?? ''); ?></textarea>
            </div>

            <div class="form-group">
                <label style="cursor: pointer; color: #ecf0f1; font-weight: normal;">
                    <input type="checkbox" name="is_active" <?php echo (!isset($edit_item) || $edit_item['is_active']) ? 'checked' : ''; ?>> 上架公開
                </label>
            </div>

            <button type="submit" class="btn-save"><?php echo $edit_item ? '儲存卡牌變更' : '印製並發行卡牌'; ?></button>
            <?php if ($edit_item): ?><a href="items.php" style="display: block; text-align: center; color: #888; margin-top: 15px; text-decoration: none;">放棄修改</a><?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h2>🌐 全球卡牌圖鑑管理</h2>
        <table>
            <thead>
                <tr>
                    <th width="80">卡面</th>
                    <th>資訊</th>
                    <th width="80">狀態</th>
                    <th width="80">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $i): 
                    $cat_class = 'cat-daily'; $cat_name = '日常';
                    if ($i['category'] == 'stock') { $cat_class = 'cat-stock'; $cat_name = '股市'; }
                    elseif ($i['category'] == 'estate') { $cat_class = 'cat-estate'; $cat_name = '房市'; }
                ?>
                <tr>
                    <td>
                        <?php if (!empty($i['image_path'])): ?>
                            <img src="../<?php echo htmlspecialchars($i['image_path']); ?>" class="card-thumb" alt="thumb">
                        <?php else: ?>
                            <div class="card-thumb" style="display:flex; align-items:center; justify-content:center; color:#4facfe;">無圖</div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div style="font-size: 1.1rem; font-weight: bold; color: #f1c40f; margin-bottom: 4px;">
                            <span class="cat-badge <?php echo $cat_class; ?>"><?php echo $cat_name; ?></span>
                            <?php echo htmlspecialchars($i['item_name']); ?>
                        </div>
                        <div style="font-size: 0.85rem; color: #ecf0f1; margin-bottom: 2px;">
                            定價：<span style="color:#2ecc71; font-weight:bold;"><?php echo $i['price_minutes']; ?></span> | 
                            屬性：<span style="color:#e74c3c; font-weight:bold;"><?php echo $i['effect_type']; ?> (<?php echo $i['effect_value']; ?>)</span>
                        </div>
                        <div style="font-size: 0.8rem; color: #95a5a6;"><?php echo htmlspecialchars($i['description']); ?></div>
                    </td>
                    <td><span class="<?php echo $i['is_active'] ? 'status-on' : 'status-off'; ?>"><?php echo $i['is_active'] ? '流通中' : '已絕版'; ?></span></td>
                    <td>
                        <a href="items.php?edit_id=<?php echo $i['id']; ?>" style="color: #4facfe; text-decoration: none; font-weight:bold;">修改</a><br><br>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('確定要銷毀這張卡牌嗎？');">
                            <input type="hidden" name="action" value="delete_item">
                            <input type="hidden" name="item_id" value="<?php echo $i['id']; ?>">
                            <button type="submit" class="btn-del">🗑️</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>