<?php
declare(strict_types=1);

namespace Celena\Module\Settings;

use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Auth;
use Celena\Core\Security\Csrf;
use Celena\Core\Security\Filter;
use Celena\Core\Security\Permission;
use Celena\Core\Template\Engine;
use Celena\Core\Template\ThemeManager;
use Celena\Module\AdminBase\AdminController;

/**
 * Настройки: общие + SEO по умолчанию + производительность/кеш + переключатель темы.
 */
final class SettingsController extends AdminController
{
    public function __construct(
        Engine $engine,
        Auth $auth,
        Options $options,
        private readonly ThemeManager $themes,
    ) {
        parent::__construct($engine, $auth, $options);
    }

    public function index(Request $request): Response
    {
        if (!Permission::can($this->auth->user(), 'options.read')) {
            return $this->redirect('/admin', 'Доступ запрещён.', 'error');
        }
        return $this->view('admin/settings/index', [
            'opts' => [
                'site_name'      => (string) $this->options->get('site_name', 'Celena CMS'),
                'site_url'       => (string) $this->options->get('site_url', ''),
                'site_tagline'   => (string) $this->options->get('site_tagline', ''),
                'theme'          => (string) $this->options->get('theme', 'default'),
                'posts_per_page' => (string) $this->options->get('posts_per_page', '10'),
                'locale'         => (string) $this->options->get('locale', 'ru'),
                'seo_title'      => (string) $this->options->get('seo_title', ''),
                'seo_description'=> (string) $this->options->get('seo_description', ''),
                'seo_keywords'   => (string) $this->options->get('seo_keywords', ''),
                'cache_templates'=> (string) $this->options->get('cache_templates', '1'),
                'cache_data'     => (string) $this->options->get('cache_data', '1'),
                'cache_http'     => (string) $this->options->get('cache_http', '0'),
                'comments_open'  => (string) $this->options->get('comments_open', '1'),
                'comments_moderate' => (string) $this->options->get('comments_moderate', '1'),
                'media_max_original' => (string) $this->options->get('media_max_original', '2400'),
                'media_thumb_size'   => (string) $this->options->get('media_thumb_size', '320'),
                'media_medium_size'  => (string) $this->options->get('media_medium_size', '800'),
                'media_large_size'   => (string) $this->options->get('media_large_size', '1600'),
                'media_jpeg_quality' => (string) $this->options->get('media_jpeg_quality', '82'),
                'media_webp_quality' => (string) $this->options->get('media_webp_quality', '80'),
                'gdpr_enabled'       => (string) $this->options->get('gdpr_enabled', '0'),
                'gdpr_eu_only'       => (string) $this->options->get('gdpr_eu_only', '1'),
                'gdpr_text'          => (string) $this->options->get('gdpr_text', 'Мы используем cookie для работы сайта и аналитики. Продолжая, вы соглашаетесь с нашей Политикой конфиденциальности.'),
                'gdpr_accept_label'  => (string) $this->options->get('gdpr_accept_label', 'Принимаю'),
                'gdpr_decline_label' => (string) $this->options->get('gdpr_decline_label', 'Отказаться'),
                'gdpr_privacy_url'   => (string) $this->options->get('gdpr_privacy_url', '/p/privacy'),
            ],
            'themes' => $this->themes->all(),
        ], 'settings', 'Настройки');
    }

    public function save(Request $request): Response
    {
        if (!Permission::can($this->auth->user(), 'options.write')) {
            return $this->redirect('/admin/settings', 'Доступ запрещён.', 'error');
        }
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/settings', 'CSRF.', 'error');
        }
        $fields = [
            'site_name', 'site_url', 'site_tagline', 'theme',
            'seo_title', 'seo_description', 'seo_keywords',
            'locale',
        ];
        foreach ($fields as $f) {
            $value = Filter::string($request->input($f, ''), 65535);
            $this->options->set($f, $value);
        }
        $this->options->set('posts_per_page', (string) Filter::int($request->input('posts_per_page', 10), 10));
        foreach (['cache_templates', 'cache_data', 'cache_http', 'comments_open', 'comments_moderate'] as $f) {
            $this->options->set($f, Filter::bool($request->input($f, false)) ? '1' : '0');
        }

        // Настройки медиа-пайплайна
        $mediaDefaults = [
            'media_max_original' => [200, 8000, 2400],
            'media_thumb_size'   => [64,  800,  320],
            'media_medium_size'  => [100, 2000, 800],
            'media_large_size'   => [200, 4000, 1600],
            'media_jpeg_quality' => [10,  100,  82],
            'media_webp_quality' => [10,  100,  80],
        ];
        foreach ($mediaDefaults as $key => [$min, $max, $default]) {
            $v = Filter::int($request->input($key, $default), $default);
            if ($v < $min) $v = $min;
            if ($v > $max) $v = $max;
            $this->options->set($key, (string) $v);
        }

        // GDPR-баннер
        foreach (['gdpr_enabled', 'gdpr_eu_only'] as $f) {
            $this->options->set($f, Filter::bool($request->input($f, false)) ? '1' : '0');
        }
        $this->options->set('gdpr_text',          Filter::string($request->input('gdpr_text', ''), 2000));
        $this->options->set('gdpr_accept_label',  Filter::string($request->input('gdpr_accept_label', 'Принимаю'), 100));
        $this->options->set('gdpr_decline_label', Filter::string($request->input('gdpr_decline_label', 'Отказаться'), 100));
        $this->options->set('gdpr_privacy_url',   Filter::string($request->input('gdpr_privacy_url', ''), 300));

        return $this->redirect('/admin/settings', 'Настройки сохранены.');
    }

    public function clearCache(Request $request): Response
    {
        if (!Permission::can($this->auth->user(), 'options.write')) {
            return $this->redirect('/admin', 'Доступ запрещён.', 'error');
        }
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/settings', 'CSRF.', 'error');
        }
        $root = \Celena\Core\Kernel::rootPath();
        $count = 0;
        foreach (glob($root . '/storage/cache/tpl/*.php') ?: [] as $f) { @unlink($f); $count++; }
        foreach (glob($root . '/storage/cache/data/*') ?: [] as $f)   { if (is_file($f)) { @unlink($f); $count++; } }
        foreach (glob($root . '/storage/cache/http/*') ?: [] as $f)   { if (is_file($f)) { @unlink($f); $count++; } }
        return $this->redirect('/admin/settings', "Очищено $count файл(ов) кеша.");
    }
}
