<?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'];
$family_id = $_SESSION['family_id'];
$display_name = $_SESSION['display_name'];

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

try {
    $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);

    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS inventory (id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER, item_name TEXT, quantity INTEGER DEFAULT 0)");
    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS active_buffs (id INTEGER PRIMARY KEY AUTOINCREMENT, buff_type TEXT, effect_value REAL DEFAULT 1.0, active_count INTEGER DEFAULT 0, target_task_id INTEGER DEFAULT 0)");
    try { $sqlite_db->exec("ALTER TABLE active_buffs ADD COLUMN target_task_id INTEGER DEFAULT 0"); } catch (Exception $e) {}

    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN last_buff_date TEXT DEFAULT ''"); } catch (Exception $e) {}
    try { $sqlite_db->exec("ALTER TABLE estate_properties ADD COLUMN last_attack_date TEXT DEFAULT ''"); } catch (Exception $e) {}

    $today_date = date('Y-m-d');
    $today_weekday = date('w');
    
    $stmt_assign = $mysql_db->prepare("SELECT a.schedule_type, a.schedule_value, t.id as template_id, t.task_name FROM task_assignments a JOIN tasks_template t ON a.task_id = t.id WHERE a.player_id = :pid");
    $stmt_assign->execute([':pid' => $player_id]);
    $all_assign = $stmt_assign->fetchAll();

    $stmt_done = $sqlite_db->prepare("SELECT task_id FROM task_history WHERE substr(created_at, 1, 10) = :today");
    $stmt_done->execute([':today' => $today_date]);
    $done_tids = $stmt_done->fetchAll(PDO::FETCH_COLUMN);

    $available_tasks = [];
    foreach($all_assign as $t) {
        $type = $t['schedule_type']; $val = $t['schedule_value']; $is_today = false;
        if ($type === 'daily' || $type === 'daily_deadline') $is_today = true;
        elseif ($type === 'weekly' && in_array($today_weekday, explode(',', $val))) $is_today = true;
        elseif ($type === 'specific_date' && $val === $today_date) $is_today = true;
        if ($is_today && !in_array($t['template_id'], $done_tids)) { $available_tasks[] = $t; }
    }

    $my_estates = [];
    $opponent_estates = [];
    $stmt_users = $mysql_db->query("SELECT id, display_name, sqlite_file FROM users WHERE role='player'");
    foreach($stmt_users as $u) {
        if (!empty($u['sqlite_file']) && file_exists('../'.$u['sqlite_file'])) {
            $u_db = getPlayerSQLiteConnection($u['sqlite_file']);
            try {
                $props = $u_db->query("SELECT id, custom_name, building_name, city_name, building_id FROM estate_properties WHERE building_id > 0")->fetchAll();
                foreach($props as $p) {
                    $p['owner_id'] = $u['id'];
                    $p['owner_name'] = $u['display_name'];
                    $p['display_title'] = (!empty($p['custom_name']) ? $p['custom_name'] : $p['building_name']) . " ({$p['city_name']})";
                    
                    if ($u['id'] == $player_id) { $my_estates[] = $p; } 
                    else { $opponent_estates[] = $p; }
                }
            } catch (Exception $e) { } 
        }
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_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 ($_POST['action'] === 'buy_global') {
            $item_id = (int)$_POST['item_id'];
            $stmt_item = $mysql_db->prepare("SELECT * FROM global_items WHERE id = :id AND is_active = 1");
            $stmt_item->execute([':id' => $item_id]);
            $g_item = $stmt_item->fetch();

            if (!$g_item) { $error_msg = "卡牌已經絕版或不存在！"; } 
            elseif ($current_wallet < $g_item['price_minutes']) { $error_msg = "餘額不足！還差 " . ($g_item['price_minutes'] - $current_wallet) . " 分鐘！"; } 
            else {
                try {
                    $sqlite_db->beginTransaction();
                    $price = (int)$g_item['price_minutes'];
                    $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $price");
                    $stmt_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('buy_card', :amt, :desc)");
                    $stmt_log->execute([':amt' => -$price, ':desc' => "購買卡牌：{$g_item['item_name']}"]);

                    $stmt_check_inv = $sqlite_db->prepare("SELECT id FROM inventory WHERE item_id = :item_id");
                    $stmt_check_inv->execute([':item_id' => $item_id]);
                    $inv_item = $stmt_check_inv->fetch();

                    if ($inv_item) { $sqlite_db->prepare("UPDATE inventory SET quantity = quantity + 1 WHERE id = :id")->execute([':id' => $inv_item['id']]); } 
                    else { $sqlite_db->prepare("INSERT INTO inventory (item_id, item_name, quantity) VALUES (:item_id, :item_name, 1)")->execute([':item_id' => $item_id, ':item_name' => $g_item['item_name']]); }
                    
                    $sqlite_db->commit();
                    $success_msg = "🎉 購買成功！已放進背包囉！";
                } catch (Exception $e) { $sqlite_db->rollBack(); $error_msg = "購買失敗：" . $e->getMessage(); }
            }
        }
        elseif ($_POST['action'] === 'buy_family') {
            $item_id = (int)$_POST['item_id'];
            $stmt_item = $mysql_db->prepare("SELECT * FROM items_shop WHERE id = :id AND family_id = :fid AND is_active = 1");
            $stmt_item->execute([':id' => $item_id, ':fid' => $family_id]);
            $f_item = $stmt_item->fetch();

            if (!$f_item) { $error_msg = "獎勵缺貨中！"; } 
            elseif ($current_wallet < $f_item['price_minutes']) { $error_msg = "餘額不足！還差 " . ($f_item['price_minutes'] - $current_wallet) . " 分鐘！"; } 
            else {
                try {
                    $sqlite_db->beginTransaction(); $mysql_db->beginTransaction(); 
                    $price = (int)$f_item['price_minutes'];
                    $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes - $price");
                    $stmt_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('buy_reward', :amt, :desc)");
                    $stmt_log->execute([':amt' => -$price, ':desc' => "兌換獎勵：{$f_item['item_name']}"]);

                    $stmt_redemption = $mysql_db->prepare("INSERT INTO reward_redemptions (family_id, player_id, item_id, item_name, cost_minutes, status) VALUES (:fid, :pid, :item_id, :item_name, :cost, 'pending')");
                    $stmt_redemption->execute([':fid' => $family_id, ':pid' => $player_id, ':item_id' => $f_item['id'], ':item_name' => $f_item['item_name'], ':cost' => $price]);

                    $sqlite_db->commit(); $mysql_db->commit();
                    $success_msg = "🎟️ 兌換成功！已通知家長，請至背包查看狀態。";
                } catch (Exception $e) {
                    if ($sqlite_db->inTransaction()) $sqlite_db->rollBack();
                    if ($mysql_db->inTransaction()) $mysql_db->rollBack();
                    $error_msg = "兌換失敗：" . $e->getMessage();
                }
            }
        }
        elseif ($_POST['action'] === 'use_card') {
            $item_id = (int)$_POST['item_id'];
            $stmt_inv = $sqlite_db->prepare("SELECT quantity, item_name FROM inventory WHERE item_id = :id AND quantity > 0");
            $stmt_inv->execute([':id' => $item_id]);
            $inv_data = $stmt_inv->fetch();

            if (!$inv_data) {
                $error_msg = "背包裡沒有這張卡牌喔！";
            } else {
                $stmt_effect = $mysql_db->prepare("SELECT category, effect_type, effect_value FROM global_items WHERE id = :id");
                $stmt_effect->execute([':id' => $item_id]);
                $effect_data = $stmt_effect->fetch();

                if ($effect_data && $effect_data['effect_type'] === 'collectible') {
                    $error_msg = "✨ 這是典藏卡，沒有特殊魔法喔！";
                } elseif ($effect_data) {
                    try {
                        $category = $effect_data['category'];
                        $buff_type = $effect_data['effect_type'];
                        $buff_val = (float)$effect_data['effect_value'];
                        
                        if ($category === 'stock') {
                            $target_stock = isset($_POST['target_stock']) ? $_POST['target_stock'] : 'ALL';
                            $sqlite_db->prepare("UPDATE inventory SET quantity = quantity - 1 WHERE item_id = :id")->execute([':id' => $item_id]);
                            $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('use_card', 0, :desc)")->execute([':desc' => "使用了卡牌：{$inv_data['item_name']}"]);
                            
                            $res = StockEngine::applyInstantMagic($mysql_db, $player_id, $target_stock, $buff_val);
                            if ($res) { $success_msg = "📈 股市干涉魔法【{$inv_data['item_name']}】發動！目標：{$target_stock}。已引發劇烈震盪！"; } 
                            else { $error_msg = "股市發動失敗。"; }
                        } 
                        elseif ($category === 'estate') {
                            if ($buff_type === 'estate_boost') {
                                $target_prop_id = (int)$_POST['target_estate_my'];
                                if ($target_prop_id <= 0) { $error_msg = "請選擇一棟您的建築！"; } 
                                else {
                                    $prop = $sqlite_db->prepare("SELECT * FROM estate_properties WHERE id=?");
                                    $prop->execute([$target_prop_id]);
                                    $my_p = $prop->fetch();
                                    
                                    if ($my_p && $my_p['building_id'] > 0) {
                                        if (isset($my_p['last_buff_date']) && $my_p['last_buff_date'] === $today_date) {
                                            $error_msg = "🏢 這棟建物今天已經接受過財神眷顧了，一天只能舉辦一次促銷喔，請明天再來或選擇其他建物！";
                                        } else {
                                            $actual_revenue = (int)$my_p['last_revenue'];
                                            
                                            if ($actual_revenue <= 0) {
                                                $error_msg = "這棟建物今天還沒有產生營收（可能是今天剛落成），財神暫時無法施展魔法喔！";
                                            } else {
                                                // ★ 核心算法修正：因凌晨已發放過100%營收，雙倍道具僅補發剩下的差額 (倍率 - 1)，才符合「總收益翻倍」預期
                                                $reward = (int)round($actual_revenue * ($buff_val - 1));
                                                
                                                $sqlite_db->beginTransaction();
                                                $sqlite_db->prepare("UPDATE inventory SET quantity = quantity - 1 WHERE item_id = :id")->execute([':id' => $item_id]);
                                                $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $reward");
                                                
                                                $sqlite_db->prepare("UPDATE estate_properties SET last_buff_date = :td WHERE id = :id")->execute([':td' => $today_date, ':id' => $target_prop_id]);
                                                
                                                $desc = "🌟 財神降臨：在【{$my_p['custom_name']}】發動魔法，倍化今日營收（補發額外 " . (($buff_val - 1) * 100) . "%），獲得 {$reward} 分鐘！";
                                                $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('use_card', ?, ?)")->execute([$reward, $desc]);
                                                
                                                $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('estate_alert', 0, ?)")->execute(["✨ 財神眷顧！您的產業【{$my_p['custom_name']}】今日營收成功翻倍，為您額外帶來了 {$reward} 分鐘的驚人利潤！"]);

                                                $sqlite_db->commit();
                                                $success_msg = "🌟 財神降臨！【{$my_p['custom_name']}】順利翻倍，為您額外帶來 {$reward} 分鐘的利潤！";
                                            }
                                        }
                                    } else {
                                        $error_msg = "該土地上沒有營運中的建物！";
                                    }
                                }
                            }
                            elseif ($buff_type === 'estate_demolish') {
                                $target_data = $_POST['target_estate_opponent']; 
                                if (empty($target_data)) { $error_msg = "請選擇一個對手的建築！"; } 
                                else {
                                    list($target_owner_id, $target_prop_id) = explode('_', $target_data);
                                    
                                    $t_stmt = $mysql_db->prepare("SELECT sqlite_file, display_name FROM users WHERE id=?");
                                    $t_stmt->execute([$target_owner_id]);
                                    $target_user = $t_stmt->fetch();
                                    
                                    if ($target_user && file_exists('../'.$target_user['sqlite_file'])) {
                                        $sqlite_db->beginTransaction();
                                        $sqlite_db->prepare("UPDATE inventory SET quantity = quantity - 1 WHERE item_id = :id")->execute([':id' => $item_id]);
                                        $desc = "🌪️ 天災降臨：使用了卡牌【{$inv_data['item_name']}】對 {$target_user['display_name']} 發動了攻擊。";
                                        $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('use_card', 0, ?)")->execute([$desc]);

                                        $t_db = getPlayerSQLiteConnection($target_user['sqlite_file']);
                                        
                                        $p_info = $t_db->prepare("SELECT building_id, custom_name, last_attack_date FROM estate_properties WHERE id=?");
                                        $p_info->execute([$target_prop_id]);
                                        $target_prop = $p_info->fetch();
                                        
                                        if (isset($target_prop['last_attack_date']) && $target_prop['last_attack_date'] === $today_date) {
                                            $sqlite_db->rollBack(); 
                                            $error_msg = "🌪️ 這棟建物今天已經遭遇過天災，結構受到保護，無法在同一天內連續破壞！";
                                        } else {
                                            $sqlite_db->commit(); 

                                            $prev_stmt = $mysql_db->prepare("SELECT from_building_id FROM estate_upgrade_paths WHERE to_building_id = ? LIMIT 1");
                                            $prev_stmt->execute([$target_prop['building_id']]);
                                            $prev_id = $prev_stmt->fetchColumn();

                                            if ($prev_id) {
                                                $b_stmt = $mysql_db->prepare("SELECT * FROM estate_buildings WHERE id = ?");
                                                $b_stmt->execute([$prev_id]);
                                                $prev_b = $b_stmt->fetch();

                                                $t_db->prepare("UPDATE estate_properties SET building_id=?, building_name=?, build_cost=?, demolish_cost=?, last_attack_date=? WHERE id=?")
                                                     ->execute([$prev_id, $prev_b['building_name'], $prev_b['build_cost'], $prev_b['demolish_cost'], $today_date, $target_prop_id]);
                                                
                                                $t_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('estate_alert', 0, ?)")
                                                     ->execute(["🚨 遭受攻擊！您的建物【{$target_prop['custom_name']}】遭到玩家【{$display_name}】發動天災，被迫降級為【{$prev_b['building_name']}】！"]);
                                                
                                                $success_msg = "🌪️ 天災發威！您已將 {$target_user['display_name']} 的建物強制降級！";
                                            } else {
                                                $t_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, last_attack_date=? WHERE id=?")
                                                     ->execute([$today_date, $target_prop_id]);
                                                $t_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('estate_alert', 0, ?)")
                                                     ->execute(["🚨 遭受攻擊！您的建物【{$target_prop['custom_name']}】遭到玩家【{$display_name}】強拆，已被夷為平地！"]);
                                                
                                                $success_msg = "🌪️ 天災摧毀成功！您已將 {$target_user['display_name']} 的建物夷為平地！";
                                            }
                                        }
                                    } else {
                                        $error_msg = "找不到指定的對手！";
                                    }
                                }
                            }
                        }
                        else {
                            $target_task_id = isset($_POST['target_task_id']) ? (int)$_POST['target_task_id'] : 0;
                            if ($target_task_id <= 0) { $error_msg = "必須選擇一個任務才能施放魔法！"; } 
                            else {
                                $sqlite_db->beginTransaction();
                                $sqlite_db->prepare("UPDATE inventory SET quantity = quantity - 1 WHERE item_id = :id")->execute([':id' => $item_id]);
                                $sqlite_db->prepare("INSERT INTO active_buffs (buff_type, effect_value, active_count, target_task_id) VALUES (:type, :val, 1, :tid)")->execute([':type' => $buff_type, ':val' => $buff_val, ':tid' => $target_task_id]);
                                $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('use_card', 0, :desc)")->execute([':desc' => "使用了卡牌：{$inv_data['item_name']}"]);
                                $sqlite_db->commit();
                                $success_msg = "🪄 魔法發動成功！已精準掛載於指定的任務上！";
                            }
                        }

                    } catch (Exception $e) {
                        if ($sqlite_db->inTransaction()) $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;

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

    $global_items_raw = $mysql_db->query("SELECT * FROM global_items WHERE is_active = 1 ORDER BY category ASC, price_minutes ASC")->fetchAll();
    $shop_cards = ['daily' => [], 'stock' => [], 'estate' => []];
    foreach($global_items_raw as $g) {
        $cat = $g['category'] ?? 'daily';
        $shop_cards[$cat][] = $g;
    }

    $stmt_fam_items = $mysql_db->prepare("SELECT * FROM items_shop WHERE family_id = :fid AND is_active = 1 ORDER BY price_minutes ASC");
    $stmt_fam_items->execute([':fid' => $family_id]);
    $family_items = $stmt_fam_items->fetchAll();

    $inventory_items = $sqlite_db->query("SELECT * FROM inventory WHERE quantity > 0")->fetchAll();
    $inventory_cards = ['daily' => [], 'stock' => [], 'estate' => []];
    foreach ($inventory_items as $inv) {
        $stmt_detail = $mysql_db->prepare("SELECT image_path, effect_type, category FROM global_items WHERE id = :id");
        $stmt_detail->execute([':id' => $inv['item_id']]);
        $detail = $stmt_detail->fetch();
        $inv['image_path'] = $detail ? $detail['image_path'] : null;
        $inv['effect_type'] = $detail ? $detail['effect_type'] : 'unknown';
        $cat = $detail ? $detail['category'] : 'daily';
        $inventory_cards[$cat][] = $inv;
    }

    $stmt_redemptions = $mysql_db->prepare("SELECT * FROM reward_redemptions WHERE player_id = :pid ORDER BY created_at DESC");
    $stmt_redemptions->execute([':pid' => $player_id]);
    $redemptions = $stmt_redemptions->fetchAll();

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

} 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, #f6d365 0%, #fda085 100%); border-radius: 15px; padding: 20px; text-align: center; color: white; box-shadow: 0 4px 10px rgba(253, 160, 133, 0.3); margin-bottom: 20px; }
        .wallet-balance { font-size: 3.5rem; font-weight: bold; margin: 0; line-height: 1; }
        .wallet-unit { font-size: 1rem; margin-top: 5px; opacity: 0.9; }
        .wallet-convert { font-size: 0.85rem; background: rgba(0,0,0,0.15); display: inline-block; padding: 4px 12px; border-radius: 20px; margin-top: 10px; }
        .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: #3498db; color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        .cat-title { font-size: 1.05rem; color: #2c3e50; border-bottom: 2px solid #ccc; padding-bottom: 5px; margin: 25px 0 15px 0; display: flex; align-items: center; gap: 5px;}
        .card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 15px; }
        .item-card { background: white; border-radius: 12px; padding: 15px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.08); position: relative; display: flex; flex-direction: column;}
        .item-img { width: 100%; height: 160px; object-fit: cover; border-radius: 8px; margin-bottom: 10px; background-color: #2c3e50; border: 2px solid #3498db;}
        .item-img.no-img { display: flex; align-items: center; justify-content: center; color: white; font-size: 3rem; }
        .item-name { font-weight: bold; color: #2c3e50; font-size: 1rem; margin-bottom: 5px; }
        .item-desc { font-size: 0.75rem; color: #7f8c8d; margin-bottom: 15px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; flex: 1;}
        .btn-buy { background: #2ecc71; color: white; border: none; padding: 10px; width: 100%; border-radius: 6px; font-weight: bold; font-size: 0.95rem; cursor: pointer; transition: 0.2s;}
        .btn-buy:active { transform: scale(0.95); }
        .btn-buy:disabled { background: #bdc3c7; cursor: not-allowed; transform: none; }
        .list-item { background: white; border-radius: 12px; padding: 15px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 12px; }
        .list-info { flex: 1; }
        .list-name { font-weight: bold; color: #2c3e50; font-size: 1.05rem; margin-bottom: 4px; display: block; }
        .list-desc { font-size: 0.8rem; color: #7f8c8d; }
        .list-price { font-weight: bold; color: #e67e22; font-size: 1.2rem; }
        .btn-buy-small { background: #f39c12; color: white; border: none; padding: 8px 15px; border-radius: 20px; font-weight: bold; font-size: 0.9rem; cursor: pointer; margin-left: 15px; }
        .inv-badge { background: #e74c3c; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8rem; font-weight: bold; position: absolute; top: -5px; right: -5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);}
        .status-pending { color: #f39c12; font-weight: bold; font-size: 0.85rem;}
        .status-fulfilled { color: #27ae60; font-weight: bold; font-size: 0.85rem;}
        .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-msg { text-align: center; color: #95a5a6; padding: 30px 10px; font-size: 0.9rem; background: #fff; border-radius: 10px; border: 1px dashed #ccc;}
        select.target-select { width: 100%; padding: 6px; margin-top: 5px; margin-bottom: 10px; border: 1px solid #e74c3c; border-radius: 4px; background: #fef9e7; font-size: 0.85rem; }
        .target-select-task { border-color: #2ecc71; background: #e8f8f5; }
        .target-select-estate { border-color: #9b59b6; background: #f4ecf7; }
    </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.8;">我的可用時間</p>
        <p class="wallet-balance"><?php echo $current_wallet; ?></p>
        <p class="wallet-unit">分鐘 (MINS)</p>
        <?php if ($time_convert_str): ?><div class="wallet-convert"><?php echo $time_convert_str; ?></div><?php endif; ?>
    </div>

    <div class="tabs">
        <div class="tab-btn active" onclick="switchTab('tab-global')">🌍 卡牌店</div>
        <div class="tab-btn" onclick="switchTab('tab-family')">🏠 柑仔店</div>
        <div class="tab-btn" onclick="switchTab('tab-inventory')">🎒 我的背包</div>
    </div>

    <div id="tab-global" class="tab-content active">
        <?php if (count($global_items_raw) === 0): ?>
            <div class="empty-msg">目前沒有發行任何卡牌喔。</div>
        <?php endif; ?>

        <?php if (count($shop_cards['daily']) > 0): ?>
            <div class="cat-title">🏃 日常任務魔法</div>
            <div class="card-grid">
                <?php foreach ($shop_cards['daily'] as $g): ?>
                    <div class="item-card">
                        <?php if (!empty($g['image_path'])): ?><img src="../<?php echo htmlspecialchars($g['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#2ecc71;">🃏</div><?php endif; ?>
                        <div class="item-name"><?php echo htmlspecialchars($g['item_name']); ?></div>
                        <div class="item-desc"><?php echo htmlspecialchars($g['description']); ?></div>
                        <form method="POST" onsubmit="return confirm('確定購買嗎？');">
                            <input type="hidden" name="action" value="buy_global"><input type="hidden" name="item_id" value="<?php echo $g['id']; ?>">
                            <?php if ($current_wallet >= $g['price_minutes']): ?><button type="submit" class="btn-buy" style="background:#2ecc71;">💰 <?php echo $g['price_minutes']; ?> 分</button>
                            <?php else: ?><button type="button" class="btn-buy" disabled>差 <?php echo ($g['price_minutes'] - $current_wallet); ?> 分</button><?php endif; ?>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (count($shop_cards['stock']) > 0): ?>
            <div class="cat-title">📈 股市干涉道具</div>
            <div class="card-grid">
                <?php foreach ($shop_cards['stock'] as $g): ?>
                    <div class="item-card">
                        <?php if (!empty($g['image_path'])): ?><img src="../<?php echo htmlspecialchars($g['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#e74c3c;">🃏</div><?php endif; ?>
                        <div class="item-name"><?php echo htmlspecialchars($g['item_name']); ?></div>
                        <div class="item-desc"><?php echo htmlspecialchars($g['description']); ?></div>
                        <form method="POST" onsubmit="return confirm('確定購買嗎？');">
                            <input type="hidden" name="action" value="buy_global"><input type="hidden" name="item_id" value="<?php echo $g['id']; ?>">
                            <?php if ($current_wallet >= $g['price_minutes']): ?><button type="submit" class="btn-buy" style="background:#e74c3c;">💰 <?php echo $g['price_minutes']; ?> 分</button>
                            <?php else: ?><button type="button" class="btn-buy" disabled>差 <?php echo ($g['price_minutes'] - $current_wallet); ?> 分</button><?php endif; ?>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (count($shop_cards['estate']) > 0): ?>
            <div class="cat-title">🏘️ 房地產專用魔法</div>
            <div class="card-grid">
                <?php foreach ($shop_cards['estate'] as $g): ?>
                    <div class="item-card">
                        <?php if (!empty($g['image_path'])): ?><img src="../<?php echo htmlspecialchars($g['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#9b59b6;">🃏</div><?php endif; ?>
                        <div class="item-name"><?php echo htmlspecialchars($g['item_name']); ?></div>
                        <div class="item-desc"><?php echo htmlspecialchars($g['description']); ?></div>
                        <form method="POST" onsubmit="return confirm('確定購買嗎？');">
                            <input type="hidden" name="action" value="buy_global"><input type="hidden" name="item_id" value="<?php echo $g['id']; ?>">
                            <?php if ($current_wallet >= $g['price_minutes']): ?><button type="submit" class="btn-buy" style="background:#9b59b6;">💰 <?php echo $g['price_minutes']; ?> 分</button>
                            <?php else: ?><button type="button" class="btn-buy" disabled>差 <?php echo ($g['price_minutes'] - $current_wallet); ?> 分</button><?php endif; ?>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div id="tab-family" class="tab-content">
        <?php if (count($family_items) > 0): ?>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <?php foreach ($family_items as $f): ?>
                    <div class="list-item">
                        <div class="list-info"><span class="list-name"><?php echo htmlspecialchars($f['item_name']); ?></span><span class="list-desc"><?php echo htmlspecialchars($f['description']); ?></span></div>
                        <div style="display: flex; align-items: center;"><span class="list-price"><?php echo $f['price_minutes']; ?> 分</span>
                            <form method="POST" onsubmit="return confirm('確定兌換嗎？');">
                                <input type="hidden" name="action" value="buy_family"><input type="hidden" name="item_id" value="<?php echo $f['id']; ?>">
                                <?php if ($current_wallet >= $f['price_minutes']): ?><button type="submit" class="btn-buy-small">兌換</button>
                                <?php else: ?><button type="button" class="btn-buy-small" style="background:#bdc3c7;" disabled>不足</button><?php endif; ?>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-msg">柑仔店目前還沒有上架商品！</div>
        <?php endif; ?>
    </div>

    <div id="tab-inventory" class="tab-content">
        <?php if (count($inventory_items) === 0): ?>
            <div class="empty-msg" style="margin-bottom: 25px;">背包裡還沒有卡牌。</div>
        <?php else: ?>
            
            <?php if (count($inventory_cards['daily']) > 0): ?>
                <div class="cat-title" style="margin-top:0;">🏃 日常任務魔法</div>
                <div class="card-grid" style="margin-bottom: 25px;">
                    <?php foreach ($inventory_cards['daily'] as $inv): ?>
                        <div class="item-card">
                            <div class="inv-badge">擁有 <?php echo $inv['quantity']; ?> 張</div>
                            <?php if (!empty($inv['image_path'])): ?><img src="../<?php echo htmlspecialchars($inv['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#2ecc71;">🃏</div><?php endif; ?>
                            <div class="item-name"><?php echo htmlspecialchars($inv['item_name']); ?></div>
                            
                            <form method="POST" onsubmit="return confirm('確定要把魔法掛載在指定的任務上嗎？');">
                                <input type="hidden" name="action" value="use_card">
                                <input type="hidden" name="item_id" value="<?php echo $inv['item_id']; ?>">
                                
                                <select name="target_task_id" class="target-select target-select-task" required>
                                    <option value="">-- 請選擇指定任務 --</option>
                                    <?php foreach($available_tasks as $at): ?>
                                        <option value="<?php echo $at['template_id']; ?>">📝 <?php echo htmlspecialchars($at['task_name']); ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <button type="submit" class="btn-buy" style="background:#2ecc71;">🪄 掛載魔法</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (count($inventory_cards['stock']) > 0): ?>
                <div class="cat-title" style="margin-top:0;">📈 股市干涉道具</div>
                <div class="card-grid" style="margin-bottom: 25px;">
                    <?php foreach ($inventory_cards['stock'] as $inv): ?>
                        <div class="item-card">
                            <div class="inv-badge">擁有 <?php echo $inv['quantity']; ?> 張</div>
                            <?php if (!empty($inv['image_path'])): ?><img src="../<?php echo htmlspecialchars($inv['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#e74c3c;">🃏</div><?php endif; ?>
                            <div class="item-name"><?php echo htmlspecialchars($inv['item_name']); ?></div>
                            
                            <form method="POST" onsubmit="return confirm('即將對指定目標發動干涉！\n警告：股價將在【按下的瞬間】產生劇烈震盪！確定嗎？');">
                                <input type="hidden" name="action" value="use_card">
                                <input type="hidden" name="item_id" value="<?php echo $inv['item_id']; ?>">
                                
                                <?php if ($inv['effect_type'] === 'stock_all'): ?>
                                    <input type="hidden" name="target_stock" value="ALL">
                                    <div style="font-size: 0.85rem; color: #e74c3c; margin: 5px 0; font-weight:bold;">🎯 目標：全體大盤</div>
                                <?php else: ?>
                                    <select name="target_stock" class="target-select" required>
                                        <option value="">-- 選擇狙擊目標 --</option>
                                        <?php foreach($active_stocks as $s): ?>
                                            <option value="<?php echo $s['stock_code']; ?>">🎯 <?php echo $s['stock_name']; ?> (<?php echo $s['stock_code']; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php endif; ?>
                                
                                <button type="submit" class="btn-buy" style="background:#e74c3c;">🪄 瞬間發動干涉</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (count($inventory_cards['estate']) > 0): ?>
                <div class="cat-title" style="margin-top:0;">🏘️ 房地產專用魔法</div>
                <div class="card-grid" style="margin-bottom: 25px;">
                    <?php foreach ($inventory_cards['estate'] as $inv): ?>
                        <div class="item-card">
                            <div class="inv-badge">擁有 <?php echo $inv['quantity']; ?> 張</div>
                            <?php if (!empty($inv['image_path'])): ?><img src="../<?php echo htmlspecialchars($inv['image_path']); ?>" class="item-img"><?php else: ?><div class="item-img no-img" style="border-color:#9b59b6;">🃏</div><?php endif; ?>
                            <div class="item-name"><?php echo htmlspecialchars($inv['item_name']); ?></div>
                            
                            <form method="POST" onsubmit="return confirm('確定要對該目標發動魔法嗎？');">
                                <input type="hidden" name="action" value="use_card">
                                <input type="hidden" name="item_id" value="<?php echo $inv['item_id']; ?>">
                                
                                <?php if ($inv['effect_type'] === 'estate_boost'): ?>
                                    <select name="target_estate_my" class="target-select target-select-estate" required>
                                        <option value="">-- 選擇我的金雞母 --</option>
                                        <?php foreach($my_estates as $p): ?>
                                            <option value="<?php echo $p['id']; ?>">🏢 <?php echo htmlspecialchars($p['display_title']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <button type="submit" class="btn-buy" style="background:#f1c40f; color:#d35400;">🌟 呼叫財神降臨</button>
                                
                                <?php elseif ($inv['effect_type'] === 'estate_demolish'): ?>
                                    <?php if (count($opponent_estates) > 0): ?>
                                        <select name="target_estate_opponent" class="target-select target-select-estate" required style="border-color:#34495e; background:#ecf0f1; color:#2c3e50;">
                                            <option value="">-- 選擇要強拆的目標 --</option>
                                            <?php foreach($opponent_estates as $p): ?>
                                                <option value="<?php echo $p['owner_id'] . '_' . $p['id']; ?>">💣 [<?php echo htmlspecialchars($p['owner_name']); ?>] <?php echo htmlspecialchars($p['display_title']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="submit" class="btn-buy" style="background:#2c3e50;">🌪️ 發動天災拆除</button>
                                    <?php else: ?>
                                        <select disabled class="target-select target-select-estate" style="border-color:#ccc; background:#eee; color:#999;">
                                            <option>-- 目前無對手目標 --</option>
                                        </select>
                                        <button type="button" class="btn-buy" disabled style="background:#bdc3c7;">無法發動</button>
                                    <?php endif; ?>
                                
                                <?php else: ?>
                                    <button type="button" class="btn-buy" style="background:#9b59b6; margin-top:5px;" onclick="alert('此卡牌無特殊魔法！')">典藏卡保留</button>
                                <?php endif; ?>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

        <?php endif; ?>

        <h3 style="font-size: 1rem; color: #2c3e50; border-bottom: 2px solid #ccc; padding-bottom:5px;">🎟️ 實體兌換券狀態</h3>
        <?php if (count($redemptions) > 0): ?>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <?php foreach ($redemptions as $r): ?>
                    <div class="list-item" style="padding: 10px 15px;">
                        <div class="list-info"><span class="list-name" style="font-size: 0.95rem;"><?php echo htmlspecialchars($r['item_name']); ?></span><span class="list-desc" style="font-size:0.75rem;">購買於 <?php echo date('m/d H:i', strtotime($r['created_at'])); ?></span></div>
                        <div><?php if ($r['status'] === 'pending'): ?><span class="status-pending">⏳ 待處理</span><?php else: ?><span class="status-fulfilled">✅ 已實現</span><?php endif; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-msg">你還沒有買過任何實體獎勵喔。</div>
        <?php endif; ?>
    </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');
    }
    <?php if(isset($_POST['action']) && in_array($_POST['action'], ['use_card', 'buy_global', 'buy_family'])): ?> switchTab('tab-inventory'); <?php endif; ?>
</script>

</body>
</html>