<?php
/**
 * 炎酷CMS - 后台登录校验与公共助手
 * 每个后台页面开头：define('YKCMS',1); require .../inc/auth.php;
 */
defined('YKCMS') or exit('Access Denied');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once dirname(dirname(dirname(__DIR__))) . '/inc/functions.php';

// 后台 URL 基础路径（兼容子目录安装）
$ykScriptDir = str_replace('\\', '/', dirname(isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : ''));
$ykPos = strpos($ykScriptDir, '/admin');
define('ADMIN_URL', ($ykPos !== false ? substr($ykScriptDir, 0, $ykPos) : '') . '/admin');
// 站点根 URL 与站点根物理路径
define('SITE_URL', substr(ADMIN_URL, 0, -strlen('/admin')));
define('SITE_PATH', dirname(dirname(dirname(__DIR__))));

/**
 * 校验登录态，未登录跳登录页
 */
function admin_check_login() {
    if (empty($_SESSION['yk_admin_id'])) {
        header('Location: ' . ADMIN_URL . '/login.php');
        exit;
    }
}

/**
 * 当前登录管理员（带静态缓存）
 * @return array|null
 */
function admin_current() {
    static $admin = false;
    if ($admin === false) {
        $admin = null;
        if (!empty($_SESSION['yk_admin_id'])) {
            $admin = db_one('SELECT id, username, mobile, role, add_time FROM ' . DB_PREFIX . 'admin WHERE id = ?', array((int)$_SESSION['yk_admin_id']));
            if (!$admin) {
                // 账号已被删除，强制退出
                unset($_SESSION['yk_admin_id'], $_SESSION['yk_admin_name']);
                header('Location: ' . ADMIN_URL . '/login.php');
                exit;
            }
        }
    }
    return $admin;
}

/**
 * CSRF 令牌
 */
function csrf_token() {
    if (empty($_SESSION['yk_csrf'])) {
        $_SESSION['yk_csrf'] = md5(uniqid(mt_rand(), true));
    }
    return $_SESSION['yk_csrf'];
}

/** CSRF 隐藏域 */
function csrf_field() {
    return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">';
}

/**
 * 写操作 CSRF 校验，失败直接终止
 */
function csrf_check() {
    $token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
    if ($token === '' || empty($_SESSION['yk_csrf']) || !hash_equals($_SESSION['yk_csrf'], $token)) {
        http_response_code(403);
        exit('CSRF 校验失败，请返回刷新页面后重试');
    }
}

/**
 * 写操作日志
 */
function admin_log($action, $detail = '') {
    $admin = admin_current();
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    db_insert('INSERT INTO ' . DB_PREFIX . 'log (admin, action, detail, ip, add_time) VALUES (?, ?, ?, ?, ?)', array(
        $admin ? $admin['username'] : (isset($_SESSION['yk_admin_name']) ? $_SESSION['yk_admin_name'] : '-'),
        $action,
        mb_substr((string)$detail, 0, 480),
        $ip,
        time(),
    ));
}

/** 一次性提示消息 */
function flash_set($msg, $type = 'ok') {
    $_SESSION['yk_flash'] = array($msg, $type);
}
function flash_get() {
    if (!empty($_SESSION['yk_flash'])) {
        $f = $_SESSION['yk_flash'];
        unset($_SESSION['yk_flash']);
        return $f;
    }
    return null;
}

/** 后台分页 HTML */
function admin_pager($total, $page, $pageSize, $baseUrl) {
    $pages = max(1, (int)ceil($total / max(1, $pageSize)));
    if ($pages <= 1) return '';
    $baseUrl .= (strpos($baseUrl, '?') !== false ? '&' : '?') . 'p=';
    $html = '<div class="yk-pager">';
    if ($page > 1) $html .= '<a href="' . e($baseUrl . ($page - 1)) . '">上一页</a>';
    for ($i = 1; $i <= $pages; $i++) {
        $cls = $i == $page ? ' class="on"' : '';
        $html .= '<a' . $cls . ' href="' . e($baseUrl . $i) . '">' . $i . '</a>';
    }
    if ($page < $pages) $html .= '<a href="' . e($baseUrl . ($page + 1)) . '">下一页</a>';
    return $html . '</div>';
}

/**
 * 栏目树铺平为带层级的下拉选项列表
 * @return array 每行含 id/name/depth
 */
function column_options($pid = 0, $depth = 0, &$out = array()) {
    $rows = db_all('SELECT id, name FROM ' . DB_PREFIX . 'column WHERE pid = ? ORDER BY sort ASC, id ASC', array($pid));
    foreach ($rows as $r) {
        $r['depth'] = $depth;
        $out[] = $r;
        column_options($r['id'], $depth + 1, $out);
    }
    return $out;
}

/** 取某栏目的全部后代 ID（含自身） */
function column_descendant_ids($id) {
    $ids = array((int)$id);
    $children = db_all('SELECT id FROM ' . DB_PREFIX . 'column WHERE pid = ?', array((int)$id));
    foreach ($children as $c) {
        $ids = array_merge($ids, column_descendant_ids($c['id']));
    }
    return $ids;
}

admin_check_login();
