<?php
/**
 * Admin Settings.
 *
 * @package Button_Text_Changer_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Admin settings class.
 */
final class WBTC_Admin {

	/**
	 * Singleton instance.
	 *
	 * @var WBTC_Admin|null
	 */
	private static $instance = null;


	/**
	 * Settings manager.
	 *
	 * @var WBTC_Button_Text_Changer|null
	 */
	private $manager = null;


	/**
	 * Get singleton instance.
	 *
	 * @return WBTC_Admin
	 */
	public static function instance() {

		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}


	/**
	 * Constructor.
	 */
	private function __construct() {

		/**
		 * Load settings manager.
		 */
		if ( class_exists( 'WBTC_Button_Text_Changer' ) ) {

			$this->manager =
				WBTC_Button_Text_Changer::instance();
		}


		/**
		 * Admin menu.
		 */
		add_action(
			'admin_menu',
			array(
				$this,
				'register_menu',
			)
		);


		/**
		 * Register settings.
		 */
		add_action(
			'admin_init',
			array(
				$this,
				'register_settings',
			)
		);


		/**
		 * Admin CSS and JS.
		 */
		add_action(
			'admin_enqueue_scripts',
			array(
				$this,
				'enqueue_assets',
			)
		);


		/**
		 * Reset settings.
		 */
		add_action(
			'admin_post_wbtc_reset_settings',
			array(
				$this,
				'reset_settings',
			)
		);
	}


	/**
	 * Register admin menu.
	 *
	 * @return void
	 */
	public function register_menu() {

		add_submenu_page(
			'woocommerce',
			__(
				'Button Text Changer',
				'button-text-changer-for-woocommerce'
			),
			__(
				'Button Text Changer',
				'button-text-changer-for-woocommerce'
			),
			'manage_woocommerce',
			'wbtc-settings',
			array(
				$this,
				'render_settings_page',
			)
		);
	}


	/**
	 * Register plugin settings.
	 *
	 * @return void
	 */
	public function register_settings() {

		register_setting(
			'wbtc_settings_group',
			'wbtc_settings',
			array(
				'type'              => 'array',
				'sanitize_callback' => array(
					$this,
					'sanitize_settings',
				),
				'default'           => array(
					'enabled'     => 'yes',
					'add_to_cart' => '',
					'view_cart'   => '',
					'update_cart' => '',
					'checkout'    => '',
					'place_order' => '',
					'read_more'   => '',
				),
			)
		);
	}


	/**
	 * Sanitize settings.
	 *
	 * @param array $input Settings input.
	 * @return array
	 */
	public function sanitize_settings( $input ) {

		$input = is_array( $input )
			? $input
			: array();


		$settings = array(
			'enabled'     => 'no',
			'add_to_cart' => '',
			'view_cart'   => '',
			'update_cart' => '',
			'checkout'    => '',
			'place_order' => '',
			'read_more'   => '',
		);


		/**
		 * Plugin enabled state.
		 */
		if (
			isset( $input['enabled'] )
			&&
			'yes' === $input['enabled']
		) {

			$settings['enabled'] = 'yes';
		}


		/**
		 * Button text fields.
		 */
		$text_fields = array(
			'add_to_cart',
			'view_cart',
			'update_cart',
			'checkout',
			'place_order',
			'read_more',
		);


		foreach ( $text_fields as $field ) {

			if ( isset( $input[ $field ] ) ) {

				$settings[ $field ] =
					sanitize_text_field(
						$input[ $field ]
					);
			}
		}


		return $settings;
	}


	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook_suffix Current admin page.
	 * @return void
	 */
	public function enqueue_assets( $hook_suffix ) {

		/**
		 * Only load assets on plugin settings page.
		 */
		if (
			'woocommerce_page_wbtc-settings' !==
			$hook_suffix
		) {

			return;
		}


		/**
		 * Admin CSS.
		 */
		$css_file =
			WBTC_PATH .
			'admin/css/admin.css';


		$css_url =
			WBTC_URL .
			'admin/css/admin.css';


		if ( file_exists( $css_file ) ) {

			wp_enqueue_style(
				'wbtc-admin',
				$css_url,
				array(),
				filemtime( $css_file )
			);
		}


		/**
		 * Admin JavaScript.
		 */
		$js_file =
			WBTC_PATH .
			'admin/js/admin.js';


		$js_url =
			WBTC_URL .
			'admin/js/admin.js';


		if ( file_exists( $js_file ) ) {

			wp_enqueue_script(
				'wbtc-admin',
				$js_url,
				array( 'jquery' ),
				filemtime( $js_file ),
				true
			);
		}
	}


