<?php
if (!defined('ROOT_PATH')) {
    exit('Access Denied');
}

function tpl_e($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function tpl_table($table)
{
    global $db;
    return $db->table(preg_replace('/[^a-z_]/', '', (string) $table));
}

function tpl_all($sql, array $params = array())
{
    global $db;
    return $db ? $db->fetchAll($sql, $params) : array();
}

function tpl_one($sql, array $params = array())
{
    global $db;
    return $db ? $db->fetch($sql, $params) : null;
}

function tpl_columns($table)
{
    static $cache = array();
    $table = preg_replace('/[^a-z_]/', '', (string) $table);
    if (!isset($cache[$table])) {
        $cache[$table] = array();
        foreach (tpl_all('SHOW COLUMNS FROM ' . tpl_table($table)) as $row) {
            $cache[$table][] = $row['Field'];
        }
    }
    return $cache[$table];
}

function tpl_config($key, $default = '')
{
    global $siteConfig;
    return isset($siteConfig[$key]) ? $siteConfig[$key] : $default;
}

function tpl_site_name()
{
    return trim((string) tpl_config('site_name', '企业官网'));
}

function tpl_phone()
{
    return trim((string) tpl_config('site_phone', '400-888-8888'));
}

function tpl_email()
{
    return trim((string) tpl_config('site_email', 'admin@admin.com'));
}

function tpl_address()
{
    return trim((string) tpl_config('site_address', ''));
}

function tpl_contact_person()
{
    return trim((string) tpl_config('contact_person', '负责人'));
}

function tpl_icp()
{
    return trim((string) tpl_config('site_icp', ''));
}

function tpl_asset($path)
{
    global $site;
    return $site['template_dir'] . 'skin/k620-source/' . ltrim($path, '/');
}

function tpl_reference_image($name)
{
    $folder = strpos($name, '17423') === 0 ? '20250319/' : '20250317/';
    return tpl_asset('static/upload/image/' . $folder . $name);
}

function tpl_normalize_url($url)
{
    $url = trim((string) $url);
    if ($url === '') {
        return '';
    }
    if (preg_match('#^https?://(?:127\.0\.0\.1|localhost)(?::\d+)?(/.*)$#i', $url, $match)) {
        return $match[1];
    }
    return $url;
}

function tpl_logo()
{
    $logo = tpl_normalize_url(tpl_config('site_logo', ''));
    return $logo !== '' ? $logo : tpl_reference_image('1742361772583118.png');
}

function tpl_company_intro_raw()
{
    $intro = trim((string) tpl_config('company_intro', ''));
    return $intro !== '' ? $intro : trim((string) tpl_config('site_description', ''));
}

function tpl_company_intro_html()
{
    $intro = tpl_company_intro_raw();
    if ($intro === '') {
        return '<p>暂无公司介绍。</p>';
    }
    return strip_tags($intro) !== $intro ? $intro : '<p>' . nl2br(tpl_e($intro)) . '</p>';
}

function tpl_text($html, $length = 120)
{
    $text = html_entity_decode(strip_tags((string) $html), ENT_QUOTES, 'UTF-8');
    $text = trim(preg_replace('/\s+/u', ' ', $text));
    if ($length <= 0) {
        return $text;
    }
    return function_exists('mb_substr') ? mb_substr($text, 0, $length, 'UTF-8') : substr($text, 0, $length);
}

function tpl_company_intro_text($length = 240)
{
    return tpl_text(tpl_company_intro_raw(), $length);
}

function tpl_custom_vars()
{
    static $vars = null;
    if ($vars !== null) {
        return $vars;
    }
    $vars = array();
    foreach (tpl_all('SELECT var_key,var_value FROM ' . tpl_table('custom_var') . ' ORDER BY id ASC') as $row) {
        $key = trim((string) $row['var_key']);
        if ($key !== '') {
            $vars[$key] = (string) $row['var_value'];
        }
    }
    return $vars;
}

function tpl_qr_code()
{
    $custom = tpl_custom_vars();
    $qr = isset($custom['title']) ? tpl_normalize_url($custom['title']) : '';
    return $qr !== '' ? $qr : tpl_reference_image('1742372982907936.png');
}

function tpl_channels($parentId = 0, $limit = 0)
{
    $sql = 'SELECT * FROM ' . tpl_table('channel') . ' WHERE parent_id = ? AND status = 1 AND is_show = 1 ORDER BY list_order ASC,id ASC';
    if ($limit > 0) {
        $sql .= ' LIMIT ' . intval($limit);
    }
    return tpl_all($sql, array(intval($parentId)));
}

function tpl_channel($id)
{
    return tpl_one('SELECT * FROM ' . tpl_table('channel') . ' WHERE id = ? AND status = 1 LIMIT 1', array(intval($id)));
}

function tpl_root_channel($type)
{
    return tpl_one('SELECT * FROM ' . tpl_table('channel') . ' WHERE parent_id = 0 AND channel_type = ? AND status = 1 AND is_show = 1 ORDER BY list_order ASC,id ASC LIMIT 1', array(intval($type)));
}

function tpl_root_for_channel($channel)
{
    while ($channel && intval($channel['parent_id']) > 0) {
        $parent = tpl_channel($channel['parent_id']);
        if (!$parent) {
            break;
        }
        $channel = $parent;
    }
    return $channel;
}

function tpl_descendant_ids($channelId)
{
    $channelId = intval($channelId);
    if ($channelId <= 0) {
        return array();
    }
    $ids = array($channelId);
    foreach (tpl_channels($channelId) as $child) {
        $ids = array_merge($ids, tpl_descendant_ids($child['id']));
    }
    return array_values(array_unique($ids));
}

function tpl_content_route($type)
{
    $map = array(1 => 'article', 2 => 'product', 3 => 'page', 4 => 'image', 5 => 'download', 7 => 'video', 9 => 'recruit');
    return isset($map[intval($type)]) ? $map[intval($type)] : 'article';
}

function tpl_channel_title($type)
{
    $map = array(1 => '新闻资讯', 2 => '产品中心', 3 => '关于我们', 4 => '案例展示', 5 => '下载中心', 7 => '视频中心', 9 => '招聘信息');
    return isset($map[intval($type)]) ? $map[intval($type)] : '内容中心';
}

function tpl_english_title($route)
{
    $map = array('article' => 'NEWS', 'product' => 'PRODUCTS', 'page' => 'ABOUT US', 'image' => 'CASES', 'download' => 'DOWNLOAD', 'video' => 'VIDEOS', 'recruit' => 'CAREERS', 'search' => 'SEARCH', 'guestbook' => 'MESSAGE', 'contact' => 'CONTACT US');
    return isset($map[$route]) ? $map[$route] : 'INFORMATION';
}

function tpl_first_page()
{
    return tpl_one('SELECT * FROM ' . tpl_table('page') . ' WHERE status = 1 ORDER BY sort_order ASC,id ASC LIMIT 1');
}

function tpl_page_link($view = 'about')
{
    $page = tpl_first_page();
    $url = $page ? getUrl('page', intval($page['id'])) : getUrl('home');
    return $url . (strpos($url, '?') === false ? '?' : '&') . 'view=' . rawurlencode($view);
}

function tpl_nav_items()
{
    $product = tpl_root_channel(2);
    $news = tpl_root_channel(1);
    $newsChildren = $news ? tpl_channels($news['id']) : array();
    $technical = isset($newsChildren[1]) ? $newsChildren[1] : (isset($newsChildren[0]) ? $newsChildren[0] : null);
    return array(
        array('key' => 'home', 'name' => '首页', 'url' => getUrl('home')),
        array('key' => 'about', 'name' => '关于我们', 'url' => tpl_page_link('about')),
        array('key' => 'product', 'name' => '产品中心', 'url' => $product ? getUrl('channel', $product['id'], $product['channel_dir']) : getUrl('product')),
        array('key' => 'news', 'name' => '新闻资讯', 'url' => $news ? getUrl('channel', $news['id'], $news['channel_dir']) : getUrl('article')),
        array('key' => 'technical', 'name' => '技术文章', 'url' => $technical ? getUrl('channel', $technical['id'], $technical['channel_dir']) : ($news ? getUrl('channel', $news['id'], $news['channel_dir']) : getUrl('article'))),
        array('key' => 'guestbook', 'name' => '在线留言', 'url' => getUrl('guestbook')),
        array('key' => 'contact', 'name' => '联系我们', 'url' => tpl_page_link('contact')),
    );
}

function tpl_item_url($route, array $item)
{
    $redirect = isset($item['redirect_url']) ? trim((string) $item['redirect_url']) : '';
    return $redirect !== '' ? $redirect : getUrl($route, intval($item['id']));
}

function tpl_img($row = null, $fallback = '')
{
    $row = is_array($row) ? $row : array();
    foreach (array('litpic', 'video_cover', 'thumb', 'image', 'pic') as $field) {
        if (empty($row[$field])) {
            continue;
        }
        $value = trim((string) $row[$field]);
        $decoded = json_decode($value, true);
        if (is_array($decoded) && !empty($decoded)) {
            $first = reset($decoded);
            $value = is_array($first) ? (isset($first['url']) ? $first['url'] : '') : $first;
        }
        if (strpos($value, ',') !== false) {
            $value = trim(explode(',', $value)[0]);
        }
        $value = tpl_normalize_url($value);
        if ($value !== '') {
            return $value;
        }
    }
    return $fallback !== '' ? $fallback : tpl_reference_image('1742211847875717.jpg');
}

function tpl_product_pictures($item)
{
    $pictures = array(tpl_img($item));
    $raw = isset($item['pictures']) ? trim((string) $item['pictures']) : '';
    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        foreach ($decoded as $picture) {
            $url = is_array($picture) ? (isset($picture['url']) ? $picture['url'] : '') : $picture;
            $url = tpl_normalize_url($url);
            if ($url !== '') {
                $pictures[] = $url;
            }
        }
    } elseif ($raw !== '') {
        foreach (preg_split('/[,\r\n]+/', $raw) as $url) {
            $url = tpl_normalize_url($url);
            if ($url !== '') {
                $pictures[] = $url;
            }
        }
    }
    return array_slice(array_values(array_unique($pictures)), 0, 5);
}

