<?php
namespace SabaiApps\Directories\Component\System\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Form\Form;
use SabaiApps\Directories\Exception;

/**
 * SettingsFormHelper provides methods to build settings forms for system components.
 */
class SettingsFormHelper {

	/**
	 * Adds system-related settings fields to the form for a component.
	 *
	 * @param Application $application
	 * @param string      $name Component name.
	 * @param array       $settings Current settings.
	 * @param array       $form Reference to the form array.
	 */
	public function help( Application $application, $name, $settings, array &$form ) {
		$form['fields'][ $name . '_uninstall' ] = array(
			'#tab'                  => 'System',
			'#weight'               => 11,
			'#component'            => $name,
			'#title'                => __( 'Uninstall Settings', 'directories-pro' ),
			'uninstall_remove_data' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Remove data', 'directories-pro' ),
				'#description'   => __( 'Check this option to completely remove all data when the plugin is deleted.', 'directories-pro' ),
				'#default_value' => ! empty( $settings['uninstall_remove_data'] ),
				'#horizontal'    => true,
			),
		);
		$form['fields'][ $name . '_log' ]       = array(
			'#tab'              => 'System',
			'#weight'           => 10,
			'#component'        => $name,
			'#title'            => __( 'Log Settings', 'directories-pro' ),
			'log_debug'         => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Enable debug log', 'directories-pro' ),
				'#default_value' => ! empty( $settings['log_debug'] ) || $application->getPlatform()->isDebugEnabled(),
				'#horizontal'    => true,
				'#description'   => __( 'Enable standalone debug logging for troubleshooting. Warning: May slow down your site. Use temporarily.', 'directories-pro' ),
			),
			'disable_error_log' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Disable error log', 'directories-pro' ),
				'#default_value' => ! empty( $settings['disable_error_log'] ),
				'#horizontal'    => true,
			),
			'log_dir'           => array(
				'#type'             => 'textfield',
				'#title'            => __( 'Log file location', 'directories-pro' ),
				'#default_value'    => isset( $settings['log_dir'] ) ? $settings['log_dir'] : null,
				'#placeholder'      => ( $dir = $application->getPlatform()->getLogDir() ) ? $dir : $application->getComponent( 'System' )->getVarDir( 'logs' ),
				'#description'      => __( 'Enter the full path to a directory writeable by the server.', 'directories-pro' ),
				'#horizontal'       => true,
				'#element_validate' => array(
					function ( Form $form, &$value, $element ) {
						if ( ! strlen( $value = rtrim( trim( $value ), '/' ) ) ) {
							return;
						}
						if ( ! is_dir( $value ) ) {
							$form->setError( __( 'The directory specified is not a valid directory.', 'directories-pro' ), $element );
						} elseif ( ! is_writable( $value ) ) {
							$form->setError( __( 'The directory specified is not writeable by the server.', 'directories-pro' ), $element );
						}
					},
				),
			),
		);
		$form['fields'][ $name . '_scheduled_action' ]                      = array(
			'#tab'       => 'System',
			'#weight'    => 11,
			'#component' => $name,
			'#title'     => __( 'Scheduled Action Settings', 'directories-pro' ),
		);
		$form['fields'][ $name . '_scheduled_action' ]['scheduled_actions'] = array(
			'#horizontal' => true,
		) + $application->System_ScheduledActions_settingsForm( $settings['scheduled_actions'] ?? null, array( $name . '_scheduled_action', 'scheduled_actions' ) );
		if ( $application->getPlatform()->getLanguages() ) {
			$form['fields'][ $name . '_translations' ] = array(
				'#tab'         => 'System',
				'#weight'      => 9,
				'#component'   => $name,
				'#title'       => __( 'Translation Settings', 'directories-pro' ),
				'auto_reg_str' => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Auto register strings for translation', 'directories-pro' ),
					'#description'   => __( 'Check this option to automatically register strings while pages are rendered. This feature may slow down your site significantly and is only intended for sites that are in development.', 'directories-pro' ),
					'#default_value' => ! empty( $settings['auto_reg_str'] ),
					'#horizontal'    => true,
				),
			);
		}
		$form['tabs'][ $name . '_appearance' ]   = array(
			'#title'  => __( 'Appearance', 'directories-pro' ),
			'#weight' => 80,
		);
		$default_colors                          = array(
			'primary'   => array(
				'label' => __( 'Primary color', 'directories-pro' ),
				'value' => '#467FCF',
			),
			'secondary' => array(
				'label' => __( 'Secondary color', 'directories-pro' ),
				'value' => '#868E96',
			),
			'light'     => array(
				'label' => __( 'Light color', 'directories-pro' ),
				'value' => '#F8F9FA',
			),
			'dark'      => array(
				'label' => __( 'Dark color', 'directories-pro' ),
				'value' => '#212529',
			),
		);
		$form['fields'][ $name . '_appearance' ] = array(
			'#tab'       => $name . '_appearance',
			'#weight'    => 9,
			'#component' => $name,
			'#submit'    => array(
				9 => array( // weight
					function ( Form $form ) use ( $application, $name, $settings ) {
						$value = $form->getValue( $name . '_appearance' );
						try {
							$application->System_CustomCss_generateFile( $value, $settings );
						} catch ( Exception\IException $e ) {
							$form->setError( $e->getMessage() );
						}
					},
				),
			),
			'color'      => array(
				'#weight'           => 10,
				'#title'            => __( 'Color Settings', 'directories-pro' ),
				'#description'      => __( 'Select a color for each type, or leave it blank to use the default color.', 'directories-pro' ),
				'#element_validate' => array(
					function ( Form $form, &$value, $element ) use ( $default_colors ) {
						foreach ( array_keys( $default_colors ) as $color_name ) {
							if ( isset( $value[ $color_name ] )
								&& empty( $value[ $color_name ] )
							) {
								$value[ $color_name ] = null;
							}
						}
						if ( empty( $value ) ) {
							$value = null;
						}
					},
				),
			),
			'css'        => array(
				'#weight'    => 50,
				'#title'     => __( 'CSS Settings', 'directories-pro' ),
				'custom_css' => array(
					'#title'         => __( 'Custom CSS', 'directories-pro' ),
					'#type'          => 'editor',
					'#language'      => 'css',
					'#horizontal'    => true,
					'#default_value' => isset( $settings['css']['custom_css'] ) ? $settings['css']['custom_css'] : null,
				),
			),
			'effect'     => array(
				'#weight'        => 80,
				'#title'         => __( 'Scroll Effect Settings', 'directories-pro' ),
				'scroll_disable' => array(
					'#title'            => __( 'Disable scroll effect', 'directories-pro' ),
					'#type'             => 'checkbox',
					'#default_value'    => (bool) $application->getPlatform()->getOption( 'system_effect_scroll_disable' ),
					'#horizontal'       => true,
					'#element_validate' => array(
						function ( Form $form, &$value, $element ) use ( $application ) {
										$application->getPlatform()->setOption( 'system_effect_scroll_disable', (bool) $value );
										$value = null;
						},
					),
				),
				'scroll_offset'  => array(
					'#title'            => __( 'Scroll offset in pixels', 'directories-pro' ),
					'#type'             => 'slider',
					'#default_value'    => ( $offset = $application->getPlatform()->getOption( 'system_effect_scroll_offset' ) ) ? $offset : 0,
					'#min_value'        => 0,
					'#max_value'        => 500,
					'#min_text'         => __( 'Auto', 'directories-pro' ),
					'#integer'          => true,
					'#horizontal'       => true,
					'#field_suffix'     => 'px',
					'#element_validate' => array(
						function ( Form $form, &$value, $element ) use ( $application ) {
									$application->getPlatform()->setOption( 'system_effect_scroll_offset', (int) $value );
									$value = null;
						},
					),
				),
			),
		);
		foreach ( $default_colors as $color_name => $color_info ) {
			$form['fields'][ $name . '_appearance' ]['color'][ $color_name ] = array(
				'#type'                  => 'colorpicker',
				'#title'                 => $color_info['label'],
				'#default_value'         => isset( $settings['color'][ $color_name ] ) ? $settings['color'][ $color_name ] : null,
				'#attributes'            => array( 'data-custom-colors' => $color_info['value'] ),
				'#description'           => sprintf(
					$application->H( __( 'Default color: %s' ) ),
					'<span class="' . DRTS_BS_PREFIX . 'user-select-all ' . DRTS_BS_PREFIX . 'px-1" style="display:inline-block;background-color:' . $color_info['value'] . ';' . ( $color_name === 'dark' ? 'color:white;' : '' ) . '">' . $color_info['value'] . '</span>'
				),
				'#description_no_escape' => true,
				'#horizontal'            => true,
			);
		}
	}
}
