<?php
if (!function_exists('tplv')) {
    function tplv($arr, $key, $default = '') {
        return (is_array($arr) && isset($arr[$key]) && $arr[$key] !== null) ? $arr[$key] : $default;
    }
}
if (!function_exists('tpl_excerpt')) {
    function tpl_excerpt($text, $len = 120) {
        $text = trim(strip_tags((string) $text));
        return function_exists('msubstr') ? msubstr($text, 0, $len) : substr($text, 0, $len);
    }
}
if (!function_exists('tpl_format_time')) {
    function tpl_format_time($ts, $fmt = 'Y-m-d') {
        return !empty($ts) ? date($fmt, intval($ts)) : '';
    }
}
if (!function_exists('tpl_json_array')) {
    function tpl_json_array($json) {
        if (empty($json)) return array();
        $data = json_decode($json, true);
        return is_array($data) ? $data : array();
    }
}
if (!function_exists('tpl_url')) {
    function tpl_url($type, $row = array()) {
        $id = intval(tplv($row, 'id', 0));
        switch ($type) {
            case 'article': return getUrl('article', $id);
            case 'product': return getUrl('product', $id);
            case 'page': return getUrl('page', $id);
            case 'image': return getUrl('image', $id);
            case 'download': return getUrl('download', $id);
            case 'video': return getUrl('video', $id);
            case 'recruit': return getUrl('recruit', $id);
            case 'channel': return getUrl('channel', $id, tplv($row, 'channel_dir', ''));
            default: return '/public/index.php';
        }
    }
}

$tplModule = isset($module) ? $module : 'index';
$tplId = isset($id) ? intval($id) : 0;
$tplSiteName = tplv(isset($siteConfig) ? $siteConfig : array(), 'site_name', tplv(isset($site) ? $site : array(), 'site_name', '芋头CMS网站管理系统'));
$tplTemplateDir = tplv(isset($site) ? $site : array(), 'template_dir', '/template/default/');
$tplSiteLogo = tplv(isset($siteConfig) ? $siteConfig : array(), 'site_logo', '');
$tplCustomTitleValue = $tplSiteName;

try {
    $customRow = $db->fetch("SELECT * FROM {$db->table('custom_var')} WHERE var_key = ? LIMIT 1", array('title'));
    if ($customRow) {
        $tplCustomTitleValue = tplv($customRow, 'var_value', $tplSiteName);
    }
} catch (Exception $e) {
    $tplCustomTitleValue = $tplSiteName;
}

$tplCurrent = null;
$tplChannel = null;
$tplList = array();
$tplChildren = array();
$tplPager = '';
$tplSearchKeyword = isset($keyword) ? trim($keyword) : '';
$tplPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$tplPageSize = 12;
$tplOffset = ($tplPage - 1) * $tplPageSize;

if (isset($channels) && is_array($channels)) {
    $tplChildren = $channels;
}

if ($tplModule === 'channel' && $tplId > 0) {
    $tplChannel = $db->fetch("SELECT * FROM {$db->table('channel')} WHERE id = ?", array($tplId));
    if ($tplChannel) {
        $tplChildren = $db->fetchAll("SELECT * FROM {$db->table('channel')} WHERE parent_id = ? AND is_show = 1 ORDER BY list_order ASC, id ASC", array($tplId));
        $typeMap = array(1 => 'article', 2 => 'product', 3 => 'page', 4 => 'image', 5 => 'download', 7 => 'video', 8 => 'guestbook', 9 => 'recruit');
        $contentType = isset($typeMap[$tplChannel['channel_type']]) ? $typeMap[$tplChannel['channel_type']] : 'article';
        if ($contentType === 'page') {
            $tplCurrent = $db->fetch("SELECT * FROM {$db->table('page')} WHERE channel_id = ? ORDER BY id DESC LIMIT 1", array($tplId));
        } elseif ($contentType !== 'guestbook') {
            $totalRow = $db->fetch("SELECT COUNT(*) AS c FROM {$db->table($contentType)} WHERE channel_id = ? AND status = 1", array($tplId));
            $tplList = $db->fetchAll("SELECT * FROM {$db->table($contentType)} WHERE channel_id = ? AND status = 1 ORDER BY sort_order ASC, id DESC LIMIT {$tplOffset}, {$tplPageSize}", array($tplId));
            $tplPager = showPage($tplPage, ceil((intval(tplv($totalRow, 'c', 0)) / $tplPageSize)), tpl_url('channel', $tplChannel));
        }
    }
}

