<?php
/**
 * 炎酷CMS - 前台入口
 * 路由：无参数=首页；?col=栏目列表；?art=文章详情；?page=单页；其余 404
 */
define('YKCMS', 1);

require dirname(__DIR__) . '/inc/render.php';

// 访问统计（按 IP 记录每次前台访问；可视化预览不计数）
if (!preview_active()) stats_record();

/* ---------------- 404 页面 ---------------- */

function show_404() {
    http_response_code(404);
    page_head('页面不存在');
    render_header('home');
    echo '<div style="max-width:720px;margin:80px auto;text-align:center;">'
       . '<h1 style="font-size:64px;color:#ddd;margin:0;">404</h1>'
       . '<p style="color:#888;">您访问的页面不存在或已被删除。</p>'
       . '<p><a href="' . e(url_home()) . '">返回首页</a></p>'
       . '</div>';
    render_footer();
    page_foot();
    exit;
}

/* ---------------- 首页 ---------------- */

function route_home() {
    page_head(); // 使用全局 SEO 默认
    render_header('home');
    render_banner();
    $blocks = db_all('SELECT * FROM ' . DB_PREFIX . 'index_block WHERE is_show = 1 ORDER BY sort ASC, id ASC');
    foreach ($blocks as $row) {
        render_block_row($row);
    }
    render_footer(true); // 友情链接仅首页底部显示
    page_foot();
}

/* ---------------- 栏目列表 ?col={id}[&p={页码}] ---------------- */

