<?php
// 🐘 Elephant's Protocol: dashboard_data.php
// 用途：安全地吐出當前登入者的個資 (錢、等級、暱稱)

header('Content-Type: application/json; charset=utf-8');
session_start();
require 'db.php';

// 1. 嚴格安檢：沒登入的人滾回門口
if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // 未授權狀態碼
    echo json_encode(['success' => false, 'message' => '尚未登入']);
    exit;
}

try {
    // 2. 根據 Session ID 去資料庫撈最新的資料
    // (為什麼要重撈？因為錢的數量隨時會變，不能只讀 Session 裡的舊資料)
    $stmt = $pdo->prepare("SELECT username, email, coins, level, is_verified FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if ($user) {
        // 3. 回傳數據給前端 (注意：絕對不要回傳 password！)
        echo json_encode([
            'success' => true,
            'user' => [
                'username' => $user['username'],
                'email'    => $user['email'],
                'coins'    => number_format($user['coins']), // 幫忙加逗號 (999,999)
                'level'    => $user['level'],
                'is_verified' => $user['is_verified']
            ]
        ]);
    } else {
        // 極端情況：Session 還在，但資料庫裡人被砍了
        session_destroy();
        echo json_encode(['success' => false, 'message' => '帳號異常，請重新登入']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => '讀取失敗']);
}
?>