<?php
// 引入資料庫連線與啟動 Session
require_once 'config.php';

// 如果已經登入過，就直接幫他導向，不用再登入一次
if (isset($_SESSION['user_id'])) {
    if ($_SESSION['role'] === 'admin') {
        header("Location: admin/tasks.php"); // 暫時先導向任務頁面，之後會幫家長做一個專屬首頁
    } else {
        header("Location: player/dashboard.php");
    }
    exit;
}

$error_msg = '';

// 處理登入表單送出
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $error_msg = "請輸入帳號與密碼！";
    } else {
        try {
            // 從 MySQL 撈取該帳號資料
            $stmt = $mysql_db->prepare("SELECT * FROM users WHERE username = :username");
            $stmt->execute([':username' => $username]);
            $user = $stmt->fetch();

            // 驗證密碼是否正確
            if ($user && password_verify($password, $user['password_hash'])) {
                
                // 登入成功！將重要資訊存入 Session 中
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['family_id'] = $user['family_id']; // ★ 本次升級重點：記錄他屬於哪一個家庭
                $_SESSION['username'] = $user['username'];
                $_SESSION['display_name'] = $user['display_name'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['sqlite_file'] = $user['sqlite_file']; // 家長會是 NULL，小孩會有路徑

                // 依據角色進行網頁導向
                if ($user['role'] === 'admin') {
                    header("Location: admin/tasks.php");
                } else {
                    header("Location: player/dashboard.php");
                }
                exit;
                
            } else {
                $error_msg = "帳號或密碼錯誤，請檢查後重試。";
            }
        } catch (PDOException $e) {
            $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 15px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 20px; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #34495e; }
        input[type="text"], input[type="password"] { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; font-size: 16px; transition: border-color 0.3s; }
        input[type="text"]:focus, input[type="password"]:focus { border-color: #3498db; outline: none; }
        button { background-color: #3498db; 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 #2980b9; transition: transform 0.1s, box-shadow 0.1s; }
        button:hover { background-color: #2980b9; }
        button:active { transform: translateY(4px); box-shadow: 0 0 0 #2980b9; }
        .alert { padding: 10px; border-radius: 6px; margin-bottom: 15px; text-align: center; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .footer-link { text-align: center; margin-top: 20px; font-size: 0.95rem; }
        .footer-link a { color: #27ae60; text-decoration: none; font-weight: bold; }
    </style>
</head>
<body>

<div class="card">
    <h1>⏳ 時間大富翁</h1>

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

    <form method="POST" action="login.php">
        <input type="hidden" name="action" value="login">
        
        <div class="form-group">
            <label for="username">登入帳號</label>
            <input type="text" id="username" name="username" required placeholder="請輸入帳號">
        </div>

        <div class="form-group">
            <label for="password">密碼</label>
            <input type="password" id="password" name="password" required placeholder="請輸入密碼">
        </div>

        <button type="submit">登入遊戲</button>
    </form>

    <div class="footer-link">
        還沒有專屬的家庭嗎？ <a href="register.php">建立家庭系統</a>
    </div>
</div>

</body>
</html>