<?php
/**
 * 后台管理员认证模块
 */
require_once __DIR__ . '/../config.php';

class AdminAuth {
    private $db;

    public function __construct() {
        $this->db = getDB();
    }

    /** 检查是否已登录 */
    public function isLoggedIn() {
        return isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0;
    }

    /** 登录验证 */
    public function login($username, $password) {
        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE username = ?");
        $stmt->execute([$username]);
        $admin = $stmt->fetch();

        if (!$admin) return false;

        // MD5验证（可升级为bcrypt）
        if (md5($password) === $admin['password']) {
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_username'] = $admin['username'];
            $_SESSION['admin_nickname'] = $admin['nickname'];

            // 更新登录时间
            $stmt = $this->db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
            $stmt->execute([$admin['id']]);
            return true;
        }
        return false;
    }

    /** 退出登录 */
    public function logout() {
        unset($_SESSION['admin_id']);
        unset($_SESSION['admin_username']);
        unset($_SESSION['admin_nickname']);
    }

    /** 获取当前管理员信息 */
    public function getAdmin() {
        if (!$this->isLoggedIn()) return null;
        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE id = ?");
        $stmt->execute([$_SESSION['admin_id']]);
        return $stmt->fetch();
    }

    /** 修改密码 */
    public function changePassword($oldPwd, $newPwd) {
        $admin = $this->getAdmin();
        if (!$admin) return false;
        if (md5($oldPwd) !== $admin['password']) return false;

        $stmt = $this->db->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
        $stmt->execute([md5($newPwd), $admin['id']]);
        return true;
    }

    /** 强制跳转登录 */
    public static function requireLogin() {
        if (!isset($_SESSION['admin_id'])) {
            header('Location: login.php');
            exit;
        }
    }
}