function tpl_query_items($table, $channelId = 0, $pageSize = 12, $page = null, $keyword = '')
{
    $table = preg_replace('/[^a-z_]/', '', (string) $table);
    $columns = tpl_columns($table);
    $page = $page === null ? max(1, intval(isset($_GET['page']) ? $_GET['page'] : 1)) : max(1, intval($page));
    $where = array('status = 1');
    $params = array();
    if (in_array('deleted_at', $columns, true)) {
        $where[] = 'deleted_at = 0';
    }
    if ($channelId > 0 && in_array('channel_id', $columns, true)) {
        $ids = tpl_descendant_ids($channelId);
        $where[] = 'channel_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
        $params = array_merge($params, $ids);
    }
    $keyword = trim((string) $keyword);
    if ($keyword !== '') {
        $searchFields = array_values(array_intersect(array('title', 'summary', 'content'), $columns));
        if ($searchFields) {
            $likes = array();
            foreach ($searchFields as $field) {
                $likes[] = $field . ' LIKE ?';
                $params[] = '%' . $keyword . '%';
            }
            $where[] = '(' . implode(' OR ', $likes) . ')';
        }
    }
    $whereSql = implode(' AND ', $where);
    $count = tpl_one('SELECT COUNT(*) AS total FROM ' . tpl_table($table) . ' WHERE ' . $whereSql, $params);
    $total = intval(isset($count['total']) ? $count['total'] : 0);
    $pageSize = max(1, intval($pageSize));
    $pages = max(1, intval(ceil($total / $pageSize)));
    $page = min($page, $pages);
    $order = in_array('sort_order', $columns, true) ? 'sort_order ASC,id DESC' : 'id DESC';
    $items = tpl_all('SELECT * FROM ' . tpl_table($table) . ' WHERE ' . $whereSql . ' ORDER BY ' . $order . ' LIMIT ' . (($page - 1) * $pageSize) . ',' . $pageSize, $params);
    return array('items' => $items, 'total' => $total, 'page' => $page, 'pages' => $pages, 'page_size' => $pageSize);
}

