<?php
namespace Fabrica\Dashboard;

if (!defined('WPINC')) { die(); }

abstract class SettingsCommon {
	public static function init() {
		add_action('admin_menu', array(Settings::class, 'registerSection'));
		add_action('admin_init', array(Settings::class, 'registerSettings'), 20);
	}

	// Register the settings page
	public static function registerSection() {
		add_options_page(
			'Fabrica Dashboard Settings',
			'Fabrica Dashboard',
			'manage_options',
			'fd-settings',
			array(Settings::class, 'display')
		);
	}

	public abstract static function displayAlert();

	// Render the page
	public static function display() {
		?><div class="wrap">
			<h1><?php esc_html_e("Fabrica Dashboard Settings", Base::$textDomain); ?></h1><?php static::displayAlert(); ?>
			<form method="post" action="options.php"><?php
				settings_fields('fd-settings');
				do_settings_sections('fd-settings');
				submit_button();
			?></form>
		</div><?php
	}

	// Register custom settings
	public static function registerSettings() {
		register_setting(
			'fd-settings', // Option group
			'fd-settings', // Option name
			array(Settings::class, 'sanitize') // Sanitize
		);

		add_settings_section(
			'general', // ID
			__("General", Base::$textDomain), // Title
			array(Settings::class, 'displayGeneralHeader'), // Callback
			'fd-settings' // Page
		);

		add_settings_field(
			'enable_default_boxes', // ID
			__("WordPress Dashboard boxes", Base::$textDomain), // Title
			array(Settings::class, 'enableDefaultBoxesCallback'), // Callback
			'fd-settings', // Page
			'general' // Section
		);
	}

	// Sanitize each setting field as needed
	public static function sanitize($input) {
		$sanitized = array();
		if (isset($input['enable_default_boxes']) && $input['enable_default_boxes'] === "1") {
			$sanitized['enable_default_boxes'] = "1";
		}
		return $sanitized;
	}

	// General header
	public static function displayGeneralHeader() {

	}

	public static function enableDefaultBoxesCallback() {
		$checked = (array_key_exists('enable_default_boxes', Base::$settings) && Base::$settings['enable_default_boxes'] === '1') ? ' checked' : '';
		?><fieldset><label for="fd-settings[enable_default_boxes]"><input type="checkbox" id="enable_default_boxes" name="fd-settings[enable_default_boxes]" value="1"<?php echo esc_attr($checked); ?>>
		<?php esc_html_e("Re-enable the standard 'Welcome', 'At a Glance', 'Activity', 'Quick Draft' and 'WordPress News' widgets.", Base::$textDomain); ?></label>
		<p class="description"><?php esc_html_e("Fabrica Dashboard hides these boxes by default.", Base::$textDomain); ?></p></fieldset><?php
	}
}
