<?php
declare(strict_types=1);

namespace Celena\Module\Dashboard;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Template\Engine;
use Celena\Module\Settings\Options;

/**
 * Главная страница фронта. Показывает последние новости (как демо-лента).
 */
final class HomeController
{
    public function __construct(
        private readonly Engine $engine,
        private readonly Options $options,
        private readonly Connection $conn,
    ) {
    }

    public function index(Request $request): Response
    {
        $siteName = (string) $this->options->get('site_name', 'Celena CMS');
        $siteUrl = (string) $this->options->get('site_url', '');

        $news = $this->conn->builder('celena_news')
            ->where('status', '=', 'published')
            ->orderBy('published_at', 'desc')
            ->limit(5)
            ->get();
        foreach ($news as &$n) {
            $n['url'] = '/news/' . $n['slug'];
            $n['date'] = (string) ($n['published_at'] ?? '');
        }
        unset($n);

        // Hero-слайды для главной commerce-темы. Берём последние активные
        // товары; если плагин shop неактивен или таблицы нет — пустой массив.
        $heroSlides = [];
        try {
            $themes = ['lime', 'green', 'peach', 'mint'];
            $rows = $this->conn->builder('shop_products')
                ->where('is_active', '=', true)
                ->orderBy('is_featured', 'desc')
                ->orderBy('id', 'desc')
                ->limit(4)
                ->get();
            foreach ($rows as $i => $r) {
                $heroSlides[] = [
                    'title'         => (string) $r['title'],
                    'url'           => '/shop/product/' . (string) $r['slug'],
                    'cover'         => (string) ($r['cover'] ?? ''),
                    'price_fmt'     => number_format((float) $r['price'], 2, '.', ' '),
                    'old_price_fmt' => !empty($r['old_price']) ? number_format((float) $r['old_price'], 2, '.', ' ') : '',
                    'theme'         => $themes[$i % count($themes)],
                    'is_first'      => $i === 0 ? '1' : '',
                ];
            }
        } catch (\Throwable) {
            $heroSlides = [];
        }

        $vars = [
            'site' => ['name' => $siteName, 'url' => $siteUrl],
            'page' => [
                'title' => $siteName,
                'seo_title' => (string) ($this->options->get('seo_title') ?: $siteName),
                'seo_description' => (string) ($this->options->get('seo_description') ?: $this->options->get('site_tagline', '')),
                'og_image' => '',
            ],
            'news' => $news,
            'hero_slides' => $heroSlides,
            'now' => date('Y-m-d H:i'),
        ];
        $this->engine->setTheme((string) $this->options->get('theme', 'default'));
        return Response::html($this->engine->render('home', $vars));
    }
}
