<?php
// api/audit_members.php - 新兵審核台 (LocalStorage 無敵憑證版)
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];

// 🟢 API 模式：撈取待審核新兵 (Level 0)
if ($method === 'GET' && isset($_GET['api']) && $_GET['api'] == 'list') {
    header("Content-Type: application/json; charset=UTF-8");
    try {
        // 假設 level = 0 代表尚未核准的新兵
        $stmt = $pdo->query("SELECT id, username, email, created_at FROM users WHERE level = 0 ORDER BY created_at ASC");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["status" => "success", "data" => $data]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}

// 🔴 API 模式：執行核准或駁回
if ($method === 'POST') {
    header("Content-Type: application/json; charset=UTF-8");
    $input = json_decode(file_get_contents("php://input"), true);
    
    $admin_id = $input['admin_id'] ?? 0;
    $target_id = $input['target_id'] ?? 0;
    $action = $input['action'] ?? '';

    try {
        // 1. 終極防護：確認執行者真的是天啟者
        $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        if ($stmt->fetchColumn() < 99) throw new Exception("越權操作：您不是天啟者！");

        if ($action === 'approve') {
            // 核准：升級為正式礦工 (Level 1)
            $stmt = $pdo->prepare("UPDATE users SET level = 1 WHERE id = ?");
            $stmt->execute([$target_id]);
            $msg = "已核准，成為正式礦工！";
        } else if ($action === 'reject') {
            // 駁回：直接刪除該帳號
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$target_id]);
            $msg = "已無情駁回並刪除檔案。";
        }

        echo json_encode(["status" => "success", "message" => $msg]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}

// 🔵 網頁介面模式：如果不是 API 請求，就輸出華麗的前端介面
?>
<!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>
        :root { --primary: #00ff88; --bg: #0a0a0a; --card: #161b22; --text: #e0e0e0; }
        body { background-color: var(--bg); color: var(--text); font-family: 'Segoe UI', sans-serif; padding: 20px; margin: 0; min-height: 100vh; }
        .header { text-align: center; border-bottom: 1px dashed #333; padding-bottom: 20px; margin-bottom: 30px; }
        .header h1 { color: var(--primary); margin: 0; letter-spacing: 2px; }
        
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; max-width: 1000px; margin: 0 auto; }
        .card { background: var(--card); border: 1px solid #333; border-radius: 10px; padding: 20px; display: flex; flex-direction: column; transition: 0.3s; }
        .card:hover { border-color: var(--primary); box-shadow: 0 0 15px rgba(0,255,136,0.1); }
        
        .info { flex-grow: 1; }
        .info h3 { margin: 0 0 10px 0; color: #fff; font-size: 1.2em; border-left: 3px solid var(--primary); padding-left: 10px; }
        .info p { margin: 8px 0; color: #aaa; font-size: 0.9em; }
        
        .actions { display: flex; gap: 10px; margin-top: 20px; }
        .btn-approve { flex: 1; background: #00a86b; color: #fff; border: none; padding: 12px; font-weight: bold; cursor: pointer; border-radius: 5px; transition: 0.3s; }
        .btn-approve:hover { background: #00ff88; color: #000; }
        .btn-reject { flex: 1; background: transparent; color: #ff5252; border: 1px solid #ff5252; padding: 12px; font-weight: bold; cursor: pointer; border-radius: 5px; transition: 0.3s; }
        .btn-reject:hover { background: #ff5252; color: #fff; }

        .back-link { display: block; text-align: center; margin-top: 40px; color: #888; text-decoration: none; font-size: 16px; }
        .back-link:hover { color: var(--primary); }
    </style>
</head>
<body>

<div class="header">
    <h1>⚖️ 新兵審核台</h1>
    <p>天啟者連線中：<span id="admin_name" style="color:var(--primary); font-weight:bold;">...</span></p>
</div>

<div class="grid" id="audit_screen">
    <p style="text-align:center; width: 100%; color:#888;">📡 正在調閱新兵註冊名單...</p>
</div>

<a href="../index.html" class="back-link">← 返回戰情駕駛艙</a>

<script>
    // 🛡️ 無敵憑證讀取
    let adminId = null;
    try {
        const userStr = localStorage.getItem('zoo_user');
        if (!userStr) throw new Error("未登入");
        
        let user = JSON.parse(userStr);
        if (typeof user === 'string') user = JSON.parse(user); 
        
        if (user.level < 99) throw new Error("權限不足，僅限天啟者進入");
        
        adminId = user.user_id || user.id;
        document.getElementById('admin_name').innerText = user.username;
    } catch(e) {
        alert("天啟禁區，閒者避易。(" + e.message + ")");
        window.location.href = '../index.html';
    }

    // 撈取新兵名單
    async function loadMembers() {
        const screen = document.getElementById('audit_screen');
        try {
            const res = await fetch('audit_members.php?api=list&t=' + new Date().getTime());
            const json = await res.json();
            
            if (json.status === 'success') {
                screen.innerHTML = '';
                if (json.data.length === 0) {
                    screen.innerHTML = '<p style="text-align:center; width:100%; color:#00ff88; font-size:1.1em; padding:40px; border:1px dashed #00ff88; border-radius:10px;">🛡️ 目前沒有等待審核的新兵。</p>';
                    return;
                }

                json.data.forEach(item => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="info">
                            <h3>👤 ${item.username}</h3>
                            <p>📧 Email：${item.email}</p>
                            <p>🕒 註冊時間：${item.created_at}</p>
                            <p style="color:#ffd700; font-size:0.8em; margin-top:15px;">狀態：等待天啟者核准 (LV.0)</p>
                        </div>
                        <div class="actions">
                            <button class="btn-approve" onclick="processMember(${item.id}, 'approve')">✅ 核准入伍</button>
                            <button class="btn-reject" onclick="processMember(${item.id}, 'reject')">❌ 駁回 (刪除)</button>
                        </div>
                    `;
                    screen.appendChild(card);
                });
            } else {
                screen.innerHTML = `<p style="color:red; text-align:center; width:100%;">讀取失敗：${json.message}</p>`;
            }
        } catch (err) {
            screen.innerHTML = '<p style="color:red; text-align:center; width:100%;">伺服器連線異常</p>';
        }
    }

    // 執行核准或駁回
    async function processMember(targetId, action) {
        const confirmMsg = action === 'approve' 
            ? '確定要「核准」嗎？該員將獲得正式礦工權限。' 
            : '確定要「駁回」嗎？該帳號將被永久刪除！';
            
        if (!confirm(confirmMsg)) return;

        try {
            const res = await fetch('audit_members.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    admin_id: adminId,
                    target_id: targetId,
                    action: action
                })
            });
            const json = await res.json();
            
            if (json.status === 'success') {
                loadMembers(); // 重新載入列表
            } else {
                alert("❌ 執行失敗: " + json.message);
            }
        } catch (err) {
            alert("伺服器連線異常！");
        }
    }

    // 啟動加載
    if (adminId) loadMembers();
</script>

</body>
</html>