<?php
namespace App\Controllers;

use App\Models\Category;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $product = new Product();
        $category = new Category();
        $catId = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;

        $products = $catId
            ? $product->byCategory($catId)
            : array_filter($product->all(), fn($p) => ($p['status'] ?? 1) == 1);
        $cat = $catId ? $category->find($catId) : null;

        $catName = $cat['name'] ?? '';
        if ($cat) {
            $seo = page_seo('product_category', [
                'title'       => $catName . '降温服 - 酷冰甲科技降温·定制批发',
                'description' => "酷冰甲{$catName}系列降温服，采用科技降温方案，专为高温作业与户外暴晒场景设计，具备清凉持久、轻便透气、可循环重复使用等特点。支持企业定制、LOGO刺绣与小批量批发，10套起订，7天打样，全国发货。",
                'keywords'    => $catName . '降温服,' . $catName . ',降温服定制,降温背心,工业降温,酷冰甲',
            ]);
            foreach (['title', 'description', 'keywords'] as $f) {
                $seo[$f] = str_replace('{cat}', $catName, $seo[$f]);
            }
        } else {
            $seo = page_seo('products', [
                'title'       => '降温服产品中心 - 水冷/相变/风冷多系列 | 酷冰甲',
                'description' => '酷冰甲降温服产品中心，系统展示水冷循环降温服、相变冰袋降温背心、风冷制冷背心、冰马甲等多系列产品，按使用场景与降温方式分类，参数规格与适用行业一目了然。支持企业批量定制、LOGO刺绣与免费拿样，提供专业选型建议与透明报价，助力高温作业安全防护。',
                'keywords'    => '降温服产品,水冷降温服,相变降温服,风冷降温服,制冷背心,冰马甲,工业降温装备,降温服批发,降温服定制,酷冰甲产品',
            ]);
        }
        $pageTitle = $catName ? $catName . ' - 产品中心' : '产品中心';
        $pageDesc = $catName ? str_replace('{cat}', $catName, "酷冰甲{cat}系列降温服，科技降温，清凉定制。") : '酷冰甲全系列降温服产品：水冷循环、相变蓄冷、涡扇风冷、工业降温工装，支持小批量定制。';

        return $this->view('product/index', [
            'pageSeo' => [
                'title'       => $seo['title'],
                'description' => $seo['description'],
                'keywords'    => $seo['keywords'],
                'og_type'     => 'website',
                'og_image'    => $seo['og_image'],
                'canonical'   => $seo['canonical'],
                'noindex'     => $seo['noindex'],
                'breadcrumb'  => $catName ? [
                    ['name' => '首页', 'url' => site_url()],
                    ['name' => '产品中心', 'url' => site_url('products')],
                    ['name' => $catName, 'url' => absolute_url()],
                ] : null,
            ],
            'products'  => $products,
            'categories'=> $category->all(),
            'activeCat' => $catId,
            'cat'       => $cat,
        ]);
    }

    public function show($slug)
    {
        $product = new Product();
        $p = $product->where('slug', $slug);
        if (!$p && is_numeric($slug)) { $p = $product->find((int)$slug); }
        if (!$p) { \Core\App::notFound(); return ''; }

        $category = new Category();
        $cat = $category->find($p['category_id'] ?? 0);
        $related = array_filter($product->byCategory($p['category_id'] ?? 0), fn($x) => $x['id'] != $p['id']);

        $pName = e($p['name'] ?? '产品详情');
        $pSummary = mb_substr(strip_tags($p['summary'] ?? $p['body'] ?? ''), 0, 160);
        $pImage = $p['cover'] ?? '';
        $pPrice = $p['price'] ?? '';
        $pSku = $p['sku'] ?? ($p['model'] ?? '');

        // ── Product JSON-LD Schema ──
        $productSchema = '<script type="application/ld+json">' . json_encode([
            '@context'    => 'https://schema.org',
            '@type'       => 'Product',
            'name'        => $p['name'] ?? '',
            'description' => $pSummary,
            'image'       => $pImage,
            'sku'         => $pSku,
            'category'    => $cat['name'] ?? '',
        ] + ($pPrice ? ['offers' => [
            '@type'         => 'Offer',
            'price'         => $pPrice,
            'priceCurrency' => 'CNY',
            'availability'  => 'https://schema.org/InStock',
        ]] : []), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';

        // ── 产品页 FAQ（可见文本 + FAQPage JSON-LD，GEO 信号）────
        $faqs = [
            ['q' => '这款降温服采用什么降温原理？', 'a' => '根据系列不同，分别采用水冷循环、相变蓄冷或涡扇风冷原理散热：水冷通过微型水泵驱动冷水循环带走体热，相变依靠冰袋/凝胶融化吸热，风冷由风扇强制对流降温。详情可在商品规格表中查看对应方案。'],
            ['q' => '一次可使用多长时间？', 'a' => '相变冰袋方案单组可持续 2–4 小时，可随用随换；水冷与风冷方案续航取决于电池容量，具体以商品规格为准，支持备用电池延长作业时间。'],
            ['q' => '是否支持企业定制与 LOGO 刺绣？', 'a' => '支持。提供企业 LOGO 绣字、颜色与面料定制、一人一码量体服务，10 套起订，确认图纸后 7 天打样、约 28 天批量交付。'],
            ['q' => '如何选择合适的尺码？', 'a' => '提供标准尺码表并支持上门量体，下单后可按身高体重推荐尺码；特殊体型或工种可单独打版，确保合身与活动便利。'],
        ];
        $faqSchema = '<script type="application/ld+json">' . json_encode([
            '@context' => 'https://schema.org',
            '@type'    => 'FAQPage',
            'mainEntity' => array_map(fn($f) => [
                '@type'          => 'Question',
                'name'           => $f['q'],
                'acceptedAnswer' => ['@type' => 'Answer', 'text' => $f['a']],
            ], $faqs),
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';

        return $this->view('product/show', [
            'pageSeo' => [
                'title'       => $pName,
                'description' => $pSummary,
                'og_type'     => 'product',
                'og_image'    => $pImage,
                'breadcrumb'  => [
                    ['name' => '首页', 'url' => site_url()],
                    ['name' => '产品中心', 'url' => site_url('products')],
                    ['name' => $p['name'] ?? '产品', 'url' => absolute_url()],
                ],
                'jsonld'      => $productSchema . $faqSchema,
            ],
            'p'       => $p,
            'cat'     => $cat,
            'related' => array_slice($related, 0, 3),
            'specs'   => $product->specsArray($p),
            'faqs'    => $faqs,
        ]);
    }
}