function tpl_latest($table, $channelId = 0, $limit = 6)
{
    $result = tpl_query_items($table, intval($channelId), intval($limit), 1);
    return $result['items'];
}

function tpl_detail($table, $id)
{
    $table = preg_replace('/[^a-z_]/', '', (string) $table);
    return tpl_one('SELECT * FROM ' . tpl_table($table) . ' WHERE id = ? AND status = 1 LIMIT 1', array(intval($id)));
}

function tpl_row_time($row)
{
    foreach (array('published_at', 'release_time', 'create_time', 'update_time') as $field) {
        if (!empty($row[$field])) {
            return intval($row[$field]);
        }
    }
    return time();
}

function tpl_prev_next($table, $item)
{
    $channelId = intval(isset($item['channel_id']) ? $item['channel_id'] : 0);
    $id = intval(isset($item['id']) ? $item['id'] : 0);
    $base = ' FROM ' . tpl_table($table) . ' WHERE status = 1 AND channel_id = ? AND id ';
    return array(
        'prev' => tpl_one('SELECT *' . $base . '< ? ORDER BY id DESC LIMIT 1', array($channelId, $id)),
        'next' => tpl_one('SELECT *' . $base . '> ? ORDER BY id ASC LIMIT 1', array($channelId, $id)),
    );
}

