<?php
// 引入資料庫連線設定檔
require_once 'config.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'register_family') {
    // 取得並過濾表單資料
    $family_name = trim($_POST['family_name']);
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $display_name = trim($_POST['display_name']);
    
    // 基本驗證
    if (empty($family_name) || empty($username) || empty($password) || empty($display_name)) {
        $error_msg = "所有欄位皆為必填！";
    } else {
        try {
            // 檢查帳號是否已被其他人使用 (跨家庭也不能重複)
            $stmt = $mysql_db->prepare("SELECT id FROM users WHERE username = :username");
            $stmt->execute([':username' => $username]);
            if ($stmt->fetch()) {
                $error_msg = "此登入帳號已經被註冊過了，請換一個帳號喔！";
            } else {
                // ==========================================
                // ★ 開始資料庫交易 (Transaction)
                // 確保「建立家庭」與「建立帳號」同時成功，若失敗則全部還原
                // ==========================================
                $mysql_db->beginTransaction();

                // 1. 建立「家庭」資料
                $stmt_family = $mysql_db->prepare("INSERT INTO families (family_name) VALUES (:family_name)");
                $stmt_family->execute([':family_name' => $family_name]);
                
                // 取得剛剛自動生成的 family_id
                $family_id = $mysql_db->lastInsertId(); 

                // 2. 建立「家長 (admin)」帳號，並綁定剛剛的 family_id
                $password_hash = password_hash($password, PASSWORD_DEFAULT);

                // 家長不玩遊戲，不需要專屬的 SQLite，所以 sqlite_file 存入 NULL
                $sql_user = "INSERT INTO users (family_id, username, password_hash, role, display_name, sqlite_file) 
                             VALUES (:family_id, :username, :password_hash, 'admin', :display_name, NULL)";
                $stmt_user = $mysql_db->prepare($sql_user);
                $stmt_user->execute([
                    ':family_id' => $family_id,
                    ':username' => $username,
                    ':password_hash' => $password_hash,
                    ':display_name' => $display_name
                ]);

                // 確認無誤，提交交易！
                $mysql_db->commit();

                $success_msg = "恭喜！「{$family_name}」的家庭系統已建立完成。請前往登入您的家長管理後台！";
            }
        } catch (PDOException $e) {
            // 發生任何資料庫錯誤時，還原交易 (Rollback)
            if ($mysql_db->inTransaction()) {
                $mysql_db->rollBack();
            }
            $error_msg = "系統錯誤：" . $e->getMessage();
        }
    }
}
?>

<!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', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
        .card { background: #fff; padding: 30px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); width: 100%; max-width: 420px; }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 5px; font-size: 1.6rem; }
        .subtitle { text-align: center; color: #7f8c8d; font-size: 0.9rem; margin-bottom: 25px; }
        
        .form-group { margin-bottom: 18px; }
        label { display: block; margin-bottom: 6px; font-weight: bold; color: #34495e; font-size: 0.95rem; }
        input[type="text"], input[type="password"] { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; font-size: 1rem; transition: border-color 0.3s; }
        input[type="text"]:focus, input[type="password"]:focus { border-color: #3498db; outline: none; box-shadow: 0 0 5px rgba(52, 152, 219, 0.3); }
        
        button { background-color: #27ae60; color: white; border: none; padding: 14px; width: 100%; border-radius: 6px; cursor: pointer; font-size: 1.1rem; font-weight: bold; box-shadow: 0 4px 0 #219653; transition: transform 0.1s, box-shadow 0.1s; margin-top: 10px; }
        button:hover { background-color: #2ecc71; }
        button:active { transform: translateY(4px); box-shadow: 0 0 0 #219653; }
        
        .alert { padding: 12px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: bold; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        
        .footer-link { text-align: center; margin-top: 20px; font-size: 0.95rem; }
        .footer-link a { color: #3498db; text-decoration: none; font-weight: bold; }
        .footer-link a:hover { text-decoration: underline; }
    </style>
</head>
<body>

<div class="card">
    <h1>🏠 註冊家庭系統</h1>
    <div class="subtitle">第一步：由家長建立專屬的家庭空間</div>

    <?php if ($error_msg): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error_msg); ?></div>
    <?php endif; ?>
    <?php if ($success_msg): ?>
        <div class="alert alert-success">
            <?php echo htmlspecialchars($success_msg); ?><br><br>
            <a href="login.php" style="color:#155724; text-decoration:underline;">👉 前往登入</a>
        </div>
    <?php else: ?>
        <form method="POST" action="register.php">
            <input type="hidden" name="action" value="register_family">
            
            <div class="form-group">
                <label for="family_name">家庭名稱</label>
                <input type="text" id="family_name" name="family_name" required placeholder="例如：王家大院、開心家庭">
            </div>

            <div style="height: 1px; background-color: #eee; margin: 25px 0;"></div>

            <div class="form-group">
                <label for="username">家長登入帳號 (英文或數字)</label>
                <input type="text" id="username" name="username" required placeholder="例如：papa_wang">
            </div>

            <div class="form-group">
                <label for="password">家長登入密碼</label>
                <input type="password" id="password" name="password" required placeholder="請設定密碼">
            </div>

            <div class="form-group">
                <label for="display_name">您的顯示名稱</label>
                <input type="text" id="display_name" name="display_name" required placeholder="例如：爸爸、媽媽">
            </div>

            <button type="submit">註冊並建立家庭</button>
        </form>
    <?php endif; ?>

    <div class="footer-link">
        已經有家庭帳號了嗎？ <a href="login.php">直接登入</a>
    </div>
</div>

</body>
</html>