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

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

$family_id = $_SESSION['family_id'];
$current_user_id = $_SESSION['user_id'];
$error_msg = '';
$success_msg = '';

// 預設表單變數 (新增模式)
$form_action = 'add_member';
$form_id = '';
$form_username = '';
$form_display_name = '';
$form_role = 'player';
$form_title = '➕ 新增家庭成員';

// ==========================================
// 1. 處理 POST 請求 (新增、修改、刪除、初始化)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // 處理：刪除成員
    if ($action === 'delete_member' && !empty($_POST['member_id'])) {
        $member_id = (int)$_POST['member_id'];
        
        if ($member_id === (int)$current_user_id) {
            $error_msg = "操作失敗：您不能刪除您自己目前的帳號！";
        } else {
            try {
                $stmt = $mysql_db->prepare("SELECT sqlite_file FROM users WHERE id = :id AND family_id = :family_id");
                $stmt->execute([':id' => $member_id, ':family_id' => $family_id]);
                $user_to_delete = $stmt->fetch();

                if ($user_to_delete) {
                    $stmt_del = $mysql_db->prepare("DELETE FROM users WHERE id = :id");
                    $stmt_del->execute([':id' => $member_id]);

                    if (!empty($user_to_delete['sqlite_file']) && file_exists('../' . $user_to_delete['sqlite_file'])) {
                        unlink('../' . $user_to_delete['sqlite_file']);
                    }
                    $success_msg = "成員已成功刪除！";
                } else {
                    $error_msg = "找不到該成員或無權限刪除。";
                }
            } catch (PDOException $e) {
                $error_msg = "刪除失敗：" . $e->getMessage();
            }
        }
    }
    // 處理：初始化成員資料
    elseif ($action === 'init_member' && !empty($_POST['member_id'])) {
        $member_id = (int)$_POST['member_id'];
        
        try {
            $stmt = $mysql_db->prepare("SELECT display_name, sqlite_file FROM users WHERE id = :id AND family_id = :family_id AND role = 'player'");
            $stmt->execute([':id' => $member_id, ':family_id' => $family_id]);
            $player_to_init = $stmt->fetch();

            if ($player_to_init && !empty($player_to_init['sqlite_file']) && file_exists('../' . $player_to_init['sqlite_file'])) {
                $sqlite_db = getPlayerSQLiteConnection($player_to_init['sqlite_file']);
                
                // 1. 強制清空並重建 SQLite 所有進度表 (包含股市庫存與大富翁福利)
                $sqlite_reset = "
                    DROP TABLE IF EXISTS wallet;
                    DROP TABLE IF EXISTS transaction_logs;
                    DROP TABLE IF EXISTS task_history;
                    DROP TABLE IF EXISTS inventory;
                    DROP TABLE IF EXISTS active_buffs;
                    DROP TABLE IF EXISTS time_bank;
                    DROP TABLE IF EXISTS stock_portfolio; 
                    DROP TABLE IF EXISTS claimed_events;

                    CREATE TABLE wallet (id INTEGER PRIMARY KEY, balance_minutes INTEGER DEFAULT 0);
                    INSERT INTO wallet (balance_minutes) VALUES (50);
                    
                    CREATE TABLE transaction_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, action_type TEXT, amount INTEGER, description TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
                    INSERT INTO transaction_logs (action_type, amount, description) VALUES ('system', 50, '初始發放時間 (帳號重置)');
                    
                    CREATE TABLE task_history (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, task_name TEXT, estimated_time INTEGER, actual_time INTEGER, stars INTEGER, earned_minutes INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
                    
                    CREATE TABLE inventory (id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER, item_name TEXT, quantity INTEGER DEFAULT 0);
                    
                    CREATE TABLE active_buffs (id INTEGER PRIMARY KEY AUTOINCREMENT, buff_type TEXT, effect_value REAL DEFAULT 1.0, active_count INTEGER DEFAULT 0);
                    
                    CREATE TABLE time_bank (id INTEGER PRIMARY KEY, balance_minutes INTEGER DEFAULT 0, last_interest_calc DATETIME DEFAULT CURRENT_TIMESTAMP);
                    INSERT INTO time_bank (balance_minutes) VALUES (0);

                    CREATE TABLE stock_portfolio (id INTEGER PRIMARY KEY AUTOINCREMENT, stock_id INTEGER UNIQUE, stock_code TEXT, stock_name TEXT, total_shares INTEGER DEFAULT 0, average_cost REAL DEFAULT 0.0);
                    
                    CREATE TABLE claimed_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event_id INTEGER, claimed_date TEXT);
                ";
                $sqlite_db->exec($sqlite_reset);

                // 2. 刪除該玩家在 MySQL 上的實體兌換券紀錄
                $stmt_del_redemptions = $mysql_db->prepare("DELETE FROM reward_redemptions WHERE player_id = :pid AND family_id = :fid");
                $stmt_del_redemptions->execute([':pid' => $member_id, ':fid' => $family_id]);

                // 3. 刪除該玩家在 MySQL 上「還沒發動的股市魔法」
                $stmt_del_magic = $mysql_db->prepare("DELETE FROM stock_market_events WHERE player_id = :pid");
                $stmt_del_magic->execute([':pid' => $member_id]);

                $success_msg = "♻️ 玩家「{$player_to_init['display_name']}」的資料已成功初始化，包含股市與卡牌已完全歸零！";
            } else {
                $error_msg = "找不到該玩家資料，或該成員不是玩家身份。";
            }
        } catch (Exception $e) {
            $error_msg = "初始化失敗：" . $e->getMessage();
        }
    }
    // 處理：修改成員
    elseif ($action === 'edit_member' && !empty($_POST['member_id'])) {
        $member_id = (int)$_POST['member_id'];
        $display_name = trim($_POST['display_name']);
        $password = $_POST['password']; 

        if (empty($display_name)) {
            $error_msg = "顯示暱稱不可為空！";
        } else {
            try {
                if (empty($password)) {
                    $sql = "UPDATE users SET display_name = :display_name WHERE id = :id AND family_id = :family_id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':display_name' => $display_name, ':id' => $member_id, ':family_id' => $family_id]);
                } else {
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
                    $sql = "UPDATE users SET display_name = :display_name, password_hash = :password_hash WHERE id = :id AND family_id = :family_id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':display_name' => $display_name, ':password_hash' => $password_hash, ':id' => $member_id, ':family_id' => $family_id]);
                }
                $success_msg = "成員「{$display_name}」資料修改成功！";
            } catch (PDOException $e) {
                $error_msg = "修改失敗：" . $e->getMessage();
            }
        }
    }
    // 處理：新增成員
    elseif ($action === 'add_member') {
        $username = trim($_POST['username']);
        $password = $_POST['password'];
        $display_name = trim($_POST['display_name']);
        $role = ($_POST['role'] === 'admin') ? 'admin' : 'player';

        if (empty($username) || empty($password) || empty($display_name)) {
            $error_msg = "所有欄位皆為必填！";
        } else {
            try {
                $stmt_check = $mysql_db->prepare("SELECT id FROM users WHERE username = :username");
                $stmt_check->execute([':username' => $username]);
                
                if ($stmt_check->fetch()) {
                    $error_msg = "此帳號已被佔用，請換一個。";
                } else {
                    $mysql_db->beginTransaction();
                    $sqlite_path = null;
                    if ($role === 'player') {
                        $safe_uname = preg_replace('/[^a-zA-Z0-9_-]/', '', $username);
                        $sqlite_path = "database/user_" . $safe_uname . "_" . uniqid() . ".sqlite";
                    }
                    
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
                    $sql_user = "INSERT INTO users (family_id, username, password_hash, role, display_name, sqlite_file) 
                                 VALUES (:family_id, :username, :password_hash, :role, :display_name, :sqlite_file)";
                    $stmt_user = $mysql_db->prepare($sql_user);
                    $stmt_user->execute([
                        ':family_id' => $family_id,
                        ':username' => $username,
                        ':password_hash' => $password_hash,
                        ':role' => $role,
                        ':display_name' => $display_name,
                        ':sqlite_file' => $sqlite_path
                    ]);

                    if ($role === 'player') {
                        $sqlite_db = getPlayerSQLiteConnection($sqlite_path);
                        $sqlite_setup = "
                            CREATE TABLE wallet (id INTEGER PRIMARY KEY, balance_minutes INTEGER DEFAULT 0);
                            INSERT INTO wallet (balance_minutes) VALUES (50);
                            CREATE TABLE transaction_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, action_type TEXT, amount INTEGER, description TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
                            INSERT INTO transaction_logs (action_type, amount, description) VALUES ('system', 50, '初始發放時間');
                            CREATE TABLE task_history (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, task_name TEXT, estimated_time INTEGER, actual_time INTEGER, stars INTEGER, earned_minutes INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
                            CREATE TABLE inventory (id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER, item_name TEXT, quantity INTEGER DEFAULT 0);
                            CREATE TABLE active_buffs (id INTEGER PRIMARY KEY AUTOINCREMENT, buff_type TEXT, effect_value REAL DEFAULT 1.0, active_count INTEGER DEFAULT 0);
                            CREATE TABLE time_bank (id INTEGER PRIMARY KEY, balance_minutes INTEGER DEFAULT 0, last_interest_calc DATETIME DEFAULT CURRENT_TIMESTAMP);
                            INSERT INTO time_bank (balance_minutes) VALUES (0);
                            CREATE TABLE stock_portfolio (id INTEGER PRIMARY KEY AUTOINCREMENT, stock_id INTEGER UNIQUE, stock_code TEXT, stock_name TEXT, total_shares INTEGER DEFAULT 0, average_cost REAL DEFAULT 0.0);
                            CREATE TABLE claimed_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event_id INTEGER, claimed_date TEXT);
                        ";
                        $sqlite_db->exec($sqlite_setup);
                        $success_msg = "成功建立玩家「{$display_name}」！";
                    } else {
                        $success_msg = "成功建立共同管理員「{$display_name}」！";
                    }
                    $mysql_db->commit();
                }
            } catch (Exception $e) {
                if ($mysql_db->inTransaction()) $mysql_db->rollBack();
                $error_msg = "建立失敗：" . $e->getMessage();
            }
        }
    }
}