function tpl_slides($limit = 5)
{
    return tpl_all('SELECT * FROM ' . tpl_table('slide') . ' WHERE status = 1 AND is_show = 1 ORDER BY sort_order ASC,id DESC LIMIT ' . intval($limit));
}

function tpl_links($limit = 20)
{
    return tpl_all('SELECT * FROM ' . tpl_table('link') . ' WHERE status = 1 AND is_show = 1 ORDER BY sort_order ASC,id DESC LIMIT ' . intval($limit));
}

function tpl_pagination($result, $baseUrl)
{
    $page = intval($result['page']);
    $pages = max(1, intval($result['pages']));
    $join = strpos($baseUrl, '?') === false ? '?' : '&';
    $url = function ($number) use ($baseUrl, $join) {
        return $number <= 1 ? $baseUrl : $baseUrl . $join . 'page=' . intval($number);
    };
    ob_start();
    ?>
    <div class="pagebar"><div class="pagination">
        <a class="page-item page-link hidden-sm" href="<?php echo tpl_e($url(1)); ?>">首页</a>
        <a class="page-item page-link st" href="<?php echo tpl_e($url(max(1, $page - 1))); ?>">&lt;&lt;</a>
        <?php for ($i = max(1, $page - 2); $i <= min($pages, $page + 2); $i++): ?>
            <a href="<?php echo tpl_e($url($i)); ?>" class="page-num<?php echo $i === $page ? ' page-num-current' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
        <a class="page-item page-link" href="javascript:;"><?php echo $page; ?>/<?php echo $pages; ?></a>
        <a class="page-item page-link st" href="<?php echo tpl_e($url(min($pages, $page + 1))); ?>">&gt;&gt;</a>
        <a class="page-item page-link hidden-sm" href="<?php echo tpl_e($url($pages)); ?>">尾页</a>
    </div></div>
    <?php
    return ob_get_clean();
}

function tpl_inner_banner($title, $route = 'article')
{
    ?>
    <div class="NyBanner">
        <img src="<?php echo tpl_e(tpl_reference_image('1742194243117997.jpg')); ?>" class="nyBa_Img" alt="<?php echo tpl_e($title); ?>">
        <div class="NyBa_Con"><span><?php echo tpl_e(tpl_english_title($route)); ?></span><p><?php echo tpl_e($title); ?></p><i></i>
            <div class="Crumb"><img src="<?php echo tpl_e(tpl_asset('skin/images/ny_home.png')); ?>" class="home" alt="">当前位置：<a href="<?php echo tpl_e(getUrl('home')); ?>">首页</a> &gt;&gt; <?php echo tpl_e($title); ?></div>
        </div>
    </div>
    </div>
    <?php
}

