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

if (!defined('ROOT_PATH')) define('ROOT_PATH', dirname(__DIR__) . '/');
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'];
}

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

if ($urlMode === 'dynamic') {
    $module = isset($_GET['m']) ? trim($_GET['m']) : 'index';
    $action = isset($_GET['a']) ? trim($_GET['a']) : 'index';
} 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] ?? '';
}

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;

if (!function_exists('getUrl')) {
    function getUrl($type, $id = 0, $dir = '') {
        switch ($type) {
            case 'home':
                return '/';
            case 'guestbook':
                return '/public/guestbook.php';
            case 'channel':
                return '/public/index.php?m=channel&id=' . intval($id);
            case 'article':
                return '/public/index.php?m=article&id=' . intval($id);
            case 'product':
                return '/public/index.php?m=product&id=' . intval($id);
            default:
                return '/';
        }
    }
}

// 兼容模板普通 POST 提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['ajax'])) {
    $_GET['ajax'] = 'guestbook';
}

// AJAX API
if (isset($_GET['ajax']) && $_GET['ajax'] === 'guestbook') {
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name'] ?? '');
        $contact = trim($_POST['contact'] ?? '');
        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');
        if (empty($name) || empty($content)) {
            echo json_encode(['code' => 400, 'msg' => '姓名和留言内容不能为空']);
            exit;
        }
        if (mb_strlen($content) > 2000) {
            echo json_encode(['code' => 400, 'msg' => '留言内容不能超过2000字']);
            exit;
        }
        // 检查同一IP 1分钟内不能重复提交
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $lastSubmit = $db->fetch("SELECT id FROM {$db->table('guestbook')} WHERE ip=? AND create_time>?", [$ip, time() - 60]);
        if ($lastSubmit) {
            echo json_encode(['code' => 429, 'msg' => '提交太频繁，请稍后再试']);
            exit;
        }
        $channel = $db->fetch("SELECT id FROM {$db->table('channel')} WHERE channel_type=8 AND is_show=1 LIMIT 1");
        $channelId = $channel ? $channel['id'] : 0;
        $db->insert('guestbook', [
            'channel_id' => $channelId,
            'title' => $title,
            'content' => $content,
            'name' => $name,
            'phone' => $contact,
            'ip' => $ip,
            'create_time' => time(),
            'status' => 0,
            'is_show' => 0,
        ]);
        require_once CORE_PATH . 'lib/common.php';
        sendAdminMessage('新留言：' . ($title ?: '无标题'), "姓名：{$name}\n联系方式：{$contact}\n内容：{$content}", $name);
        echo json_encode(['code' => 200, 'msg' => '留言成功，感谢您的参与！']);
        exit;
    }
    // GET 获取列表
    $page = max(1, intval($_GET['page'] ?? 1));
    $pageSize = 10;
    $offset = ($page - 1) * $pageSize;
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('guestbook')} WHERE is_show=1")['cnt'];
    $list = $db->fetchAll("SELECT * FROM {$db->table('guestbook')} WHERE is_show=1 ORDER BY id DESC LIMIT {$offset}, {$pageSize}");
    echo json_encode([
        'code' => 200,
        'total' => $total,
        'page' => $page,
        'pageSize' => $pageSize,
        'data' => array_values(array_map(function($item) {
            return [
                'id' => $item['id'],
                'name' => $item['name'],
                'title' => $item['title'],
                'content' => $item['content'],
                'reply' => $item['reply'],
                'create_time' => $item['create_time'],
                'reply_time' => $item['reply_time'],
            ];
        }, $list))
    ]);
    exit;
}

