<?php
namespace DevOwl\RealCookieBanner\lite\settings;

use DevOwl\RealCookieBanner\settings\General as SettingsGeneral;
use MatthiasWeb\Utils\Utils;

// @codeCoverageIgnoreStart
defined('ABSPATH') or die('No script kiddies please!'); // Avoid direct file request
// @codeCoverageIgnoreEnd

trait General {
    // Documented in IOverrideGeneral
    public function overrideEnableOptionsAutoload() {
        Utils::enableOptionAutoload(SettingsGeneral::SETTING_HIDE_PAGE_IDS, SettingsGeneral::DEFAULT_HIDE_PAGE_IDS);
        Utils::enableOptionAutoload(
            SettingsGeneral::SETTING_SET_COOKIES_VIA_MANAGER,
            SettingsGeneral::DEFAULT_SET_COOKIES_VIA_MANAGER
        );
    }

    // Documented in IOverrideMultisite
    public function overrideRegister() {
        // WP < 5.3 does not support array types yet, so we store the page IDs as a CSV string.
        register_setting(SettingsGeneral::OPTION_GROUP, SettingsGeneral::SETTING_HIDE_PAGE_IDS, [
            'type' => 'string',
            'show_in_rest' => true,
            'sanitize_callback' => function ($value) {
                return SettingsGeneral::sanitize_delimited_list($value, ',', function ($id) {
                    $id = absint($id);
                    return $id > 0 ? $id : '';
                });
            },
        ]);

        register_setting(SettingsGeneral::OPTION_GROUP, SettingsGeneral::SETTING_SET_COOKIES_VIA_MANAGER, [
            'type' => 'string',
            'show_in_rest' => true,
            'sanitize_callback' => [SettingsGeneral::class, 'sanitize_set_cookies_via_manager'],
        ]);
    }

    // Documented in AbstractGeneral
    public function getAdditionalPageHideIds() {
        $ids = get_option(SettingsGeneral::SETTING_HIDE_PAGE_IDS);
        if (empty($ids)) {
            return [];
        }
        return array_map('absint', explode(',', $ids));
    }

    // Documented in AbstractGeneral
    public function getSetCookiesViaManager() {
        return get_option(SettingsGeneral::SETTING_SET_COOKIES_VIA_MANAGER);
    }
}