function tpl_handle_guestbook()
{
    global $db;
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['k620_guestbook'])) {
        return '';
    }
    $name = trim((string) (isset($_POST['name']) ? $_POST['name'] : ''));
    $phone = trim((string) (isset($_POST['phone']) ? $_POST['phone'] : ''));
    $email = trim((string) (isset($_POST['email']) ? $_POST['email'] : ''));
    $address = trim((string) (isset($_POST['address']) ? $_POST['address'] : ''));
    $content = trim((string) (isset($_POST['content']) ? $_POST['content'] : ''));
    if ($name === '' || $phone === '' || $content === '') {
        return '请填写姓名、联系电话和留言内容。';
    }
    if (function_exists('mb_strlen') && mb_strlen($content, 'UTF-8') > 2000) {
        return '留言内容不能超过 2000 字。';
    }
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    $recent = tpl_one('SELECT id FROM ' . tpl_table('guestbook') . ' WHERE ip = ? AND create_time > ? LIMIT 1', array($ip, time() - 15));
    if ($recent) {
        return '提交过于频繁，请稍后再试。';
    }
    $storedContent = ($address !== '' ? '详细地址：' . $address . "\n" : '') . $content;
    $db->insert('guestbook', array(
        'channel_id' => 0,
        'title' => '网站留言',
        'content' => $storedContent,
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
        'ip' => $ip,
        'status' => 0,
        'is_show' => 0,
        'sort_order' => 100,
        'create_time' => time(),
    ));
    $returnUrl = isset($_POST['return_url']) ? trim((string) $_POST['return_url']) : '';
    if ($returnUrl === '' || strpos($returnUrl, '/') !== 0 || strpos($returnUrl, '//') === 0) {
        $returnUrl = getUrl('guestbook');
    }
    header('Location: ' . $returnUrl . (strpos($returnUrl, '?') === false ? '?' : '&') . 'sent=1#cpzx');
    exit;
}

function tpl_product_sidebar($channel = null)
{
    $root = $channel ? tpl_root_for_channel($channel) : tpl_root_channel(2);
    $categories = $root ? tpl_channels($root['id']) : array();
    $newsRoot = tpl_root_channel(1);
    $articles = $newsRoot ? tpl_latest('article', $newsRoot['id'], 5) : array();
    ?>
    <div class="h_left"><div class="cp_type">
        <div class="hd"><p><img src="<?php echo tpl_e(tpl_asset('skin/images/proico1.png')); ?>" alt="">产品分类</p><span>PRODUCT CLASSIFICATION</span><em></em><i></i></div>
        <div class="bd"><ul>
            <?php foreach ($categories as $category): $children = tpl_channels($category['id']); ?>
            <li><p><a href="<?php echo tpl_e(getUrl('channel', $category['id'], $category['channel_dir'])); ?>"><?php echo tpl_e($category['channel_name']); ?></a><span></span></p><?php if ($children): ?><div><?php foreach ($children as $child): ?><a href="<?php echo tpl_e(getUrl('channel', $child['id'], $child['channel_dir'])); ?>"><?php echo tpl_e($child['channel_name']); ?></a><?php endforeach; ?></div><?php endif; ?></li>
            <?php endforeach; ?>
        </ul></div>
    </div></div>
    <div class="NyXgwz"><div class="NyXgwz_Title"><p><img src="<?php echo tpl_e(tpl_asset('skin/images/artico.png')); ?>" alt="">技术文章</p><span>TECHNICAL ARTICLES</span><em></em></div>
        <div class="NyXgwz_List"><dl><?php foreach ($articles as $article): ?><dd><a href="<?php echo tpl_e(tpl_item_url('article', $article)); ?>"><i></i><?php echo tpl_e($article['title']); ?></a></dd><?php endforeach; ?></dl></div>
    </div>
    <?php
}
