<?php
/**
 * ITSWEBER CMS – Site Notice Controller
 *
 * Admin settings page for the global announcement bar.
 * Data is stored in iw_plugin_settings (plugin_slug='site_notice').
 *
 * @author    Benny Weber (ITSWEBER)
 * @copyright © ITSWEBER – www.itsweber.de
 * @contact   kontakt@itsweber.de
 */

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;

class SiteNoticeController extends Controller
{
    /**
     * Show Site Notice settings form.
     * GET /admin/settings/site-notice
     */
    public function index(Request $request, array $params = []): void
    {
        $config = $this->loadConfig();

        $this->renderAdmin('settings/site-notice', [
            'pageTitle' => __('admin.site_notice.title'),
            'config'    => $config,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
    }

    /**
     * Save Site Notice settings.
     * POST /admin/settings/site-notice
     */
    public function save(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $allowedVariant = ['info', 'success', 'warning', 'danger'];
        $allowedDismiss = ['session', 'permanent', 'none'];
        $allowedPosition = ['after_header', 'before_footer'];

        $variant = trim($request->input('variant', 'info'));
        if (!in_array($variant, $allowedVariant, true)) {
            $variant = 'info';
        }

        $dismiss = trim($request->input('dismiss', 'session'));
        if (!in_array($dismiss, $allowedDismiss, true)) {
            $dismiss = 'session';
        }

        $position = trim($request->input('position', 'after_header'));
        if (!in_array($position, $allowedPosition, true)) {
            $position = 'after_header';
        }

        $linkUrl = trim($request->input('link_url', ''));
        if ($linkUrl !== '' && !preg_match('/^(https?:\/\/|\/)/i', $linkUrl)) {
            $linkUrl = '';
        }

        $config = [
            'active'     => $request->input('active') ? 1 : 0,
            'text'       => trim($request->input('text', '')),
            'variant'    => $variant,
            'link_url'   => $linkUrl,
            'link_label' => trim($request->input('link_label', '')),
            'dismiss'    => $dismiss,
            'position'   => $position,
        ];

        $this->saveConfig($config);

        set_flash('success', __('admin.site_notice.saved'));
        Response::redirect(admin_url('settings/site-notice'));
    }

    /**
     * Load site notice config from DB.
     */
    private function loadConfig(): array
    {
        $defaults = [
            'active' => 0, 'text' => '', 'variant' => 'info',
            'link_url' => '', 'link_label' => '',
            'dismiss' => 'session', 'position' => 'after_header',
        ];

        $json = plugin_setting('site_notice', 'config', '{}');
        $config = json_decode($json, true);

        return is_array($config) ? array_merge($defaults, $config) : $defaults;
    }

    /**
     * Save site notice config to DB.
     */
    private function saveConfig(array $config): void
    {
        $db = $this->db();

        $exists = $db->fetch(
            "SELECT id FROM iw_plugin_settings WHERE plugin_slug = 'site_notice' AND setting_key = 'config' LIMIT 1"
        );

        if ($exists) {
            $db->update('iw_plugin_settings', [
                'setting_value' => json_encode($config, JSON_UNESCAPED_UNICODE),
                'updated_at'    => date('Y-m-d H:i:s'),
            ], ['id' => $exists['id']]);
        } else {
            $db->insert('iw_plugin_settings', [
                'plugin_slug'   => 'site_notice',
                'setting_key'   => 'config',
                'setting_value' => json_encode($config, JSON_UNESCAPED_UNICODE),
            ]);
        }
    }
}
