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

use SabaiApps\Directories\Context;

/**
 * AlterCollationTool changes the collation of database tables created by the application.
 */
class AlterCollationTool extends AbstractTool {

	/**
	 * Returns tool information.
	 *
	 * @return array
	 */
	protected function _systemToolInfo() {
		return array(
			'label'       => __( 'Change table collation', 'directories-pro' ),
			'description' => sprintf(
				__( 'Use this tool to change the collation of database tables created by %s.', 'directories-pro' ),
				'Directories'
			),
			'weight'      => 90,
		);
	}

	/**
	 * Returns the settings form for selecting collation.
	 *
	 * @param string       $step
	 * @param array        $values
	 * @param array        $parents
	 * @param Context|null $context
	 * @return array
	 */
	public function systemToolSettingsForm( $step, array $values, array $parents = array(), ?Context $context = null ) {
		return array(
			'collation' => array(
				'#type'          => 'select',
				'#options'       => array(
					'utf8_general_ci'    => 'utf8_general_ci',
					'utf8_unicode_ci'    => 'utf8_unicode_ci',
					'utf8mb4_general_ci' => 'utf8mb4_general_ci',
					'utf8mb4_unicode_ci' => 'utf8mb4_unicode_ci',
				),
				'#default_value' => $this->_application->getPlatform()->getOption( 'system_table_collation' ),
			),
		);
	}

	/**
	 * Runs the collation change task.
	 *
	 * @param string       $task
	 * @param array        $settings
	 * @param int          $iteration
	 * @param int          $total
	 * @param array        $storage
	 * @param array        $logs
	 * @param Context|null $context
	 * @return int
	 */
	public function systemToolRunTask( $task, array $settings, $iteration, $total, array &$storage, array &$logs, ?Context $context = null ) {
		$this->_application->System_Tools_changeCollation( $settings['collation'] );
		$this->_application->getPlatform()->setOption( 'system_table_collation', $settings['collation'] );

		return 1;
	}
}
