<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * 2026企业CMS - 前台入口文件
 */

// 引入核心文件
require_once __DIR__ . '/includes/functions.php';

// 授权验证（在所有输出之前）
require_once __DIR__ . '/includes/license_middleware.php';
$licenseStatus = checkLicense();

$p = $_GET['p'] ?? 'home';
$slug = $_GET['slug'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$category = $_GET['category'] ?? '';

// 路由分发
switch ($p) {
    case 'home':
    case '':
        $pageTitle = '';
        $pageContent = load_template('index.php', compact('pageTitle'));
        break;
        
    case 'about':
        $pageData = db_query_one("SELECT * FROM `pages` WHERE `slug` = 'about' AND `status` = 1");
        if (!$pageData) { http_response_code(404); $pageData = ['title'=>'关于我们','content'=>'<p>页面内容待完善</p>']; }
        $pageTitle = $pageData['title'];
        $pageContent = load_template('about.php', ['pageData' => $pageData]);
        break;
        
    case 'contact':
        $pageData = db_query_one("SELECT * FROM `pages` WHERE `slug` = 'contact' AND `status` = 1");
        if (!$pageData) { $pageData = ['title'=>'联系我们','content'=>'']; }
        $pageTitle = $pageData['title'];
        // 处理联系表单提交
        $contactMsg = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['contact_submit'])) {
            $name = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $message = trim($_POST['message'] ?? '');
            if ($name && $phone && $message) {
                db_exec(
                    "INSERT INTO `contacts` (`name`, `phone`, `email`, `message`, `ip`) VALUES (?, ?, ?, ?, ?)",
                    [$name, $phone, $email, $message, $_SERVER['REMOTE_ADDR'] ?? '']
                );
                $contactMsg = '<div class="alert alert-success">感谢您的留言，我们会尽快回复！</div>';
            } else {
                $contactMsg = '<div class="alert alert-danger">请填写完整信息！</div>';
            }
        }
        $pageContent = load_template('contact.php', compact('pageData', 'contactMsg'));
        break;
        
    case 'services':
        $pageData = db_query_one("SELECT * FROM `pages` WHERE `slug` = 'services' AND `status` = 1");
        if (!$pageData) { $pageData = ['title'=>'服务内容','content'=>'']; }
        $pageTitle = $pageData['title'];
        $pageContent = load_template('services.php', ['pageData' => $pageData]);
        break;
        
    case 'news':
        $total = db_count('articles', 'status=1');
        $pageSize = PAGE_SIZE;
        $totalPage = ceil($total / $pageSize);
        $offset = ($page - 1) * $pageSize;
        $articles = db_query("SELECT * FROM `articles` WHERE `status`=1 ORDER BY `is_top` DESC, `published_at` DESC LIMIT {$offset}, {$pageSize}");
        $pageTitle = '新闻资讯';
        $pageContent = load_template('news.php', compact('articles', 'total', 'page', 'totalPage', 'pageSize'));
        break;
        
    case 'article':
        if (!$slug) { header('Location: /news.html'); exit; }
        $article = db_query_one("SELECT a.*, ad.realname as author_name FROM `articles` a LEFT JOIN `admins` ad ON a.author_id=ad.id WHERE a.`slug`=? AND a.`status`=1", [$slug]);
        if (!$article) { http_response_code(404); include __DIR__ . '/404.php'; exit; }
        // 更新浏览量
        db_exec("UPDATE `articles` SET `views`=`views`+1 WHERE `id`=?", [$article['id']]);
        $pageTitle = $article['title'];
        $pageContent = load_template('article.php', ['article' => $article]);
        break;
        
    case 'templates':
        // 模板中心
        $pageTitle = '模板中心';
        $pageContent = load_template('templates.php');
        break;

    case 'products':
        $where = 'status=1';
        $params = [];
        
        // 分类筛选
        if ($category) {
            $where .= ' AND `category_id`=(SELECT `id` FROM `product_categories` WHERE `slug`=?)';
            $params[] = $category;
        }
        
        // 多条件筛选（属性）
        $filter_attributes = db_query("SELECT * FROM `product_attributes` WHERE `status`=1");
        $filtered_product_ids = [];
        $has_filter = false;
        
        foreach ($filter_attributes as $attr) {
            $param_name = 'filter_' . $attr['slug'];
            if (isset($_GET[$param_name])) {
                $has_filter = true;
                $filter_value = $_GET[$param_name];
                
                // 获取符合条件的产品ID
                if (is_array($filter_value)) {
                    // 多选：只要有一个值匹配即可
                    $placeholders = implode(',', array_fill(0, count($filter_value), '?'));
                    $sql = "SELECT DISTINCT `product_id` FROM `product_attribute_values` WHERE `attribute_id`=? AND `value` IN ({$placeholders})";
                    $stmt = $GLOBALS['pdo']->prepare($sql);
                    $stmt->execute(array_merge([$attr['id']], $filter_value));
                } else {
                    // 单选
                    $sql = "SELECT DISTINCT `product_id` FROM `product_attribute_values` WHERE `attribute_id`=? AND `value`=?";
                    $stmt = $GLOBALS['pdo']->prepare($sql);
                    $stmt->execute([$attr['id'], $filter_value]);
                }
                
                $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                if (empty($filtered_product_ids)) {
                    $filtered_product_ids = $ids;
                } else {
                    // 取交集
                    $filtered_product_ids = array_intersect($filtered_product_ids, $ids);
                }
            }
        }
        
        // 价格区间筛选
        $price_min = isset($_GET['price_min']) ? floatval($_GET['price_min']) : 0;
        $price_max = isset($_GET['price_max']) ? floatval($_GET['price_max']) : 0;
        if ($price_min > 0 || $price_max > 0) {
            $has_filter = true;
            $price_sql = "SELECT `id` FROM `products` WHERE `status`=1";
            if ($price_min > 0) {
                $price_sql .= " AND `price` >= {$price_min}";
            }
            if ($price_max > 0) {
                $price_sql .= " AND `price` <= {$price_max}";
            }
            $stmt = $GLOBALS['pdo']->query($price_sql);
            $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            if (empty($filtered_product_ids)) {
                $filtered_product_ids = $ids;
            } else {
                $filtered_product_ids = array_intersect($filtered_product_ids, $ids);
            }
        }
        
        // 如果有筛选条件，则根据筛选出的产品ID查询
        if ($has_filter && !empty($filtered_product_ids)) {
            $placeholders = implode(',', array_fill(0, count($filtered_product_ids), '?'));
            $where .= " AND `id` IN ({$placeholders})";
            $params = array_merge($params, $filtered_product_ids);
        } elseif ($has_filter && empty($filtered_product_ids)) {
            // 有筛选条件但无匹配产品
            $where = '1=0'; // 强制无结果
        }
        
        $total = db_count('products', $where, $params);
        $pageSize = 12;
        $totalPage = ceil($total / $pageSize);
        $offset = ($page - 1) * $pageSize;
        $products = db_query("SELECT * FROM `products` WHERE {$where} ORDER BY `is_hot` DESC, `sort_order` ASC, `id` DESC LIMIT {$offset}, {$pageSize}", $params);
        $pageTitle = '产品中心';
        $pageContent = load_template('products.php', compact('products', 'total', 'page', 'totalPage', 'pageSize', 'category'));
        break;
        
    case 'product':
        if (!$slug) { header('Location: /products.html'); exit; }
        $product = db_query_one("SELECT * FROM `products` WHERE `slug`=? AND `status`=1", [$slug]);
        if (!$product) { http_response_code(404); include __DIR__ . '/404.php'; exit; }
        db_exec("UPDATE `products` SET `views`=`views`+1 WHERE `id`=?", [$product['id']]);
        $pageTitle = $product['title'];
        $pageContent = load_template('product.php', ['product' => $product]);
        break;
        
    case 'cases':
        $cases = db_query("SELECT * FROM `cases` WHERE `status`=1 ORDER BY `sort_order` ASC, `id` DESC LIMIT 20");
        $pageTitle = '成功案例';
        $pageContent = load_template('cases.php', compact('cases'));
        break;
        
    case 'case':
        if (!$slug) { header('Location: /cases.html'); exit; }
        $case = db_query_one("SELECT * FROM `cases` WHERE `slug`=? AND `status`=1", [$slug]);
        if (!$case) { http_response_code(404); include __DIR__ . '/404.php'; exit; }
        db_exec("UPDATE `cases` SET `views`=`views`+1 WHERE `id`=?", [$case['id']]);
        $pageTitle = $case['title'];
        $pageContent = load_template('case.php', ['case' => $case]);
        break;
        
    case 'download':
        // 下载中心
        $versions = db_query("SELECT * FROM `versions` WHERE `is_published`=1 ORDER BY `release_date` DESC, `id` DESC");
        $pageTitle = '下载中心';
        $pageContent = load_template('download.php', compact('versions'));
        break;

    case 'apply':
        // 域名自助授权申请
        $pageTitle = '申请授权';
        $pageContent = load_template('apply.php');
        break;


    case 'download-file':
        // 文件下载处理（不经过主题模板）
        include __DIR__ . '/download.php';
        exit;

    case 'barjucms':
        // CMS产品介绍页
        $pageTitle = 'BarjuCMS - 企业内容管理系统';
        $pageContent = load_template('barjucms.php');
        break;

        
    case 'team':
        $teamMembers = db_query("SELECT * FROM `team` WHERE `status`=1 ORDER BY `sort_order` ASC, `id` ASC");
        $pageTitle = '团队成员';
        $pageContent = load_template('team.php', compact('teamMembers'));
        break;
        
    case 'search':
        $keyword = trim($_GET['q'] ?? '');
        $results = [];
        if ($keyword) {
            $results['articles'] = db_query("SELECT 'article' as type, `id`, `title`, `summary`, `slug` FROM `articles` WHERE `status`=1 AND (`title` LIKE ? OR `content` LIKE ?) LIMIT 10", ["%{$keyword}%", "%{$keyword}%"]);
            $results['products'] = db_query("SELECT 'product' as type, `id`, `title`, `summary`, `slug` FROM `products` WHERE `status`=1 AND (`title` LIKE ? OR `content` LIKE ?) LIMIT 10", ["%{$keyword}%", "%{$keyword}%"]);
        }
        $pageTitle = '搜索结果';
        $pageContent = load_template('search.php', compact('keyword', 'results'));
        break;
        
    case 'category':
        $slug = $_GET['slug'] ?? '';
        if (!$slug) { header('Location: /news.html'); exit; }
        
        // 获取分类信息
        $category = db_query_one("SELECT * FROM `categories` WHERE `slug`=? AND `status`=1", [$slug]);
        if (!$category) { http_response_code(404); include __DIR__ . '/404.php'; exit; }
        
        // 获取该分类及其子分类的ID
        $category_ids = get_category_children($category['id']);
        $placeholders = implode(',', array_fill(0, count($category_ids), '?'));
        
        // 分页
        $where = "`category_id` IN ({$placeholders}) AND `status`=1";
        $total = db_count('articles', $where, $category_ids);
        $pageSize = PAGE_SIZE;
        $totalPage = ceil($total / $pageSize);
        $offset = ($page - 1) * $pageSize;
        
        // 获取文章列表
        $sql = "SELECT * FROM `articles` WHERE {$where} ORDER BY `is_top` DESC, `published_at` DESC LIMIT {$offset}, {$pageSize}";
        $stmt = $GLOBALS['pdo']->prepare($sql);
        $stmt->execute($category_ids);
        $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $pageTitle = $category['name'];
        $pageContent = load_template('category.php', compact('category', 'articles', 'total', 'page', 'totalPage', 'pageSize'));
        break;
        
    case 'page':
        $slug = $_GET['slug'] ?? '';
        $pageData = db_query_one("SELECT * FROM `pages` WHERE `slug`=? AND `status`=1", [$slug]);
        if (!$pageData) { http_response_code(404); include __DIR__ . '/404.php'; exit; }
        $pageTitle = $pageData['title'];
        $pageContent = load_template('page.php', ['pageData' => $pageData]);
        break;
        
    default:
        http_response_code(404);
        include __DIR__ . '/404.php';
        exit;
}

        // 输出最终页面
echo load_template('header.php', ['pageTitle' => $pageTitle ?? '']);
// 解析短代码（支持在页面内容中插入表单等组件）
$pageContent = parse_shortcodes($pageContent ?? '');
echo $pageContent;
echo load_template('footer.php');
