<?php
namespace App\Controllers\Admin;

use App\Models\Setting;
use App\Models\PageSeo;
use Core\Theme;

class SettingController extends AdminController
{
    private $themeFields = [
        'preset', 'primary', 'primary_600', 'secondary', 'accent',
        'bg', 'surface', 'text', 'muted', 'border', 'nav_bg',
        'font', 'radius', 'container', 'header', 'default_mode', 'custom_css',
    ];
    private $siteFields = [
        'site_name', 'site_slogan', 'contact_phone', 'contact_email',
        'contact_address', 'site_logo', 'icp', 'gongan', 'seo_title', 'seo_keywords', 'seo_description',
    ];
    private $payFields = [
        'pay_enabled', 'pay_mode',
        'pay_alipay_appid', 'pay_alipay_private_key', 'pay_alipay_public_key', 'pay_alipay_gateway',
        'pay_wechat_mchid', 'pay_wechat_appid', 'pay_wechat_key',
    ];

    /** 站点设置 */
    public function index()
    {
        $setting = new Setting();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (csrf_check()) {
                $pairs = [];
                foreach ($this->siteFields as $k) $pairs[$k] = $this->post($k, '');
                // 网站 Logo：优先用上传文件，其次用填写的图片路径/网址；两者皆空则保留现值
                $logoUp = $this->uploadFile('logo');
                if ($logoUp !== null) {
                    $pairs['site_logo'] = $logoUp;
                } else {
                    $url = trim((string) $this->post('logo_url', ''));
                    if ($url !== '') {
                        $pairs['site_logo'] = $url;
                    } else {
                        unset($pairs['site_logo']); // 不覆盖，保留数据库现有值（含默认商标）
                    }
                }
                $setting->saveMany($pairs, 'site');
            }
            $this->redirect('admin/settings');
        }
        $vals = [];
        foreach ($this->siteFields as $k) $vals[$k] = $setting->get($k, Theme::get($k));
        return $this->view('admin/settings', ['v' => $vals, 'seg' => 'settings']);
    }

    /** 风格 / 主题设置（任意网页风格） */
    public function theme()
    {
        $setting = new Setting();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (csrf_check()) {
                $pairs = [];
                foreach ($this->themeFields as $k) $pairs[$k] = $this->post($k, '');
                $setting->saveMany($pairs, 'theme');
                Theme::clearCache();
                Theme::regenerate();
            }
            $this->redirect('admin/theme');
        }
        $vals = [];
        foreach ($this->themeFields as $k) $vals[$k] = $setting->get($k, Theme::get($k, ''));
        return $this->view('admin/theme', [
            'v'       => $vals,
            'presets' => Theme::presets(),
            'seg'     => 'theme',
        ]);
    }

    /** 支付设置（支付宝 / 微信） */
    public function payment()
    {
        $setting = new Setting();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (csrf_check()) {
                $pairs = [];
                foreach ($this->payFields as $k) $pairs[$k] = $this->post($k, '');
                $setting->saveMany($pairs, 'pay');
            }
            $this->redirect('admin/payments');
        }
        $vals = [];
        foreach ($this->payFields as $k) $vals[$k] = $setting->get($k, Theme::get($k, ''));
        return $this->view('admin/payment', ['v' => $vals, 'seg' => 'payments']);
    }

    /** 逐页 SEO 页面清单（首页 / 产品中心 / 产品分类 / 新闻 / 案例 / 关于我们 / 联系我们） */
    private $seoPages = [
        'home'             => ['label' => '首页',       'title_min' => 35, 'desc_min' => 120, 'kw_min' => 10],
        'products'         => ['label' => '产品中心',   'title_min' => 0,  'desc_min' => 120, 'kw_min' => 10],
        'product_category' => ['label' => '产品分类页', 'title_min' => 0,  'desc_min' => 80,  'kw_min' => 6, 'note' => '支持 {cat} 占位符，前端会自动替换为当前分类名。'],
        'news'             => ['label' => '新闻列表',   'title_min' => 0,  'desc_min' => 120, 'kw_min' => 8],
        'cases'            => ['label' => '客户案例',   'title_min' => 0,  'desc_min' => 120, 'kw_min' => 7],
        'about'            => ['label' => '关于我们',   'title_min' => 0,  'desc_min' => 120, 'kw_min' => 7],
        'contact'          => ['label' => '联系我们',   'title_min' => 0,  'desc_min' => 120, 'kw_min' => 7],
    ];

    /** SEO 设置：页面清单（每个页面进入独立编辑页） */
    public function seo()
    {
        admin_required();
        $pageSeo = new PageSeo();
        $rows = [];
        try {
            $rows = $pageSeo->allIndexed();
        } catch (\Throwable $e) {
            // 表尚未创建（未执行升级 SQL）时给出提示，不致命报错
            $this->flash('未检测到 page_seo 表，请先到「数据库升级」执行 005_page_seo.sql', 'err');
        }
        return $this->view('admin/seo', [
            'pages' => $this->seoPages,
            'rows'  => $rows,
            'seg'   => 'seo',
        ]);
    }

    /** SEO 单页编辑：admin/seo/edit/{key} */
    public function edit($key = null)
    {
        admin_required();
        if (!$key || !isset($this->seoPages[$key])) {
            $this->flash('未找到该 SEO 页面', 'err');
            $this->redirect('admin/seo');
            return '';
        }
        $meta = $this->seoPages[$key];
        $pageSeo = new PageSeo();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!csrf_check()) {
                $this->flash('表单已过期，请刷新后重试', 'err');
                $this->redirect('admin/seo/edit/' . $key);
                return '';
            }
            $pageSeo->saveRow($key, [
                'title'          => trim((string)($_POST['title'] ?? '')),
                'description'    => trim((string)($_POST['description'] ?? '')),
                'keywords'       => trim((string)($_POST['keywords'] ?? '')),
                'og_title'       => trim((string)($_POST['og_title'] ?? '')),
                'og_description' => trim((string)($_POST['og_description'] ?? '')),
                'og_image'       => trim((string)($_POST['og_image'] ?? '')),
                'og_type'        => trim((string)($_POST['og_type'] ?? 'website')),
                'canonical'      => trim((string)($_POST['canonical'] ?? '')),
                'noindex'        => isset($_POST['noindex']) ? 1 : 0,
            ]);
            $this->flash('「' . $meta['label'] . '」SEO 设置已保存', 'ok');
            $this->redirect('admin/seo/edit/' . $key);
            return '';
        }

        $row = [];
        try {
            $row = $pageSeo->getByKey($key) ?: [];
        } catch (\Throwable $e) {
            $this->flash('未检测到 page_seo 表，请先到「数据库升级」执行 005_page_seo.sql', 'err');
        }
        return $this->view('admin/seo_edit', [
            'key'  => $key,
            'meta' => $meta,
            'v'    => $row,
            'seg'  => 'seo',
        ]);
    }
}
