<?php
session_start();
require_once __DIR__ . '/db/config.php';

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo = db();
        if ($action === 'register') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';

            if (empty($username) || empty($password)) {
                echo json_encode(['code' => 1, 'msg' => '用户名和密码不能为空']);
                exit;
            }

            if ($password !== $confirm_password) {
                echo json_encode(['code' => 1, 'msg' => '两次输入的密码不一致']);
                exit;
            }

            // Check if user exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                echo json_encode(['code' => 1, 'msg' => '用户名已存在']);
                exit;
            }

            $hash = password_hash($password, PASSWORD_DEFAULT);
            
            // Check if this is the first user
            $stmt = $pdo->query("SELECT COUNT(*) FROM users");
            $count = $stmt->fetchColumn();
            $role = ($count == 0) ? 'admin' : 'user';

            $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)");
            $stmt->execute([$username, $hash, $role]);
            
            // Auto login after registration
            $userId = $pdo->lastInsertId();
            $_SESSION['user_id'] = $userId;
            $_SESSION['username'] = $username;
            $_SESSION['role'] = $role;

            echo json_encode(['code' => 0, 'msg' => '注册成功']);
            exit;
        } elseif ($action === 'login') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';

            if (empty($username) || empty($password)) {
                echo json_encode(['code' => 1, 'msg' => '用户名和密码不能为空']);
                exit;
            }

            $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password_hash'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                echo json_encode(['code' => 0, 'msg' => '登录成功']);
                exit;
            } else {
                echo json_encode(['code' => 1, 'msg' => '用户名或密码错误']);
                exit;
            }
        }
    } catch (Exception $e) {
        echo json_encode(['code' => 1, 'msg' => '服务器错误: ' . $e->getMessage()]);
        exit;
    }
}

if ($action === 'logout') {
    session_destroy();
    header('Location: index.php');
    exit;
}

echo json_encode(['code' => 1, 'msg' => '无效的请求']);