<?php

class ThemeController
{
    protected $view;
    protected $context;

    public function __construct(array $context)
    {
        $this->context = $context;
        $this->view = new ThemeView($context['theme'] ?? 'industrial');
    }

    protected function render($view, array $data = array())
    {
        $this->view->render($view, array_merge($this->context, $data));
    }

    protected function dataFile($file)
    {
        $path = __DIR__ . '/../data/' . $file . '.php';
        return is_file($path) ? include $path : array();
    }

    protected function themeItems($file)
    {
        $pool = $this->dataFile($file);
        $theme = $this->context['theme'] ?? 'industrial';
        $items = $pool[$theme] ?? (is_array($pool) ? reset($pool) : array());
        if($file === 'products'){
            $items = $this->normalizeProductItems(is_array($items) ? $items : array(), $theme);
        }
        if($file === 'cases'){
            $items = $this->normalizeCaseItems(is_array($items) ? $items : array(), $theme);
        }
        return $items;
    }

    protected function normalizeProductItems(array $items, $theme)
    {
        $theme = preg_replace('/[^a-z0-9\-_]/i', '', (string)$theme);
        if(!$items) return $items;

        $baseCount = count($items);
        $maxId = 0;
        foreach($items as $item){
            $maxId = max($maxId, intval($item['id'] ?? 0));
        }

        $suffixes = array(
            4 => '（专项服务）',
            5 => '（配套支持）',
            6 => '（长期维护）',
        );
        while(count($items) < 6){
            $next = count($items) + 1;
            $base = $items[($next - 1) % $baseCount];
            $base['id'] = ++$maxId;
            $base['title'] = trim((string)($base['title'] ?? '主营业务')) . ($suffixes[$next] ?? (' ' . $next));
            $base['summary'] = trim((string)($base['summary'] ?? '')) . ' 提供更细分的执行支持，便于客户按阶段选择服务内容。';
            $base['content'] = trim((string)($base['content'] ?? '')) . ' 该服务更强调现场需求、执行节奏、过程反馈和后续维护，适合作为主营业务的补充方案。';
            $items[] = $base;
        }

        foreach($items as $idx=>$item){
            if($idx < 6){
                $items[$idx]['image'] = '/assets/uploads/product/' . $theme . '-product-' . ($idx + 1) . '.jpg';
            }
        }
        return $items;
    }

    protected function normalizeCaseItems(array $items, $theme)
    {
        $theme = preg_replace('/[^a-z0-9\-_]/i', '', (string)$theme);
        foreach($items as $idx=>$item){
            $imageIndex = ($idx % 3) + 1;
            $image = '/assets/uploads/case/' . $theme . '-case-' . $imageIndex . '.jpg';
            if(is_file(__DIR__ . '/..' . $image)){
                $items[$idx]['image'] = $image;
            }
        }
        return $items;
    }

    protected function contentItems($type, array $baseItems = array())
    {
        $txtItems = function_exists('txt_articles_load') ? txt_articles_load($type) : array();
        $items = $txtItems ? array_merge($txtItems, $baseItems) : $baseItems;
        $this->sortItemsDesc($items);
        return $items;
    }

    protected function sortItemsDesc(array &$items)
    {
        usort($items, function($a, $b){
            $tb = $this->itemTime($b);
            $ta = $this->itemTime($a);
            if($tb === $ta){
                return intval($b['id'] ?? 0) <=> intval($a['id'] ?? 0);
            }
            return $tb <=> $ta;
        });
    }

    protected function itemTime(array $item)
    {
        foreach(array('publish_time', 'updated_at', 'created_at', 'date') as $field){
            if(empty($item[$field])) continue;
            if(is_numeric($item[$field])) return (int)$item[$field];
            $time = strtotime((string)$item[$field]);
            if($time) return $time;
        }
        return 0;
    }

    protected function newsItems()
    {
        $content = $this->themeItems('content');
        $baseItems = array_merge($content['company_news'] ?? array(), $content['industry_news'] ?? array());
        return $this->contentItems('news', $baseItems);
    }

    protected function findItem(array $items)
    {
        $id = $_GET['id'] ?? 0;
        return function_exists('find_item') ? find_item($items, $id) : null;
    }

    protected function notFoundItem(array $items, array $fallback)
    {
        http_response_code(404);
        return $items[0] ?? $fallback;
    }
}

class HomeController extends ThemeController
{
    protected function homeDescription()
    {
        $company = $this->context['company'] ?? array();
        $desc = trim((string)($company['description'] ?? ''));
        $host = strtolower($_SERVER['HTTP_HOST'] ?? '');
        $host = preg_replace('/:\d+$/', '', $host);
        $host = preg_replace('/[^a-z0-9\.\-]/i', '', $host);
        if($host === '' || stripos($desc, $host) !== false) return $desc;
        $name = trim((string)($company['name'] ?? ''));
        $tail = $name !== '' ? ('欢迎通过 ' . $host . ' 了解' . $name . '的服务内容、案例动态与联系方式。') : ('欢迎通过 ' . $host . ' 了解服务内容、案例动态与联系方式。');
        return trim($desc . ' ' . $tail);
    }

