<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


session_start();

define('ROOT_PATH', dirname(__FILE__) . '/../');
define('CORE_PATH', ROOT_PATH . 'core/');
define('PUBLIC_PATH', ROOT_PATH . 'public/');

require_once CORE_PATH . 'db/db.php';
$db = \Core\Db\DB::getInstance();

require_once CORE_PATH . 'lib/common.php';

trackPageView();

$configs = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')}");
$siteConfig = [];
foreach ($configs as $cfg) {
    $siteConfig[$cfg['config_key']] = $cfg['config_value'];
}

$site_status = isset($siteConfig['site_status']) ? $siteConfig['site_status'] : '';
if ($site_status === 'close') {
    // 只有在后台访问时才认为是管理员（前台访问即使有admin_id session也不算）
    $isAdminRequest = (strpos($_SERVER['REQUEST_URI'], '/admin/') === 0 || strpos($_SERVER['REQUEST_URI'], '/admin') === 0);
    $isAdminLogin = $isAdminRequest && isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0;
    if (!$isAdminLogin) {
        echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Website Maintenance</title>';
        echo '<style>body{font-family:Arial;text-align:center;padding:100px 20px;background:#667eea;min-height:100vh;display:flex;align-items:center;justify-content:center;}';
        echo '.container{background:rgba(255,255,255,0.95);padding:60px;border-radius:24px;max-width:500px;box-shadow:0 25px 50px rgba(0,0,0,0.3);}';
        echo 'h2{color:#1e293b;margin-bottom:20px;font-size:24px;}';
        echo 'p{color:#64748b;line-height:1.8;font-size:16px;}';
        echo '.admin-link{display:inline-block;margin-top:30px;padding:14px 28px;background:linear-gradient(135deg,#667eea,#764ba2);';
        echo 'color:#fff;text-decoration:none;border-radius:12px;font-weight:600;transition:all 0.3s;}';
        echo '.admin-link:hover{transform:translateY(-2px);box-shadow:0 8px 25px rgba(102,126,234,0.4);}';
        echo '</style></head><body>';
        echo '<div class="container">';
        echo '<h2>Maintenance</h2>';
        echo '<p>' . nl2br(htmlspecialchars($siteConfig['site_close_msg'] ?? 'Site is under maintenance, please come back later...')) . '</p>';
        echo '<a href="/admin/login.php" class="admin-link">Admin Login</a>';
        echo '</div></body></html>';
        exit;
    }
}

$urlMode = $siteConfig['url_mode'] ?? 'dynamic';

if ($urlMode === 'dynamic') {
    $module = isset($_GET['m']) ? trim($_GET['m']) : 'index';
    $action = isset($_GET['a']) ? trim($_GET['a']) : 'index';
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    
    $module = preg_replace('/[^a-z0-9_]/i', '', $module);
    $action = preg_replace('/[^a-z0-9_]/i', '', $action);
} else {
    $path = isset($_SERVER['REQUEST_URI']) ? parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) : '/';
    $path = trim($path, '/');
    
    if (strpos($path, 'public/') === 0) {
        $path = substr($path, 7);
    }
    
    $routes = [];
    if (!empty($path)) {
        $routes = explode('/', $path);
        foreach ($routes as $k => $v) {
            $routes[$k] = preg_replace('/[^a-z0-9_\-\.]/i', '', $v);
        }
    }
    
    $module = $routes[0] ?? '';
    $action = $routes[1] ?? '';
    $id = isset($routes[1]) && is_numeric($routes[1]) ? intval($routes[1]) : 0;
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
}

require_once CORE_PATH . 'lib/common.php';

require_once CORE_PATH . 'lib/license.php';
require_once CORE_PATH . 'lib/template_loader.php';
$license = new \Core\Lib\License();
$licenseStatus = $license->getStatus();
$canRemoveCopyright = $license->canRemoveCopyright();
$templateLoader = new \Core\Lib\TemplateLoader($license);
$activeTemplateKey = $templateLoader->resolveUsableTemplate($siteConfig['site_template'] ?? 'default', $db);

$site = $siteConfig;
$site['template_dir'] = '/template/' . $activeTemplateKey . '/';
$site['template_path'] = ROOT_PATH . 'template/' . $activeTemplateKey . '/';
$site['public_dir'] = '/public/';
$site['url_mode'] = $urlMode;

function getChannelRedirectUrl($channel) {
    if (!is_array($channel)) {
        return '';
    }
    $redirectUrl = isset($channel['redirect_url']) ? trim($channel['redirect_url']) : '';
    return $redirectUrl;
}

function getChannelUrlById($id, $dir = '') {
    global $db, $urlMode;
    $id = intval($id);
    if ($id > 0) {
        $channel = $db->fetch("SELECT id, channel_dir, redirect_url FROM {$db->table('channel')} WHERE id = ?", [$id]);
        $redirectUrl = getChannelRedirectUrl($channel);
        if ($redirectUrl !== '') {
            return $redirectUrl;
        }
        if (empty($dir) && $channel && isset($channel['channel_dir'])) {
            $dir = $channel['channel_dir'];
        }
    }

    if ($urlMode === 'dynamic') {
        return '/public/index.php?m=channel&id=' . $id;
    }

    return $dir ? '/' . trim($dir, '/') . '/' : '/channel/' . $id . '/';
}

