<?php
/**
 * 炎酷CMS - 站点设置（分组表单，一次保存）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require dirname(__DIR__) . '/inc/medialib.php';

$page_title = '站点设置';
$active = 'config';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    // 文本类配置
    $keys = array('company_name', 'phone', 'address', 'email', 'icp', 'copyright',
        'logo', 'wechat_qr', 'favicon', 'kefu_phone', 'kefu_wechat', 'banner_notice',
        'seo_title', 'seo_keywords', 'seo_description',
        'theme_nav_bg', 'theme_nav_color', 'theme_nav_active', 'theme_nav_active_bg', 'theme_accent', 'theme_footer_bg', 'theme_footer_color', 'theme_side_bg', 'theme_side_color');
    foreach ($keys as $k) {
        config_set($k, isset($_POST[$k]) ? trim($_POST[$k]) : '');
    }
    // 伪静态开关
    config_set('rewrite_on', !empty($_POST['rewrite_on']) && $_POST['rewrite_on'] === '1' ? '1' : '0');
    // 模板 ID（tpl_header/tpl_footer/tpl_banner/kefu_style）由【在线编辑】可视化管理，此处不再处理
    // 客服浮动条
    config_set('kefu_on', !empty($_POST['kefu_on']) ? '1' : '0');
    // 上传限制
    config_set('upload_max', (string)max(1, min(100, (int)(isset($_POST['upload_max']) ? $_POST['upload_max'] : 2))));
    $ext = strtolower(preg_replace('/[^a-z0-9,]/', '', isset($_POST['upload_ext']) ? $_POST['upload_ext'] : ''));
    config_set('upload_ext', $ext !== '' ? $ext : 'jpg,jpeg,png,gif,webp');
    // 顶部广告条图片：banner_img[] + banner_url[] 转 JSON
    $imgs = array();
    $bImgs = isset($_POST['banner_img']) && is_array($_POST['banner_img']) ? $_POST['banner_img'] : array();
    $bUrls = isset($_POST['banner_url']) && is_array($_POST['banner_url']) ? $_POST['banner_url'] : array();
    foreach ($bImgs as $i => $img) {
        $img = trim($img);
        if ($img === '') continue;
        $imgs[] = array('img' => $img, 'url' => isset($bUrls[$i]) ? trim($bUrls[$i]) : '');
    }
    config_set('banner_images', json_encode($imgs, JSON_UNESCAPED_UNICODE));

    admin_log('站点设置', '更新站点配置');
    flash_set('站点设置已保存');
    header('Location: index.php');
    exit;
}

$cfg = site_config();
function yk_cfg($cfg, $key, $default = '') {
    return e(isset($cfg[$key]) && $cfg[$key] !== '' ? $cfg[$key] : $default);
}
// 颜色字段：color 选择器 + 文本框同步
function yk_color_field($name, $value, $label, $tip = '') {
    $value = (string)$value;
    $color = preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? $value : '#ffffff';
    echo '<div class="row"><label>' . e($label) . '</label><div class="ipt">';
    echo '<div style="display:flex;gap:8px;align-items:center">';
    echo '<input type="color" id="' . e($name) . '_picker" value="' . e($color) . '" style="width:46px;height:34px;padding:2px;border:1px solid #d5dae3;border-radius:4px;cursor:pointer"'
        . ' oninput="document.getElementById(\'' . e($name) . '\').value=this.value">';
    echo '<input type="text" name="' . e($name) . '" id="' . e($name) . '" value="' . e($value) . '" placeholder="#ffffff"'
        . ' oninput="if(/^#[0-9a-fA-F]{6}$/.test(this.value))document.getElementById(\'' . e($name) . '_picker\').value=this.value">';
    echo '</div>';
    if ($tip !== '') echo '<div class="tip">' . e($tip) . '</div>';
    echo '</div></div>';
}
// banner_images JSON 还原为行
$bannerImgs = json_decode(isset($cfg['banner_images']) ? $cfg['banner_images'] : '[]', true);
if (!is_array($bannerImgs)) $bannerImgs = array();

require dirname(__DIR__) . '/inc/header.php';
?>
<form class="yk-form" method="post" action="index.php">
  <?php echo csrf_field(); ?>

  <div class="yk-card">
    <h3>基本信息</h3>
    <div class="row"><label>公司名称</label><div class="ipt"><input type="text" name="company_name" value="<?php echo yk_cfg($cfg, 'company_name'); ?>"></div></div>
    <div class="row"><label>联系电话</label><div class="ipt"><input type="text" name="phone" value="<?php echo yk_cfg($cfg, 'phone'); ?>"></div></div>
    <div class="row"><label>公司地址</label><div class="ipt"><input type="text" name="address" value="<?php echo yk_cfg($cfg, 'address'); ?>"></div></div>
    <div class="row"><label>电子邮箱</label><div class="ipt"><input type="text" name="email" value="<?php echo yk_cfg($cfg, 'email'); ?>"></div></div>
    <div class="row"><label>备案号</label><div class="ipt"><input type="text" name="icp" value="<?php echo yk_cfg($cfg, 'icp'); ?>"></div></div>
    <div class="row"><label>版权信息</label><div class="ipt"><input type="text" name="copyright" value="<?php echo yk_cfg($cfg, 'copyright'); ?>"></div></div>
  </div>

  <div class="yk-card">
    <h3>SEO 设置</h3>
    <div class="row"><label>SEO 标题</label><div class="ipt"><input type="text" name="seo_title" value="<?php echo yk_cfg($cfg, 'seo_title'); ?>"><div class="tip">全站默认标题，栏目/文章/单页可单独设置</div></div></div>
    <div class="row"><label>SEO 关键词</label><div class="ipt"><input type="text" name="seo_keywords" value="<?php echo yk_cfg($cfg, 'seo_keywords'); ?>"></div></div>
    <div class="row"><label>SEO 描述</label><div class="ipt"><textarea name="seo_description" rows="2"><?php echo yk_cfg($cfg, 'seo_description'); ?></textarea></div></div>
    <div class="row"><label>伪静态开关</label><div class="ipt yk-check">
      <label><input type="radio" name="rewrite_on" value="1"<?php echo yk_cfg($cfg, 'rewrite_on', '0') === '1' ? ' checked' : ''; ?>> 开启</label>
      <label><input type="radio" name="rewrite_on" value="0"<?php echo yk_cfg($cfg, 'rewrite_on', '0') !== '1' ? ' checked' : ''; ?>> 关闭</label>
      <div class="tip">开启后全站链接使用 /product/、/art-1.html、/page-about.html 形式；Nginx 需先在宝塔【伪静态】中粘贴站点根目录 nginx-rewrite.txt 的规则，Apache 无需操作。开启后如果页面 404，说明服务器未配置伪静态规则。</div>
    </div></div>
  </div>

  <div class="yk-card">
    <h3>图片设置</h3>
    <?php
    yk_image_field('logo', isset($cfg['logo']) ? $cfg['logo'] : '', '站点 LOGO');
    yk_image_field('wechat_qr', isset($cfg['wechat_qr']) ? $cfg['wechat_qr'] : '', '微信二维码');
    yk_image_field('favicon', isset($cfg['favicon']) ? $cfg['favicon'] : '', '网站图标 favicon', '建议正方形 png/ico 图片');
    ?>
  </div>

  <div class="yk-card">
    <h3>主题颜色</h3>
    <?php
    yk_color_field('theme_nav_bg', isset($cfg['theme_nav_bg']) ? $cfg['theme_nav_bg'] : '', '导航条背景色');
    yk_color_field('theme_nav_color', isset($cfg['theme_nav_color']) ? $cfg['theme_nav_color'] : '', '导航条文字色');
    yk_color_field('theme_nav_active', isset($cfg['theme_nav_active']) ? $cfg['theme_nav_active'] : '', '导航点击文字色', '导航链接鼠标滑过与当前选中时的文字颜色');
    yk_color_field('theme_nav_active_bg', isset($cfg['theme_nav_active_bg']) ? $cfg['theme_nav_active_bg'] : '', '导航点击背景色', '当前选中导航项的背景颜色');
    yk_color_field('theme_accent', isset($cfg['theme_accent']) ? $cfg['theme_accent'] : '', '全局强调色', '全站链接高亮、按钮、标题装饰等强调颜色（默认红色 #e63946）');
    yk_color_field('theme_footer_bg', isset($cfg['theme_footer_bg']) ? $cfg['theme_footer_bg'] : '', '底部背景色');
    yk_color_field('theme_footer_color', isset($cfg['theme_footer_color']) ? $cfg['theme_footer_color'] : '', '底部文字色');
    yk_color_field('theme_side_bg', isset($cfg['theme_side_bg']) ? $cfg['theme_side_bg'] : '', '侧栏标题背景色');
    yk_color_field('theme_side_color', isset($cfg['theme_side_color']) ? $cfg['theme_side_color'] : '', '侧栏标题文字色');
    ?>
  </div>

  <div class="yk-card">
    <h3>模板选择</h3>
    <div class="tip" style="margin:0">导航 / 底部 / 广告条 / 客服浮动条样式已迁移至左侧菜单【在线编辑】，支持可视化实时预览选择。</div>
  </div>

  <div class="yk-card">
    <h3>客服浮动条</h3>
    <div class="row"><label>是否开启</label><div class="ipt yk-check">
      <label><input type="radio" name="kefu_on" value="1"<?php echo yk_cfg($cfg, 'kefu_on', '0') === '1' ? ' checked' : ''; ?>> 开启</label>
      <label><input type="radio" name="kefu_on" value="0"<?php echo yk_cfg($cfg, 'kefu_on', '0') !== '1' ? ' checked' : ''; ?>> 关闭</label>
    </div></div>
    <div class="row"><label>客服电话</label><div class="ipt"><input type="text" name="kefu_phone" value="<?php echo yk_cfg($cfg, 'kefu_phone'); ?>"><div class="tip">填号码如 88-88888888，前台显示为 tel: 链接，手机点击直接拨号</div></div></div>
    <?php yk_image_field('kefu_wechat', isset($cfg['kefu_wechat']) ? $cfg['kefu_wechat'] : '', '客服微信二维码'); ?>
  </div>

  <div class="yk-card">
    <h3>上传设置</h3>
    <div class="row"><label>上传大小上限</label><div class="ipt"><input type="number" name="upload_max" min="1" max="100" value="<?php echo yk_cfg($cfg, 'upload_max', '2'); ?>"><div class="tip">单位 MB</div></div></div>
    <div class="row"><label>允许上传后缀</label><div class="ipt"><input type="text" name="upload_ext" value="<?php echo yk_cfg($cfg, 'upload_ext', 'jpg,jpeg,png,gif,webp'); ?>"><div class="tip">允许的上传后缀，php 等脚本类型永远禁止</div></div></div>
  </div>

  <div class="yk-card">
    <h3>顶部广告条</h3>
    <div class="row"><label>公告文字</label><div class="ipt"><input type="text" name="banner_notice" value="<?php echo yk_cfg($cfg, 'banner_notice'); ?>"></div></div>
    <div class="row"><label>广告图片</label><div class="ipt">
      <div id="ykBannerRows">
        <?php foreach ($bannerImgs as $bi): $img = isset($bi['img']) ? $bi['img'] : ''; $url = isset($bi['url']) ? $bi['url'] : ''; ?>
        <div class="yk-banner-row" style="display:flex;gap:8px;align-items:center;margin-bottom:8px">
          <input type="text" name="banner_img[]" value="<?php echo e($img); ?>" placeholder="图片路径" style="flex:1">
          <button type="button" class="yk-btn gray sm yk-banner-lib">图库</button>
          <input type="text" name="banner_url[]" value="<?php echo e($url); ?>" placeholder="链接地址（可空）" style="flex:1">
          <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="ykBannerAdd()">+ 添加一行</button>
      <div class="tip">每行一张广告图片，可设置点击跳转链接</div>
    </div></div>
  </div>

  <div class="yk-card">
    <button class="yk-btn" type="submit">保存全部设置</button>
  </div>
</form>
<script>
var ykBannerSeq = 0;
// 给一行绑定图库按钮（行内图片输入框补唯一 id，供 ykMediaPick 回填）
function ykBannerBind(row) {
    var imgInput = row.querySelector('input[name="banner_img[]"]');
    if (!imgInput.id) {
        ykBannerSeq++;
        imgInput.id = 'banner_img_' + ykBannerSeq;
    }
    row.querySelector('.yk-banner-lib').onclick = function () { ykMediaPick(imgInput.id); };
}
function ykBannerAdd(img, url) {
    img = img || ''; url = url || '';
    var row = document.createElement('div');
    row.className = 'yk-banner-row';
    row.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:8px';
    row.innerHTML = '<input type="text" name="banner_img[]" placeholder="图片路径" style="flex:1">'
        + '<button type="button" class="yk-btn gray sm yk-banner-lib">图库</button>'
        + '<input type="text" name="banner_url[]" placeholder="链接地址（可空）" style="flex:1">'
        + '<button type="button" class="yk-btn red sm" onclick="this.parentNode.remove()">删除</button>';
    document.getElementById('ykBannerRows').appendChild(row);
    row.querySelector('input[name="banner_img[]"]').value = img;
    row.querySelector('input[name="banner_url[]"]').value = url;
    ykBannerBind(row);
}
// PHP 渲染的已有行同样走 JS 绑定
document.querySelectorAll('#ykBannerRows .yk-banner-row').forEach(ykBannerBind);
</script>
<?php
yk_medialib_assets();
require dirname(__DIR__) . '/inc/footer.php';