function route_column() {
    $id = isset($_GET['col']) ? (int)$_GET['col'] : 0;
    // 目录式伪静态 /{flag}/ 入口：按 flag 反查栏目 id
    if ($id <= 0 && !empty($_GET['col_flag'])) {
        $flag = trim((string)$_GET['col_flag']);
        if (preg_match('/^[a-zA-Z0-9_-]+$/', $flag)) {
            $id = (int)db_val('SELECT id FROM ' . DB_PREFIX . 'column WHERE flag = ?', array($flag));
        }
    }
    $p  = isset($_GET['p'])   ? max(1, (int)$_GET['p']) : 1;
    $col = $id > 0 ? db_one('SELECT * FROM ' . DB_PREFIX . 'column WHERE id = ?', array($id)) : null;
    if (!$col || !$col['status']) show_404();

    $total = 0;
    $list  = get_column_articles($id, $p, $col['page_size'], $total);
    $pagerHtml = pager_html($total, $p, $col['page_size'], $id);

    // 侧栏栏目：当前栏目有下级子栏目时显示子栏目；二级栏目则显示所属一级栏目的同级列表
    $side  = array('title' => '', 'url' => '', 'cols' => array(), 'active' => $id);
    $sideCols = db_all("SELECT id, name FROM " . DB_PREFIX . "column
                        WHERE pid = ? AND status = 1 ORDER BY sort ASC, id ASC", array($id));
    if ($sideCols) {
        $side['title'] = $col['name'];
        $side['url']   = url_col($id);
        foreach ($sideCols as $sc) {
            $side['cols'][] = array('id' => (int)$sc['id'], 'name' => $sc['name'], 'url' => url_col($sc['id']));
        }
    } elseif ((int)$col['pid'] > 0) {
        // 二级栏目：侧栏展示所属一级栏目及其全部子栏目（当前栏目高亮）
        $parent = db_one("SELECT id, name FROM " . DB_PREFIX . "column WHERE id = ? AND status = 1", array((int)$col['pid']));
        if ($parent) {
            $siblings = db_all("SELECT id, name FROM " . DB_PREFIX . "column
                                WHERE pid = ? AND status = 1 ORDER BY sort ASC, id ASC", array((int)$parent['id']));
            if ($siblings) {
                $side['title'] = $parent['name'];
                $side['url']   = url_col((int)$parent['id']);
                foreach ($siblings as $sc) {
                    $side['cols'][] = array('id' => (int)$sc['id'], 'name' => $sc['name'], 'url' => url_col($sc['id']));
                }
            }
        }
    }

    // 栏目 SEO 三件套，为空回退栏目名
    page_head(
        $col['seo_title'] !== '' ? $col['seo_title'] : $col['name'],
        $col['seo_keywords'],
        $col['seo_description'] !== '' ? $col['seo_description'] : $col['name']
    );
    render_header('col-' . column_top_id($id));
    $pv = preview_config();
    render_tpl('list', isset($pv['list_tpl']) ? (int)$pv['list_tpl'] : (int)$col['list_tpl'], array('col' => $col, 'list' => $list, 'pager' => $pagerHtml, 'side' => $side));
    render_footer();
    page_foot();
}

/* ---------------- 文章详情 ?art={id}（内容页模板 art_1~3） ---------------- */

function route_article() {
    $id = isset($_GET['art']) ? (int)$_GET['art'] : 0;
    $art = $id > 0 ? db_one('SELECT * FROM ' . DB_PREFIX . 'article WHERE id = ? AND status = 1', array($id)) : null;
    if (!$art) show_404();

    // 阅读量 +1（同步到 $art 供模板显示最新值；可视化预览不计数）
    if (!preview_active()) {
        db_exec('UPDATE ' . DB_PREFIX . 'article SET views = views + 1 WHERE id = ?', array($id));
        $art['views'] = (int)$art['views'] + 1;
    }

    // 所属栏目（面包屑与内容页模板选择用）
    $col = db_one('SELECT id, name, content_tpl FROM ' . DB_PREFIX . 'column WHERE id = ?', array((int)$art['col_id']));

    // 上一篇 / 下一篇（同栏目 id 相邻）
    $prev = db_one('SELECT id, title FROM ' . DB_PREFIX . 'article
                    WHERE col_id = ? AND status = 1 AND id < ? ORDER BY id DESC LIMIT 1',
                    array((int)$art['col_id'], $id));
    $next = db_one('SELECT id, title FROM ' . DB_PREFIX . 'article
                    WHERE col_id = ? AND status = 1 AND id > ? ORDER BY id ASC LIMIT 1',
                    array((int)$art['col_id'], $id));

    // 文章 SEO，为空回退文章标题
    page_head(
        $art['seo_title'] !== '' ? $art['seo_title'] : $art['title'],
        $art['seo_keywords'],
        $art['seo_description'] !== '' ? $art['seo_description'] : $art['title']
    );
    render_header('col-' . column_top_id((int)$art['col_id']));
    $pv = preview_config();
    render_tpl('art', isset($pv['content_tpl']) ? (int)$pv['content_tpl'] : ($col ? (int)$col['content_tpl'] : 1), array(
        'art'  => $art,
        'col'  => $col,
        'prev' => $prev,
        'next' => $next,
    ));
    render_footer();
    page_foot();
}

/* ---------------- 单页 ?page={flag} ---------------- */

function route_page() {
    $flag = isset($_GET['page']) ? trim((string)$_GET['page']) : '';
    $page = $flag !== '' ? db_one('SELECT * FROM ' . DB_PREFIX . 'page WHERE flag = ? AND status = 1', array($flag)) : null;
    if (!$page) show_404();

    // 单页 SEO，为空回退单页名称
    page_head(
        $page['seo_title'] !== '' ? $page['seo_title'] : $page['name'],
        $page['seo_keywords'],
        $page['seo_description'] !== '' ? $page['seo_description'] : $page['name']
    );
    render_header('page-' . $page['flag']);
    $pv = preview_config();
    render_tpl('page', isset($pv['page_tpl']) ? (int)$pv['page_tpl'] : (int)$page['page_tpl'], array('page' => $page));
    render_footer();
    page_foot();
}

/* ---------------- 路由分发 ---------------- */

if (isset($_GET['art'])) {
    route_article();
} elseif (isset($_GET['col']) || !empty($_GET['col_flag'])) {
    route_column();
} elseif (isset($_GET['page'])) {
    route_page();
} else {
    route_home();
}