	/**
	 * Reset all settings.
	 *
	 * @return void
	 */
	public function reset_settings() {

		/**
		 * Permission check.
		 */
		if (
			! current_user_can(
				'manage_woocommerce'
			)
		) {

			wp_die(
				esc_html__(
					'You do not have permission to reset these settings.',
					'button-text-changer-for-woocommerce'
				)
			);
		}


		/**
		 * Verify nonce.
		 */
		check_admin_referer(
			'wbtc_reset_settings',
			'wbtc_reset_nonce'
		);


		/**
		 * Reset through manager.
		 */
		if ( $this->manager ) {

			$this->manager->reset_settings();

		} else {

			/**
			 * Fallback reset.
			 */
			update_option(
				'wbtc_settings',
				array(
					'enabled'     => 'yes',
					'add_to_cart' => '',
					'view_cart'   => '',
					'update_cart' => '',
					'checkout'    => '',
					'place_order' => '',
					'read_more'   => '',
				)
			);
		}


		/**
		 * Store reset notice temporarily.
		 */
		set_transient(
			'wbtc_reset_notice_' . get_current_user_id(),
			'1',
			30
		);


		/**
		 * Redirect to settings page.
		 */
		$redirect_url = add_query_arg(
			array(
				'page' => 'wbtc-settings',
			),
			admin_url( 'admin.php' )
		);


		wp_safe_redirect(
			$redirect_url
		);

		exit;
	}