// ==========================================
// 2. 處理 GET 請求 (載入要修改的成員資料)
// ==========================================
if (isset($_GET['edit_id'])) {
    try {
        $stmt = $mysql_db->prepare("SELECT * FROM users WHERE id = :id AND family_id = :family_id");
        $stmt->execute([':id' => $_GET['edit_id'], ':family_id' => $family_id]);
        $edit_data = $stmt->fetch();

        if ($edit_data) {
            $form_action = 'edit_member';
            $form_id = $edit_data['id'];
            $form_username = $edit_data['username'];
            $form_display_name = $edit_data['display_name'];
            $form_role = $edit_data['role'];
            $form_title = '✏️ 修改成員資料';
        } else {
            $error_msg = "找不到該成員資料。";
        }
    } catch (PDOException $e) {
        $error_msg = "讀取資料失敗：" . $e->getMessage();
    }
}

// ==========================================
// 3. 撈取目前家庭的所有成員
// ==========================================
try {
    $stmt_members = $mysql_db->prepare("SELECT * FROM users WHERE family_id = :family_id ORDER BY role ASC, created_at ASC");
    $stmt_members->execute([':family_id' => $family_id]);
    $members = $stmt_members->fetchAll();
} catch (PDOException $e) {
    die("讀取資料失敗");
}
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>家庭成員管理 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #f4f7f6; margin: 0; padding: 0; }
        
        .container { max-width: 900px; margin: 20px auto; padding: 0 20px; }
        .card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
        
        .form-inline { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; align-items: end; }
        .form-group { margin-bottom: 10px; }
        label { display: block; margin-bottom: 5px; font-size: 0.9rem; font-weight: bold; }
        input, select { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        input[readonly] { background-color: #e9ecef; color: #6c757d; cursor: not-allowed; }
        
        .btn-submit { background-color: #27ae60; color: white; border: none; padding: 9px; border-radius: 4px; cursor: pointer; font-weight: bold; margin-bottom: 10px; }
        .btn-cancel { background-color: #95a5a6; color: white; text-decoration: none; padding: 8px; border-radius: 4px; display: inline-block; text-align: center; font-size: 0.9rem; margin-bottom: 10px;}
        
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        
        .btn-edit { background-color: #f39c12; color: white; padding: 5px 10px; text-decoration: none; border-radius: 4px; font-size: 0.85rem; margin-right: 5px;}
        .btn-delete { background-color: #e74c3c; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
        
        .btn-init { background-color: #8e44ad; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85rem; margin-right: 5px; transition: 0.2s;}
        .btn-init:hover { background-color: #9b59b6; transform: scale(1.05); }

        .role-admin { color: #e67e22; font-weight: bold; background: #fdf2e9; padding: 3px 8px; border-radius: 12px; font-size: 0.85em; }
        .role-player { color: #2ecc71; font-weight: bold; background: #eafaf1; padding: 3px 8px; border-radius: 12px; font-size: 0.85em; }
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; font-weight: bold; }
        .alert-error { background: #f8d7da; color: #721c24; }
        .alert-success { background: #d4edda; color: #155724; }
    </style>
</head>
<body>

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

<div class="container">
    <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
    <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>

    <div class="card" id="member-form">
        <h3><?php echo $form_title; ?></h3>
        <form method="POST" class="form-inline" action="family.php">
            <input type="hidden" name="action" value="<?php echo $form_action; ?>">
            <input type="hidden" name="member_id" value="<?php echo $form_id; ?>">
            
            <div class="form-group">
                <label>角色身份</label>
                <?php if ($form_action === 'edit_member'): ?>
                    <input type="text" value="<?php echo ($form_role === 'admin') ? '管理員 (不可改)' : '玩家 (不可改)'; ?>" readonly>
                <?php else: ?>
                    <select name="role">
                        <option value="player">👦👧 玩家 (小孩)</option>
                        <option value="admin">👨👩 管理員 (家長)</option>
                    </select>
                <?php endif; ?>
            </div>
            
            <div class="form-group">
                <label>登入帳號</label>
                <input type="text" name="username" value="<?php echo htmlspecialchars($form_username); ?>" <?php echo ($form_action === 'edit_member') ? 'readonly title="帳號建立後無法修改"' : 'required placeholder="如: kid_mary"'; ?>>
            </div>

            <div class="form-group">
                <label>顯示暱稱</label>
                <input type="text" name="display_name" required value="<?php echo htmlspecialchars($form_display_name); ?>" placeholder="如: 媽媽 / 小美">
            </div>

            <div class="form-group">
                <label>設定密碼</label>
                <input type="password" name="password" <?php echo ($form_action === 'add_member') ? 'required' : 'placeholder="不修改請留白"'; ?>>
            </div>
            
            <button type="submit" class="btn-submit"><?php echo ($form_action === 'edit_member') ? '儲存修改' : '建立帳號'; ?></button>
            
            <?php if ($form_action === 'edit_member'): ?>
                <a href="family.php" class="btn-cancel">取消</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h3>👥 成員清單</h3>
        <table>
            <thead>
                <tr>
                    <th>顯示名稱</th>
                    <th>登入帳號</th>
                    <th>身份</th>
                    <th>建立時間</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $m): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($m['display_name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($m['username']); ?></td>
                    <td>
                        <span class="<?php echo ($m['role'] == 'admin' ? 'role-admin' : 'role-player'); ?>">
                            <?php echo ($m['role'] == 'admin' ? '管理員' : '玩家'); ?>
                        </span>
                    </td>
                    <td style="font-size: 0.8rem; color: #95a5a6;"><?php echo date('Y-m-d', strtotime($m['created_at'])); ?></td>
                    <td>
                        <a href="family.php?edit_id=<?php echo $m['id']; ?>#member-form" class="btn-edit">修改</a>
                        
                        <?php if ($m['id'] !== $current_user_id): ?>
                            
                            <?php if ($m['role'] === 'player'): ?>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('⚠️ 嚴重警告！\n\n確定要【初始化】「<?php echo htmlspecialchars($m['display_name']); ?>」的遊戲進度嗎？\n\n這將會永遠清空：\n1. 錢包餘額與銀行存款\n2. 背包裡所有的卡牌與道具\n3. 過去所有的任務執行紀錄\n4. 股市庫存與未發動的魔法\n\n操作後將恢復成剛建立的新帳號狀態，資料無法復原！\n確定要繼續嗎？');">
                                    <input type="hidden" name="action" value="init_member">
                                    <input type="hidden" name="member_id" value="<?php echo $m['id']; ?>">
                                    <button type="submit" class="btn-init" title="初始化並清空進度">重置</button>
                                </form>
                            <?php endif; ?>

                            <form method="POST" style="display:inline;" onsubmit="return confirm('確定要刪除「<?php echo htmlspecialchars($m['display_name']); ?>」嗎？\n如果是玩家，他所有的時間與紀錄都會被永久刪除喔！');">
                                <input type="hidden" name="action" value="delete_member">
                                <input type="hidden" name="member_id" value="<?php echo $m['id']; ?>">
                                <button type="submit" class="btn-delete">刪除</button>
                            </form>

                        <?php else: ?>
                            <span style="font-size: 0.8rem; color: #ccc;">(您自己)</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>