if ($tplModule === 'article') {
    if ($tplId > 0) {
        $tplCurrent = $db->fetch("SELECT a.*, c.channel_name, c.channel_dir FROM {$db->table('article')} a LEFT JOIN {$db->table('channel')} c ON a.channel_id = c.id WHERE a.id = ?", array($tplId));
        if ($tplCurrent) {
            $tplChannel = $db->fetch("SELECT * FROM {$db->table('channel')} WHERE id = ?", array($tplCurrent['channel_id']));
            $tplList = $db->fetchAll("SELECT * FROM {$db->table('article')} WHERE channel_id = ? AND id <> ? AND status = 1 ORDER BY create_time DESC LIMIT 6", array($tplCurrent['channel_id'], $tplId));
        }
    } else {
        $totalRow = $db->fetch("SELECT COUNT(*) AS c FROM {$db->table('article')} WHERE status = 1");
        $tplList = $db->fetchAll("SELECT a.*, c.channel_name, c.channel_dir 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 {$tplOffset}, {$tplPageSize}");
        $tplPager = showPage($tplPage, ceil((intval(tplv($totalRow, 'c', 0)) / $tplPageSize)), '/public/index.php?m=article');
    }
}

if ($tplModule === 'product') {
    if ($tplId > 0) {
        $tplCurrent = $db->fetch("SELECT p.*, c.channel_name, c.channel_dir FROM {$db->table('product')} p LEFT JOIN {$db->table('channel')} c ON p.channel_id = c.id WHERE p.id = ?", array($tplId));
        if ($tplCurrent) {
            $tplChannel = $db->fetch("SELECT * FROM {$db->table('channel')} WHERE id = ?", array($tplCurrent['channel_id']));
            $tplList = $db->fetchAll("SELECT * FROM {$db->table('product')} WHERE channel_id = ? AND id <> ? AND status = 1 ORDER BY create_time DESC LIMIT 6", array($tplCurrent['channel_id'], $tplId));
        }
    } else {
        $totalRow = $db->fetch("SELECT COUNT(*) AS c FROM {$db->table('product')} WHERE status = 1");
        $tplList = $db->fetchAll("SELECT p.*, c.channel_name, c.channel_dir FROM {$db->table('product')} p LEFT JOIN {$db->table('channel')} c ON p.channel_id = c.id WHERE p.status = 1 ORDER BY p.create_time DESC LIMIT {$tplOffset}, {$tplPageSize}");
        $tplPager = showPage($tplPage, ceil((intval(tplv($totalRow, 'c', 0)) / $tplPageSize)), '/public/index.php?m=product');
    }
}

foreach (array('page','image','download','video','recruit') as $singleModule) {
    if ($tplModule === $singleModule && $tplId > 0) {
        $tplCurrent = $db->fetch("SELECT t.*, c.channel_name, c.channel_dir FROM {$db->table($singleModule)} t LEFT JOIN {$db->table('channel')} c ON t.channel_id = c.id WHERE t.id = ?", array($tplId));
        if ($tplCurrent && !empty($tplCurrent['channel_id'])) {
            $tplChannel = $db->fetch("SELECT * FROM {$db->table('channel')} WHERE id = ?", array($tplCurrent['channel_id']));
            if ($singleModule !== 'page') {
                $tplList = $db->fetchAll("SELECT * FROM {$db->table($singleModule)} WHERE channel_id = ? AND id <> ? AND status = 1 ORDER BY id DESC LIMIT 6", array($tplCurrent['channel_id'], $tplId));
            }
        }
    }
}

if (in_array($tplModule, array('image','download','video','recruit'), true) && $tplId < 1) {
    $totalRow = $db->fetch("SELECT COUNT(*) AS c FROM {$db->table($tplModule)} WHERE status = 1");
    $tplList = $db->fetchAll("SELECT t.*, c.channel_name, c.channel_dir FROM {$db->table($tplModule)} t LEFT JOIN {$db->table('channel')} c ON t.channel_id = c.id WHERE t.status = 1 ORDER BY t.id DESC LIMIT {$tplOffset}, {$tplPageSize}");
    $tplPager = showPage($tplPage, ceil((intval(tplv($totalRow, 'c', 0)) / $tplPageSize)), '/public/index.php?m=' . $tplModule);
}

if ($tplModule === 'search' && $tplSearchKeyword !== '') {
    $kw = '%' . $tplSearchKeyword . '%';
    $tplList = $db->fetchAll("SELECT id, title, summary, content, litpic, create_time, 'article' AS content_model FROM {$db->table('article')} WHERE status = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?) ORDER BY create_time DESC LIMIT 30", array($kw, $kw, $kw));
}

$seo_title = '';
$seo_keywords = '';
$seo_description = '';
if ($tplCurrent) {
    $seo_title = tplv($tplCurrent, 'seo_title', tplv($tplCurrent, 'title', tplv($tplCurrent, 'page_title', '')));
    $seo_keywords = tplv($tplCurrent, 'seo_keywords', '');
    $seo_description = tplv($tplCurrent, 'seo_description', tpl_excerpt(tplv($tplCurrent, 'summary', tplv($tplCurrent, 'content', tplv($tplCurrent, 'page_content', ''))), 120));
} elseif ($tplChannel) {
    $seo_title = tplv($tplChannel, 'seo_title', tplv($tplChannel, 'channel_name', ''));
    $seo_keywords = tplv($tplChannel, 'seo_keywords', '');
    $seo_description = tplv($tplChannel, 'seo_description', '');
}