	/**
	 * Render settings page.
	 *
	 * @return void
	 */
	public function render_settings_page() {

		/**
		 * Permission check.
		 */
		if (
			! current_user_can(
				'manage_woocommerce'
			)
		) {

			return;
		}


		/**
		 * Get current settings.
		 */
		$settings = $this->manager
			? $this->manager->get_settings()
			: array(
				'enabled'     => 'yes',
				'add_to_cart' => '',
				'view_cart'   => '',
				'update_cart' => '',
				'checkout'    => '',
				'place_order' => '',
				'read_more'   => '',
			);


		/**
		 * Reset success message.
		 */
		$reset_notice = false;


		$notice_key =
			'wbtc_reset_notice_' .
			get_current_user_id();


		if ( '1' === get_transient( $notice_key ) ) {

			$reset_notice = true;

			delete_transient( $notice_key );
		}

		?>

```
	<div class="wrap wbtc-admin-wrap">

		<h1>
			<?php
			esc_html_e(
				'Button Text Changer for WooCommerce',
				'button-text-changer-for-woocommerce'
			);
			?>
		</h1>


		<p class="description">

			<?php
			esc_html_e(
				'Change WooCommerce button labels globally without targeting individual products.',
				'button-text-changer-for-woocommerce'
			);
			?>

		</p>


		<?php if ( $reset_notice ) : ?>

			<div class="notice notice-success is-dismissible">

				<p>

					<?php
					esc_html_e(
						'Button text settings have been reset successfully.',
						'button-text-changer-for-woocommerce'
					);
					?>

				</p>

			</div>

		<?php endif; ?>


		<!--
			========================================
			MAIN SETTINGS FORM
			========================================
		-->

		<form
			id="wbtc-settings-form"
			method="post"
			action="options.php"
		>

			<?php
			settings_fields(
				'wbtc_settings_group'
			);
			?>


			<!-- General Settings -->

			<div class="wbtc-card">

				<h2>

					<?php
					esc_html_e(
						'General',
						'button-text-changer-for-woocommerce'
					);
					?>

				</h2>


				<table class="form-table">

					<tr>

						<th scope="row">

							<label for="wbtc-enabled">

								<?php
								esc_html_e(
									'Enable Plugin',
									'button-text-changer-for-woocommerce'
								);
								?>

							</label>

						</th>


						<td>

							<label>

								<input
									type="checkbox"
									id="wbtc-enabled"
									name="wbtc_settings[enabled]"
									value="yes"
									<?php
									checked(
										$settings['enabled'] ?? 'yes',
										'yes'
									);
									?>
								>


								<?php
								esc_html_e(
									'Enable global WooCommerce button text changes',
									'button-text-changer-for-woocommerce'
								);
								?>

							</label>

						</td>

					</tr>

				</table>

			</div>


			<!-- WooCommerce Button Text -->

			<div class="wbtc-card">

				<h2>

					<?php
					esc_html_e(
						'WooCommerce Button Text',
						'button-text-changer-for-woocommerce'
					);
					?>

				</h2>


				<p class="description">

					<?php
					esc_html_e(
						'Leave a field empty to keep the original WooCommerce text.',
						'button-text-changer-for-woocommerce'
					);
					?>

				</p>


				<table class="form-table">

					<?php

					/**
					 * Add to Cart.
					 */
					$this->render_text_field(
						'add_to_cart',
						__(
							'Add to Cart',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);


					/**
					 * View Cart.
					 */
					$this->render_text_field(
						'view_cart',
						__(
							'View Cart',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);


					/**
					 * Update Cart.
					 */
					$this->render_text_field(
						'update_cart',
						__(
							'Update Cart',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);


					/**
					 * Proceed to Checkout.
					 */
					$this->render_text_field(
						'checkout',
						__(
							'Proceed to Checkout',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);


					/**
					 * Place Order.
					 */
					$this->render_text_field(
						'place_order',
						__(
							'Place Order',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);


					/**
					 * Read More.
					 */
					$this->render_text_field(
						'read_more',
						__(
							'Read More',
							'button-text-changer-for-woocommerce'
						),
						$settings
					);

					?>

				</table>

			</div>

		</form>


		<!--
			========================================
			ACTION BUTTONS
			========================================
		-->

		<div class="wbtc-actions-row">


			<!-- SAVE BUTTON -->

			<button
				type="submit"
				form="wbtc-settings-form"
				class="button button-primary wbtc-save-button"
			>

				<?php
				esc_html_e(
					'Save Button Settings',
					'button-text-changer-for-woocommerce'
				);
				?>

			</button>


			<!-- RESET BUTTON -->

			<form
				method="post"
				action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
				class="wbtc-reset-form"
			>

				<input
					type="hidden"
					name="action"
					value="wbtc_reset_settings"
				>


				<?php
				wp_nonce_field(
					'wbtc_reset_settings',
					'wbtc_reset_nonce'
				);
				?>


				<button
					type="submit"
					class="button button-secondary wbtc-reset-button"
					onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to reset all button text settings?', 'button-text-changer-for-woocommerce' ) ); ?>');"
				>

					<?php
					esc_html_e(
						'Reset Settings',
						'button-text-changer-for-woocommerce'
					);
					?>

				</button>

			</form>

		</div>

	</div>

	<?php
}


/**
 * Render text field.
 *
 * @param string $key      Setting key.
 * @param string $label    Field label.
 * @param array  $settings Current settings.
 * @return void
 */
private function render_text_field(
	$key,
	$label,
	$settings
) {

	$value =
		isset( $settings[ $key ] )
			? $settings[ $key ]
			: '';

	?>

	<tr>

		<th scope="row">

			<label
				for="<?php echo esc_attr( 'wbtc-' . $key ); ?>"
			>

				<?php
				echo esc_html( $label );
				?>

			</label>

		</th>


		<td>

			<input
				type="text"
				class="regular-text wbtc-button-text-field"
				id="<?php echo esc_attr( 'wbtc-' . $key ); ?>"
				name="<?php echo esc_attr( 'wbtc_settings[' . $key . ']' ); ?>"
				value="<?php echo esc_attr( $value ); ?>"
			>


			<p class="description">

				<?php

				switch ( $key ) {

					case 'add_to_cart':

						esc_html_e(
							'Changes the Add to Cart button globally.',
							'button-text-changer-for-woocommerce'
						);

						break;


					case 'view_cart':

						esc_html_e(
							'Changes the View Cart button globally.',
							'button-text-changer-for-woocommerce'
						);

						break;


					case 'update_cart':

						esc_html_e(
							'Changes the Update Cart button on the WooCommerce cart page.',
							'button-text-changer-for-woocommerce'
						);

						break;


					case 'checkout':

						esc_html_e(
							'Changes the Proceed to Checkout button on the cart page.',
							'button-text-changer-for-woocommerce'
						);

						break;


					case 'place_order':

						esc_html_e(
							'Changes the Place Order button on the checkout page.',
							'button-text-changer-for-woocommerce'
						);

						break;


					case 'read_more':

						esc_html_e(
							'Changes the Read More button globally.',
							'button-text-changer-for-woocommerce'
						);

						break;
				}

				?>

			</p>

		</td>

	</tr>

	<?php
}

}