function getUrl($type, $id = 0, $dir = '') {
    global $urlMode, $siteConfig;
    $base = rtrim($siteConfig['site_url'] ?? 'http://' . $_SERVER['HTTP_HOST'], '/');
    
    if ($urlMode === 'dynamic') {
        switch ($type) {
            case 'home': return '/public/index.php?m=index';
            case 'channel': return getChannelUrlById($id, $dir);
            case 'article': return '/public/index.php?m=article&id=' . $id;
            case 'product': return '/public/index.php?m=product&id=' . $id;
            case 'search': return '/public/index.php?m=search';
            case 'guestbook': return '/public/index.php?m=guestbook';
            case 'page': return '/public/index.php?m=page&id=' . $id;
            case 'image': return '/public/index.php?m=image&id=' . $id;
            case 'download': return '/public/index.php?m=download&id=' . $id;
            case 'video': return '/public/index.php?m=video&id=' . $id;
            case 'recruit': return '/public/index.php?m=recruit&id=' . $id;
            default: return '/public/index.php';
        }
    } else {
        switch ($type) {
            case 'home': return '/';
            case 'channel': return getChannelUrlById($id, $dir);
            case 'article': return '/article/' . $id . '.html';
            case 'product': return '/product/' . $id . '.html';
            case 'search': return '/search/';
            case 'guestbook': return '/guestbook/';
            case 'download': return '/download/' . $id . '.html';
            case 'video': return '/video/' . $id . '.html';
            case 'recruit': return '/recruit/' . $id . '.html';
            case 'page': return '/page/' . $id . '.html';
            default: return '/';
        }
    }
}

$channels = $db->fetchAll("SELECT * FROM {$db->table('channel')} WHERE parent_id = 0 AND is_show = 1 ORDER BY list_order ASC, id ASC");
$slides = $db->fetchAll("SELECT * FROM {$db->table('slide')} WHERE status = 1 ORDER BY sort_order ASC, id DESC LIMIT 5");
$topArticles = $db->fetchAll("SELECT a.*, c.channel_name FROM {$db->table('article')} a LEFT JOIN {$db->table('channel')} c ON a.channel_id = c.id WHERE a.status = 1 AND a.flag LIKE '%top%' ORDER BY a.create_time DESC LIMIT 5");
$latestArticles = $db->fetchAll("SELECT a.*, c.channel_name FROM {$db->table('article')} a LEFT JOIN {$db->table('channel')} c ON a.channel_id = c.id WHERE a.status = 1 ORDER BY a.create_time DESC LIMIT 10");
$latestProducts = $db->fetchAll("SELECT * FROM {$db->table('product')} WHERE status = 1 ORDER BY create_time DESC LIMIT 8");
$links = $db->fetchAll("SELECT * FROM {$db->table('link')} WHERE status = 1 ORDER BY sort_order ASC, id DESC");

$templateDir = ROOT_PATH . 'template/' . $activeTemplateKey . '/';

if (empty($module)) {
    $module = 'index';
}

if ($module === 'channel' && $id > 0) {
    $redirectChannel = $db->fetch("SELECT redirect_url FROM {$db->table('channel')} WHERE id = ? AND is_show = 1", [$id]);
    $redirectUrl = getChannelRedirectUrl($redirectChannel);
    if ($redirectUrl !== '') {
        header('Location: ' . $redirectUrl);
        exit;
    }
}

switch ($module) {
    case 'article':
        $tplFile = $id > 0 ? $templateDir . 'article/article.html' : $templateDir . 'article/list.html';
        break;
    case 'product':
        $tplFile = $id > 0 ? $templateDir . 'product/article.html' : $templateDir . 'product/list.html';
        break;
    case 'channel':
        $tplFile = $templateDir . 'channel/list.html';
        break;
    case 'image':
        $tplFile = $id > 0 ? $templateDir . 'image.html' : $templateDir . 'channel/list.html';
        break;
    case 'search':
        $tplFile = $templateDir . 'search.html';
        break;
    case 'guestbook':
        $tplFile = $templateDir . 'guestbook.html';
        break;
    case 'page':
        $tplFile = ($id > 0) ? $templateDir . 'page.html' : $templateDir . 'channel/list.html';
        break;
    case 'download':
        $tplFile = $id > 0 ? $templateDir . 'download.html' : $templateDir . 'channel/list.html';
        break;
    case 'video':
        $tplFile = $id > 0 ? $templateDir . 'video.html' : $templateDir . 'channel/list.html';
        break;
    case 'recruit':
        $tplFile = $id > 0 ? $templateDir . 'recruit.html' : $templateDir . 'channel/list.html';
        break;
    case 'cart':
        $tplFile = $templateDir . 'member/cart.html';
        break;
    default:
        $tplFile = $templateDir . 'index.html';
        break;
}

if (file_exists($tplFile)) {
    include $tplFile;
} else {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Welcome</title>';
    echo '<style>body{font-family:Arial;margin:0;padding:40px;text-align:center;background:#f5f5f5;}';
    echo '.container{max-width:800px;margin:0 auto;background:#fff;padding:60px;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}';
    echo 'h1{color:#0d3b66;}p{color:#666;line-height:1.8;}';
    echo '</style></head><body>';
    echo '<div class="container"><h1>Welcome to 芋头CMS</h1>';
    echo '<p>Your website is successfully installed!</p>';
    echo '<p style="margin-top:30px;"><a href="/admin/" style="color:#00d2d3;text-decoration:none;font-size:18px;">Go to Admin Panel</a></p>';
    echo '</div></body></html>';
}