    public function index()
    {
        $news = $this->newsItems();
        $content = array(
            'company_news' => array_slice($news, 0, 1),
            'industry_news' => array_slice($news, 1),
        );
        $this->render('home/index', array(
            'pageTitle' => $this->context['company']['title'] ?? '',
            'pageDesc' => $this->homeDescription(),
            'products' => array_slice($this->contentItems('product', $this->themeItems('products')), 0, 6),
            'cases' => $this->contentItems('case', $this->themeItems('cases')),
            'contentData' => $content,
            'faqs' => $this->contentItems('faq', $this->themeItems('faq')),
            'showLinks' => true,
        ));
    }
}

class NewsController extends ThemeController
{
    public function index()
    {
        $company = $this->context['company'];
        $this->render('news/index', array(
            'pageTitle' => '新闻资讯_' . ($company['name'] ?? ''),
            'pageDesc' => '查看' . ($company['name'] ?? '') . '企业新闻、行业资讯和项目动态。',
            'items' => $this->newsItems(),
        ));
    }

    public function detail()
    {
        $items = $this->newsItems();
        $item = $this->findItem($items);
        if(!$item){
            $item = $this->notFoundItem($items, array('title'=>'内容不存在','summary'=>'','content'=>''));
        }
        $company = $this->context['company'];
        $this->render('news/detail', array(
            'pageTitle' => ($item['title'] ?? '') . '_' . ($company['name'] ?? ''),
            'pageDesc' => $item['summary'] ?? '',
            'item' => $item,
            'items' => $items,
        ));
    }
}

class ProductController extends ThemeController
{
    protected function items()
    {
        return $this->contentItems('product', $this->themeItems('products'));
    }

    public function index()
    {
        $company = $this->context['company'];
        $this->render('product/index', array(
            'pageTitle' => '产品服务_' . ($company['name'] ?? ''),
            'pageDesc' => '查看' . ($company['name'] ?? '') . '产品服务与项目支持内容。',
            'items' => $this->items(),
        ));
    }

    public function detail()
    {
        $items = $this->items();
        $item = $this->findItem($items);
        if(!$item){
            $item = $this->notFoundItem($items, array('title'=>'内容不存在','summary'=>'','content'=>''));
        }
        $company = $this->context['company'];
        $this->render('product/detail', array(
            'pageTitle' => ($item['title'] ?? '') . '_' . ($company['name'] ?? ''),
            'pageDesc' => $item['summary'] ?? '',
            'item' => $item,
            'items' => $items,
        ));
    }
}

class CaseController extends ThemeController
{
    protected function items()
    {
        return $this->contentItems('case', $this->themeItems('cases'));
    }

    public function index()
    {
        $company = $this->context['company'];
        $this->render('case/index', array(
            'pageTitle' => '客户案例_' . ($company['name'] ?? ''),
            'pageDesc' => '查看' . ($company['name'] ?? '') . '客户案例和项目服务经验。',
            'items' => $this->items(),
        ));
    }

    public function detail()
    {
        $items = $this->items();
        $item = $this->findItem($items);
        if(!$item){
            $item = $this->notFoundItem($items, array('title'=>'内容不存在','summary'=>'','content'=>''));
        }
        $company = $this->context['company'];
        $this->render('case/detail', array(
            'pageTitle' => ($item['title'] ?? '') . '_' . ($company['name'] ?? ''),
            'pageDesc' => $item['summary'] ?? '',
            'item' => $item,
            'items' => $items,
        ));
    }
}

class FaqController extends ThemeController
{
    protected function items()
    {
        return $this->contentItems('faq', $this->themeItems('faq'));
    }

    public function index()
    {
        $company = $this->context['company'];
        $this->render('faq/index', array(
            'pageTitle' => '常见问题_' . ($company['name'] ?? ''),
            'pageDesc' => '查看' . ($company['name'] ?? '') . '服务咨询与项目常见问题。',
            'items' => $this->items(),
        ));
    }

    public function detail()
    {
        $items = $this->items();
        $item = $this->findItem($items);
        if(!$item){
            $item = $this->notFoundItem($items, array('question'=>'内容不存在','answer'=>'','content'=>''));
        }
        $company = $this->context['company'];
        $title = $item['question'] ?? ($item['title'] ?? '');
        $this->render('faq/detail', array(
            'pageTitle' => $title . '_' . ($company['name'] ?? ''),
            'pageDesc' => $item['answer'] ?? ($item['summary'] ?? ''),
            'item' => $item,
            'items' => $items,
        ));
    }
}

class PageController extends ThemeController
{
    public function about()
    {
        $company = $this->context['company'];
        $this->render('page/about', array(
            'pageTitle' => '关于我们_' . ($company['name'] ?? ''),
            'pageDesc' => ($company['name'] ?? '') . '企业介绍、服务理念与发展情况。',
        ));
    }

    public function contact()
    {
        $company = $this->context['company'];
        $this->render('page/contact', array(
            'pageTitle' => '联系我们_' . ($company['name'] ?? ''),
            'pageDesc' => '联系' . ($company['name'] ?? '') . '，了解服务咨询、项目合作与售后支持。',
        ));
    }
}
