<?php
/**
 * 炎酷CMS - 首页可视化编辑（首页模块管理）
 * 模块类型 mod_type：about=关于我们 / article=文章模块 / product=产品模块
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require dirname(__DIR__) . '/inc/medialib.php';

$page_title = '首页区块';
$active = 'block';
$T = DB_PREFIX . 'index_block';

$modNames = array('about' => '关于我们', 'article' => '文章模块', 'product' => '产品模块', 'link' => '友情链接');
$orderNames = array('new' => '最新', 'hot' => '热门', 'recommend' => '推荐');

// ---------- 写操作 ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $do = isset($_POST['do']) ? $_POST['do'] : '';

    if ($do === 'delete') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $row = db_one("SELECT name FROM $T WHERE id = ?", array($id));
        if ($row) {
            db_exec("DELETE FROM $T WHERE id = ?", array($id));
            admin_log('删除首页模块', 'ID:' . $id . ' 名称:' . $row['name']);
            flash_set('模块已删除');
        }
        header('Location: index.php');
        exit;
    }

    if ($do === 'move') {
        // 上移/下移：与相邻模块交换 sort
        $id  = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $dir = (isset($_POST['dir']) && $_POST['dir'] === 'up') ? 'up' : 'down';
        $cur = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if ($cur) {
            if ($dir === 'up') {
                $sib = db_one("SELECT * FROM $T WHERE (sort < ? OR (sort = ? AND id < ?)) ORDER BY sort DESC, id DESC LIMIT 1",
                    array($cur['sort'], $cur['sort'], $cur['id']));
            } else {
                $sib = db_one("SELECT * FROM $T WHERE (sort > ? OR (sort = ? AND id > ?)) ORDER BY sort ASC, id ASC LIMIT 1",
                    array($cur['sort'], $cur['sort'], $cur['id']));
            }
            if ($sib) {
                if ((int)$cur['sort'] === (int)$sib['sort']) {
                    // sort 相同则错开再交换
                    db_exec("UPDATE $T SET sort = ? WHERE id = ?", array((int)$sib['sort'] + 1, $cur['id']));
                } else {
                    db_exec("UPDATE $T SET sort = ? WHERE id = ?", array($sib['sort'], $cur['id']));
                    db_exec("UPDATE $T SET sort = ? WHERE id = ?", array($cur['sort'], $sib['id']));
                }
            }
            admin_log('模块排序', 'ID:' . $id . ' ' . ($dir === 'up' ? '上移' : '下移'));
        }
        header('Location: index.php');
        exit;
    }

    if ($do === 'toggle') {
        // 显示开关切换
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $row = db_one("SELECT is_show FROM $T WHERE id = ?", array($id));
        if ($row) {
            db_exec("UPDATE $T SET is_show = ? WHERE id = ?", array($row['is_show'] ? 0 : 1, $id));
            admin_log('模块显示开关', 'ID:' . $id . ' ' . ($row['is_show'] ? '隐藏' : '显示'));
        }
        header('Location: index.php');
        exit;
    }

    if ($do === 'save') {
        $id      = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $modType = isset($_POST['mod_type']) ? $_POST['mod_type'] : '';
        if (!isset($modNames[$modType])) $modType = 'article';
        $name = trim(isset($_POST['name']) ? $_POST['name'] : '');
        if ($name === '') {
            flash_set('模块名称不能为空', 'err');
            header('Location: index.php?act=' . ($id ? 'edit&id=' . $id : 'add&mod_type=' . $modType));
            exit;
        }
        $order = isset($_POST['data_order']) ? $_POST['data_order'] : 'new';
        if (!isset($orderNames[$order])) $order = 'new';
        $listNum = (int)(isset($_POST['list_num']) ? $_POST['list_num'] : 0);
        // about=简介字数（默认120）；文章/产品=调用条数（默认6）；友情链接不需要
        $listNum = $modType === 'about' ? max(10, min(2000, $listNum > 0 ? $listNum : 120)) : max(1, min(50, $listNum > 0 ? $listNum : 6));
        // 友情链接：文字+链接行存配置 friend_links（全站仅一份，模块行控制是否显示）
        if ($modType === 'link') {
            $links  = array();
            $lNames = isset($_POST['fl_name']) && is_array($_POST['fl_name']) ? $_POST['fl_name'] : array();
            $lUrls  = isset($_POST['fl_url']) && is_array($_POST['fl_url']) ? $_POST['fl_url'] : array();
            foreach ($lNames as $i => $ln) {
                $ln = trim($ln);
                $lu = isset($lUrls[$i]) ? trim($lUrls[$i]) : '';
                if ($ln === '' || $lu === '') continue;
                if (!preg_match('#^https?://#i', $lu)) $lu = 'http://' . $lu;
                $links[] = array('name' => $ln, 'url' => $lu);
            }
            config_set('friend_links', json_encode($links, JSON_UNESCAPED_UNICODE));
            $listNum = 0;
        }
        $data = array(
            'name'        => $name,
            'mod_type'    => $modType,
            'col_id'      => (int)(isset($_POST['col_id']) ? $_POST['col_id'] : 0),
            'tpl_id'      => 1, // 模板样式由【在线编辑】可视化管理；编辑时下方会回填数据库原值
            'list_num'    => $listNum,
            'intro'       => trim(isset($_POST['intro']) ? $_POST['intro'] : ''),
            'image'       => trim(isset($_POST['image']) ? $_POST['image'] : ''),
            'link_url'    => trim(isset($_POST['link_url']) ? $_POST['link_url'] : ''),
            'title_style' => 1, // 标题样式由【在线编辑】可视化管理；编辑时下方会回填数据库原值
            'title_color' => trim(isset($_POST['title_color']) ? $_POST['title_color'] : ''),
            'data_order'  => $order,
            'show_thumb'  => !empty($_POST['show_thumb']) ? 1 : 0,
            'show_desc'   => !empty($_POST['show_desc']) ? 1 : 0,
            'show_time'   => !empty($_POST['show_time']) ? 1 : 0,
            'sort'        => (int)(isset($_POST['sort']) ? $_POST['sort'] : 0),
            'is_show'     => !empty($_POST['is_show']) ? 1 : 0,
        );
        if ($id > 0) {
            // 模板样式/标题样式不在本表单维护（见左侧菜单【在线编辑】），保留数据库原值
            $keep = db_one("SELECT tpl_id, title_style FROM $T WHERE id = ?", array($id));
            if ($keep) {
                $data['tpl_id'] = max(1, (int)$keep['tpl_id']);
                $data['title_style'] = max(1, (int)$keep['title_style']);
            }
            db_exec("UPDATE $T SET name=?, mod_type=?, col_id=?, tpl_id=?, list_num=?, intro=?, image=?, link_url=?, title_style=?, title_color=?, data_order=?, show_thumb=?, show_desc=?, show_time=?, sort=?, is_show=? WHERE id=?",
                array($data['name'], $data['mod_type'], $data['col_id'], $data['tpl_id'], $data['list_num'], $data['intro'], $data['image'], $data['link_url'], $data['title_style'], $data['title_color'], $data['data_order'], $data['show_thumb'], $data['show_desc'], $data['show_time'], $data['sort'], $data['is_show'], $id));
            admin_log('编辑首页模块', 'ID:' . $id . ' 名称:' . $name);
            flash_set('模块已保存');
        } else {
            $id = db_insert("INSERT INTO $T (name, mod_type, col_id, tpl_id, list_num, intro, image, link_url, title_style, title_color, data_order, show_thumb, show_desc, show_time, sort, is_show) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                array($data['name'], $data['mod_type'], $data['col_id'], $data['tpl_id'], $data['list_num'], $data['intro'], $data['image'], $data['link_url'], $data['title_style'], $data['title_color'], $data['data_order'], $data['show_thumb'], $data['show_desc'], $data['show_time'], $data['sort'], $data['is_show']));
            admin_log('新增首页模块', 'ID:' . $id . ' 名称:' . $name . ' 类型:' . $modNames[$modType]);
            flash_set('模块已新增');
        }
        header('Location: index.php');
        exit;
    }
}

// ---------- 添加模块：第一步选类型 ----------
$act = isset($_GET['act']) ? $_GET['act'] : '';
if ($act === 'add' && empty($_GET['mod_type'])) {
    $page_title = '添加模块';
    require dirname(__DIR__) . '/inc/header.php';
    ?>
<div class="yk-card">
  <h3>选择模块类型</h3>
  <div class="yk-grid">
    <div class="cell" style="width:200px">
      <div style="font-size:15px;font-weight:bold;margin:10px 0">关于我们</div>
      <div class="nm">调用一个单页作为公司简介展示</div>
      <a class="yk-btn sm" href="index.php?act=add&amp;mod_type=about">选择</a>
    </div>
    <div class="cell" style="width:200px">
      <div style="font-size:15px;font-weight:bold;margin:10px 0">文章模块</div>
      <div class="nm">调用某栏目的文章列表（新闻/动态等）</div>
      <a class="yk-btn sm" href="index.php?act=add&amp;mod_type=article">选择</a>
    </div>
    <div class="cell" style="width:200px">
      <div style="font-size:15px;font-weight:bold;margin:10px 0">产品模块</div>
      <div class="nm">调用产品/案例栏目内容，带缩略图展示</div>
      <a class="yk-btn sm" href="index.php?act=add&amp;mod_type=product">选择</a>
    </div>
    <div class="cell" style="width:200px">
      <div style="font-size:15px;font-weight:bold;margin:10px 0">友情链接</div>
      <div class="nm">文字+链接列表，显示在首页底部</div>
      <a class="yk-btn sm" href="index.php?act=add&amp;mod_type=link">选择</a>
    </div>
  </div>
  <div class="tip" style="margin-top:14px">产品模块同时用于案例展示，选择产品/案例栏目即可</div>
  <div style="margin-top:14px"><a class="yk-btn gray" href="index.php">返回列表</a></div>
</div>
    <?php
    require dirname(__DIR__) . '/inc/footer.php';
    exit;
}

// ---------- 新增/编辑表单 ----------
if ($act === 'add' || $act === 'edit') {
    $row = array('id' => 0, 'name' => '', 'mod_type' => 'article', 'col_id' => 0, 'tpl_id' => 1, 'list_num' => 6,
        'intro' => '', 'image' => '', 'link_url' => '', 'title_style' => 1, 'title_color' => '',
        'data_order' => 'new', 'show_thumb' => 1, 'show_desc' => 1, 'show_time' => 1, 'sort' => 0, 'is_show' => 1);
    if ($act === 'edit') {
        $id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
        $row = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if (!$row) { flash_set('模块不存在', 'err'); header('Location: index.php'); exit; }
        $page_title = '编辑模块';
    } else {
        $modType = isset($_GET['mod_type']) ? $_GET['mod_type'] : 'article';
        if (!isset($modNames[$modType])) $modType = 'article';
        $row['mod_type'] = $modType;
        if ($modType === 'about') $row['list_num'] = 120;
        $page_title = '添加模块';
    }
    $modType = $row['mod_type'];
    if (!isset($modNames[$modType])) $modType = 'article';
    $colOptions = column_options();
    $pageOptions = db_all('SELECT id, name FROM ' . DB_PREFIX . 'page ORDER BY sort ASC, id ASC');
    // 友情链接：读取已保存的链接行
    $friendLinks = json_decode(site_config('friend_links', '[]'), true);
    if (!is_array($friendLinks)) $friendLinks = array();
    // 模板样式文字示意（按模块类型区分）
    $tplHintMap = array(
        'about'   => array(1 => '样式1-左图右文', 2 => '样式2-右图左文色块', 3 => '样式3-上图下文卡片', 4 => '样式4-纯文字居中', 5 => '样式5-图片背景浮层'),
        'article' => array(1 => '样式1-左图右文列表', 2 => '样式2-纯文字日期列表', 3 => '样式3-首条大图+列表', 4 => '样式4-两列卡片', 5 => '样式5-横向滚动卡片'),
        'product' => array(1 => '样式1-四列网格图卡', 2 => '样式2-标题遮罩图卡', 3 => '样式3-大小图混排', 4 => '样式4-圆角阴影卡片', 5 => '样式5-左图右简介列表'),
        'link'    => array(1 => '样式1-文字链接行'),
    );
    $tplHints   = isset($tplHintMap[$modType]) ? $tplHintMap[$modType] : $tplHintMap['article'];
    $titleHints = array(1 => '样式1-左侧竖线', 2 => '样式2-底部下划线', 3 => '样式3-居中两侧横线', 4 => '样式4-底色块', 5 => '样式5-菱形前缀');
    require dirname(__DIR__) . '/inc/header.php';
    ?>
<div class="yk-card">
  <h3><?php echo e($page_title); ?>（<?php echo e($modNames[$modType]); ?>）</h3>
  <form class="yk-form" method="post" action="index.php">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="do" value="save">
    <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
    <input type="hidden" name="mod_type" value="<?php echo e($modType); ?>">
    <div class="row"><label>模块名称</label><div class="ipt"><input type="text" name="name" value="<?php echo e($row['name']); ?>" required></div></div>

    <?php if ($modType === 'about'): ?>
    <div class="row"><label>数据来源单页</label><div class="ipt"><select name="col_id">
      <option value="0">请选择单页</option>
      <?php foreach ($pageOptions as $p): ?>
      <option value="<?php echo (int)$p['id']; ?>"<?php echo (int)$row['col_id'] === (int)$p['id'] ? ' selected' : ''; ?>><?php echo e($p['name']); ?></option>
      <?php endforeach; ?>
    </select></div></div>
    <?php yk_image_field('image', $row['image'], '形象图片', '可空，留空则使用单页的形象图片'); ?>
    <div class="row"><label>简介字数</label><div class="ipt"><input type="number" name="list_num" min="10" max="2000" value="<?php echo (int)$row['list_num']; ?>"><div class="tip">自动从单页内容截取的文字数（自动过滤标签代码和图片，保留空行），默认 120</div></div></div>
    <div class="row"><label>查看更多链接</label><div class="ipt"><input type="text" name="link_url" value="<?php echo e($row['link_url']); ?>"><div class="tip">可空，留空则默认链接到该单页</div></div></div>
    <?php elseif ($modType === 'link'): ?>
    <div class="row"><label>链接列表</label><div class="ipt">
      <div id="ykFlRows">
        <?php foreach ($friendLinks as $fl): ?>
        <div class="yk-fl-row" style="display:flex;gap:8px;align-items:center;margin-bottom:8px">
          <input type="text" name="fl_name[]" value="<?php echo e(isset($fl['name']) ? $fl['name'] : ''); ?>" placeholder="链接文字" style="flex:1">
          <input type="text" name="fl_url[]" value="<?php echo e(isset($fl['url']) ? $fl['url'] : ''); ?>" placeholder="https:// 链接地址" style="flex:2">
          <button type="button" class="yk-btn red sm" onclick="this.parentNode.remove()">删除</button>
        </div>
        <?php endforeach; ?>
      </div>
      <button type="button" class="yk-btn gray sm" onclick="ykFlAdd()">+ 添加一行</button>
      <div class="tip">文字+链接，新窗口打开，显示在首页底部友情链接区</div>
    </div></div>
    <?php else: ?>
    <div class="row"><label>数据栏目</label><div class="ipt"><select name="col_id">
      <option value="0">请选择栏目</option>
      <?php foreach ($colOptions as $o): ?>
      <option value="<?php echo (int)$o['id']; ?>"<?php echo (int)$row['col_id'] === (int)$o['id'] ? ' selected' : ''; ?>><?php echo str_repeat('　', $o['depth']) . e($o['name']); ?></option>
      <?php endforeach; ?>
    </select><?php if ($modType === 'product'): ?><div class="tip">产品模块同时用于案例展示，选择产品/案例栏目即可</div><?php endif; ?></div></div>
    <div class="row"><label>调用条数</label><div class="ipt"><input type="number" name="list_num" min="1" max="50" value="<?php echo (int)$row['list_num']; ?>"></div></div>
    <div class="row"><label>排序方式</label><div class="ipt"><select name="data_order">
      <?php foreach ($orderNames as $k => $v): ?>
      <option value="<?php echo e($k); ?>"<?php echo $row['data_order'] === $k ? ' selected' : ''; ?>><?php echo e($v); ?></option>
      <?php endforeach; ?>
    </select></div></div>
    <div class="row"><label>显示项</label><div class="ipt yk-check">
      <label><input type="checkbox" name="show_thumb" value="1"<?php echo $row['show_thumb'] ? ' checked' : ''; ?>> 缩略图</label>
      <label><input type="checkbox" name="show_desc" value="1"<?php echo $row['show_desc'] ? ' checked' : ''; ?>> 简介</label>
      <label><input type="checkbox" name="show_time" value="1"<?php echo $row['show_time'] ? ' checked' : ''; ?>> 时间</label>
    </div></div>
    <?php endif; ?>

    <?php if ($modType !== 'link'): ?>
    <div class="row"><label>模板样式</label><div class="ipt"><div class="tip" style="padding-top:8px">当前：样式<?php echo (int)$row['tpl_id']; ?>（在左侧菜单【在线编辑】→“首页区块”中可视化修改）</div></div></div>
    <div class="row"><label>标题样式</label><div class="ipt"><div class="tip" style="padding-top:8px">当前：样式<?php echo (int)$row['title_style']; ?>（在左侧菜单【在线编辑】→“首页区块”中可视化修改）</div></div></div>
    <div class="row"><label>标题颜色</label><div class="ipt">
      <input type="color" name="title_color" value="<?php echo preg_match('/^#[0-9a-fA-F]{6}$/', $row['title_color']) ? e($row['title_color']) : '#333333'; ?>" style="width:46px;height:34px;padding:2px;border:1px solid #d5dae3;border-radius:4px;cursor:pointer">
      <div class="tip">模块标题文字颜色</div>
    </div></div>
    <?php endif; ?>
    <div class="row"><label>排序</label><div class="ipt"><input type="number" name="sort" value="<?php echo (int)$row['sort']; ?>"><div class="tip">数字越小越靠前</div></div></div>
    <div class="row"><label>是否显示</label><div class="ipt yk-check"><label><input type="checkbox" name="is_show" value="1"<?php echo $row['is_show'] ? ' checked' : ''; ?>> 在首页显示</label></div></div>
    <div class="row"><label></label><div class="ipt">
      <button class="yk-btn" type="submit">保存</button>
      <a class="yk-btn gray" href="index.php">返回列表</a>
    </div></div>
  </form>
</div>
<script>
// 友情链接行编辑器
function ykFlAdd(name, url) {
    name = name || ''; url = url || '';
    var row = document.createElement('div');
    row.className = 'yk-fl-row';
    row.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:8px';
    row.innerHTML = '<input type="text" name="fl_name[]" placeholder="链接文字" style="flex:1">'
        + '<input type="text" name="fl_url[]" placeholder="https:// 链接地址" style="flex:2">'
        + '<button type="button" class="yk-btn red sm" onclick="this.parentNode.remove()">删除</button>';
    row.querySelector('input[name="fl_name[]"]').value = name;
    row.querySelector('input[name="fl_url[]"]').value = url;
    document.getElementById('ykFlRows').appendChild(row);
}
</script>
    <?php
    yk_medialib_assets();
    require dirname(__DIR__) . '/inc/footer.php';
    exit;
}

// ---------- 列表 ----------
$list = db_all("SELECT * FROM $T ORDER BY sort ASC, id ASC");
$colNames = array();
foreach (db_all('SELECT id, name FROM ' . DB_PREFIX . 'column') as $c) {
    $colNames[$c['id']] = $c['name'];
}
$pageNames = array();
foreach (db_all('SELECT id, name FROM ' . DB_PREFIX . 'page') as $p) {
    $pageNames[$p['id']] = $p['name'];
}
$badgeColor = array('about' => '#1a9b4c', 'article' => '#1e6fff', 'product' => '#ff7d2a', 'link' => '#7c3aed');

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3>首页模块列表 <a class="yk-btn sm" href="index.php?act=add" style="float:right">+ 添加模块</a></h3>
  <table class="yk-table">
    <tr><th width="90">类型</th><th>模块名</th><th width="70">样式</th><th width="120">数据源</th><th width="80">条数/字数</th><th width="110">排序</th><th width="70">显示</th><th width="130">操作</th></tr>
    <?php foreach ($list as $b): $mt = isset($modNames[$b['mod_type']]) ? $b['mod_type'] : 'article'; ?>
    <tr>
      <td><span style="display:inline-block;padding:2px 8px;border-radius:3px;color:#fff;font-size:12px;background:<?php echo $badgeColor[$mt]; ?>"><?php echo e($modNames[$mt]); ?></span></td>
      <td><?php echo e($b['name']); ?></td>
      <td>样式 <?php echo (int)$b['tpl_id']; ?></td>
      <td><?php
        if ($mt === 'about') {
            echo $b['col_id'] && isset($pageNames[$b['col_id']]) ? e($pageNames[$b['col_id']]) : '<span style="color:#999">未设置</span>';
        } elseif ($mt === 'link') {
            echo '<span style="color:#999">文字链接（页脚显示）</span>';
        } else {
            echo $b['col_id'] && isset($colNames[$b['col_id']]) ? e($colNames[$b['col_id']]) : '<span style="color:#999">未设置</span>';
        }
      ?></td>
      <td><?php echo $mt === 'link' ? '-' : (int)$b['list_num'] . ($mt === 'about' ? ' 字' : ' 条'); ?></td>
      <td style="white-space:nowrap">
        <form method="post" action="index.php" style="display:inline">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="move"><input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>"><input type="hidden" name="dir" value="up">
          <button type="submit" class="yk-btn gray sm">上移</button>
        </form>
        <form method="post" action="index.php" style="display:inline">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="move"><input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>"><input type="hidden" name="dir" value="down">
          <button type="submit" class="yk-btn gray sm">下移</button>
        </form>
      </td>
      <td>
        <form method="post" action="index.php" style="display:inline">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="toggle">
          <input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>">
          <button type="submit" style="background:none;border:none;cursor:pointer;padding:0;font-size:13px;color:<?php echo $b['is_show'] ? '#1a9b4c' : '#d93025'; ?>"><?php echo $b['is_show'] ? '显示' : '隐藏'; ?></button>
        </form>
      </td>
      <td class="yk-actions">
        <a href="index.php?act=edit&amp;id=<?php echo (int)$b['id']; ?>">编辑</a>
        <form method="post" action="index.php" style="display:inline" onsubmit="return confirm('确定删除该模块？');">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="delete">
          <input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$list): ?><tr><td colspan="8" style="text-align:center;color:#999">暂无模块，点击右上角「+ 添加模块」创建</td></tr><?php endif; ?>
  </table>
</div>
<?php require dirname(__DIR__) . '/inc/footer.php'; ?>
