<?php

namespace App\Http\Controllers\Admin;

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

/**
 * ITSWEBER CMS – Admin Consent Controller
 *
 * Manages the Cookie / Consent banner settings (Phase 6d).
 * All settings are stored in iw_settings with group = 'consent'.
 */
class ConsentController extends Controller
{
    /** Keys managed by this controller (all stored in group 'consent'). */
    private array $consentFields = [
        'consent_enabled',
        'consent_title',
        'consent_text',
        'consent_accept_label',
        'consent_reject_label',
        'consent_settings_label',
        'consent_save_label',
        'consent_cat_necessary_label',
        'consent_cat_necessary_desc',
        'consent_cat_functional_label',
        'consent_cat_functional_desc',
        'consent_privacy_url',
        'consent_privacy_label',
        'consent_cookie_name',
        'consent_cookie_days',
        'consent_show_logo',
        'consent_show_reopen',
        'consent_reopen_label',
    ];

    public function index(Request $request, array $params = []): void
    {
        $settings = Setting::getAllAsMap();

        $view = $this->app->service('view');
        $html = $view->renderAdmin('consent/index', [
            'pageTitle' => __('admin.consent.title'),
            'settings'  => $settings,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
        Response::html($html);
    }

    public function save(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        // consent_enabled is a checkbox – absent from POST when unchecked
        $enabled = $request->input('consent_enabled', '0') === '1' ? '1' : '0';
        Setting::set('consent_enabled', $enabled, 'consent');

        // Checkboxes that follow the same pattern
        $checkboxFields = ['consent_show_logo', 'consent_show_reopen'];

        foreach ($this->consentFields as $key) {
            if ($key === 'consent_enabled') {
                continue; // already handled above
            }

            if (in_array($key, $checkboxFields, true)) {
                $value = $request->input($key, '0') === '1' ? '1' : '0';
            } elseif ($key === 'consent_cookie_days') {
                $value = (string) max(1, (int) $request->input($key, '365'));
            } else {
                $value = trim($request->input($key, ''));
            }

            Setting::set($key, $value, 'consent');
        }

        set_flash('success', 'Cookie-Einstellungen wurden gespeichert.');
        Response::redirect('/admin/consent');
    }
}