// 渲染模板
$tplFile = $site['template_path'] . 'guestbook.html';
if (!file_exists($tplFile)) {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>在线留言</title>';
    echo '<style>body{font-family:sans-serif;max-width:600px;margin:60px auto;padding:20px;background:#f8fafc;}';
    echo '.form-group{margin-bottom:16px;}label{display:block;font-size:14px;font-weight:600;margin-bottom:6px;color:#374151;}';
    echo 'input,textarea{width:100%;padding:10px 12px;border:1px solid #d1d5db;border-radius:8px;font-size:14px;box-sizing:border-box;}';
    echo 'textarea{height:120px;resize:vertical;}';
    echo '.btn{background:#3b82f6;color:#fff;border:none;padding:10px 24px;border-radius:8px;font-size:14px;cursor:pointer;width:100%;}';
    echo '.msg{padding:12px 16px;border-radius:8px;margin-bottom:16px;font-size:14px;}.msg.success{background:#dcfce7;color:#16a34a;}.msg.error{background:#fef2f2;color:#dc2626;}</style></head>';
    echo '<body><h2 style="font-size:20px;margin-bottom:24px;">在线留言</h2>';
    echo '<div id="msgBox"></div>';
    echo '<form id="guestbookForm">';
    echo '<div class="form-group"><label>姓名 <span style="color:#f00">*</span></label><input type="text" name="name" id="name" required placeholder="请输入您的姓名" /></div>';
    echo '<div class="form-group"><label>联系方式</label><input type="text" name="contact" id="contact" placeholder="手机号或邮箱" /></div>';
    echo '<div class="form-group"><label>标题</label><input type="text" name="title" id="title" placeholder="简短描述您的问题" /></div>';
    echo '<div class="form-group"><label>留言内容 <span style="color:#f00">*</span></label><textarea name="content" id="content" required placeholder="请输入留言内容..."></textarea></div>';
    echo '<button type="submit" class="btn" id="submitBtn">提交留言</button>';
    echo '</form>';
    echo '<div id="guestbookList" style="margin-top:40px;"></div>';
    echo '<script>';
    echo 'var form=document.getElementById("guestbookForm"),msgBox=document.getElementById("msgBox"),submitBtn=document.getElementById("submitBtn");';
    echo 'form.addEventListener("submit",function(e){e.preventDefault();';
    echo 'submitBtn.disabled=true;submitBtn.textContent="提交中...";';
    echo 'var fd=new FormData(form);';
    echo 'fetch("?m=guestbook&ajax=1",{method:"POST",body:fd}).then(function(r){return r.json();}).then(function(d){';
    echo 'msgBox.innerHTML="<div class=\"msg "+(d.code===200?"success":"error")+"\">"+d.msg+"</div>";';
    echo 'if(d.code===200){form.reset();loadList(1);}';
    echo 'submitBtn.disabled=false;submitBtn.textContent="提交留言";';
    echo '}).catch(function(){msgBox.innerHTML="<div class=\"msg error\">提交失败，请稍后重试</div>";submitBtn.disabled=false;submitBtn.textContent="提交留言";});';
    echo '});';
    echo 'function loadList(page){fetch("?m=guestbook&ajax=1&page="+page).then(function(r){return r.json();}).then(function(d){';
    echo 'var l=document.getElementById("guestbookList"),html="";';
    echo 'if(d.data&&d.data.length>0){d.data.forEach(function(item){';
    echo 'html+="<div style=\"background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:16px;margin-bottom:12px;\">";';
    echo 'html+="<div style=\"display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;\">";';
    echo 'html+="<span style=\"font-weight:600;color:#374151;\">"+item.name+"</span>";';
    echo 'html+="<span style=\"font-size:12px;color:#9ca3af;\">"+new Date(item.create_time*1000).toLocaleString()+"</span></div>";';
    echo 'if(item.title)html+="<div style=\"font-size:13px;color:#6b7280;margin-bottom:6px;\">"+item.title+"</div>";';
    echo 'html+="<div style=\"font-size:14px;color:#374151;line-height:1.7;\">"+item.content.replace(/\\n/g,"<br>")+"</div>";';
    echo 'if(item.reply)html+="<div style=\"margin-top:10px;padding:10px;background:#f0fdf4;border-radius:6px;font-size:13px;\">";';
    echo 'html+="<span style=\"color:#16a34a;font-weight:600;\">回复：</span>"+item.reply.replace(/\\n/g,"<br>")+"</div>";';;
    echo 'html+="</div>";});}else{html="<div style=\"text-align:center;padding:30px;color:#9ca3af;\">暂无留言</div>";}';
    echo 'var totalPages=Math.ceil(d.total/d.pageSize),pages="";';
    echo 'for(var i=1;i<=Math.min(totalPages,5);i++)pages+="<a href=\'javascript:loadList("+i+")\' style=\'"+(i==page?"background:#3b82f6;color:#fff;":"color:#3b82f6;")+"display:inline-block;width:32px;height:32px;line-height:32px;text-align:center;border-radius:6px;margin-right:4px;text-decoration:none;\'>"+i+"</a>";';
    echo 'if(totalPages>1)html+="<div style=\"margin-top:16px;\">"+pages+"</div>";';
    echo 'l.innerHTML=html;});}';
    echo 'loadList(1);';
    echo '</script></body></html>';
    exit;
}
include $tplFile;
