<?php
/**
 * General settings admin page.
 *
 * @package Vanquish\MultipleAddresses\Admin
 */

namespace Vanquish\MultipleAddresses\Admin;

use Vanquish\MultipleAddresses\Com\Html;
use Vanquish\MultipleAddresses\Com\Locale;
use Vanquish\MultipleAddresses\Com\Settings;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Renders the free general settings and fires the `vanmuad_settings_extra`
 * action so premium can inject its own fields, and `vanmuad_settings_saved` so
 * premium can persist them.
 */
class SettingsPage {

	/**
	 * Menu/page slug.
	 */
	const SLUG = 'vanmuad-addresses';

	/**
	 * Whether the settings were just saved.
	 *
	 * @var bool
	 */
	private $saved = false;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * Page styles.
	 *
	 * @param string $hook Current admin page.
	 * @return void
	 */
	public function enqueue( $hook ) {
		if ( false === strpos( (string) $hook, self::SLUG ) ) {
			return;
		}

		wp_enqueue_style(
			'vanmuad-admin',
			VANMUAD_URL . 'assets/css/vanmuad-admin.css',
			array(),
			VANMUAD_VERSION
		);

		// WooCommerce's own enhanced selects (Select2) power the category picker and
		// the AJAX product search. They are not loaded on third-party screens by
		// default, so both the script and its stylesheet are requested here.
		wp_enqueue_style( 'woocommerce_admin_styles' );
		wp_enqueue_script( 'wc-enhanced-select' );

		// WordPress' own colour picker, used by the button-colour setting. It gives
		// a Clear button for free, which a native <input type="color"> cannot do —
		// and clearing is how "use the default" is expressed.
		wp_enqueue_style( 'wp-color-picker' );

		// Drives the colour picker and the repeatable rows premium sections may
		// render (fee ranges). It ships in the free build too — generic UI code
		// that simply finds nothing to do when those controls are not on the page.
		wp_enqueue_script(
			'vanmuad-admin',
			VANMUAD_URL . 'assets/js/vanmuad-admin.js',
			array( 'jquery', 'wp-color-picker' ),
			VANMUAD_VERSION,
			true
		);
	}

	/**
	 * Render the page.
	 *
	 * @return void
	 */
	public function render() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$this->maybe_save();

		$settings = new Settings();
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Multiple Addresses — Settings', 'vanquish-multiple-addresses-for-woocommerce' ); ?></h1>

			<?php if ( $this->saved ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'vanquish-multiple-addresses-for-woocommerce' ); ?></p></div>
			<?php endif; ?>

			<?php
			// Explains the per-language fields; returns '' on a monolingual site.
			// Escaped here rather than trusted to escape itself: the reader of this
			// line should not have to open another class to know the output is safe,
			// and a change over there must not be able to make this line unsafe.
			echo wp_kses_post( Locale::notice() );

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only notice; the reset itself is nonce-checked in ResetSettings::handle().
			if ( isset( $_GET['vanmuad_reset'] ) ) {
				echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings reset to their defaults.', 'vanquish-multiple-addresses-for-woocommerce' ) . '</p></div>';
			}
			?>

			<form method="post">
				<?php wp_nonce_field( 'vanmuad_save_settings', 'vanmuad_settings_nonce' ); ?>

				<div class="card" style="max-width:90%;padding:2px 20px 14px;">
					<h2><?php esc_html_e( 'Address book', 'vanquish-multiple-addresses-for-woocommerce' ); ?></h2>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><?php esc_html_e( 'Show the selector on', 'vanquish-multiple-addresses-for-woocommerce' ); ?></th>
							<td>
								<fieldset class="vanmuad-toggle-stack">
									<?php Html::toggle( 'vanmuad_selector_on_billing', $settings->is_enabled( 'selector_on_billing', true ), __( 'The billing address form', 'vanquish-multiple-addresses-for-woocommerce' ) ); ?>
									<?php Html::toggle( 'vanmuad_selector_on_shipping', $settings->is_enabled( 'selector_on_shipping', true ), __( 'The shipping address form', 'vanquish-multiple-addresses-for-woocommerce' ) ); ?>
								</fieldset>
								<p class="description"><?php esc_html_e( 'Customers keep one address book and can use any saved address for either form. Turn both off to disable the feature entirely.', 'vanquish-multiple-addresses-for-woocommerce' ); ?></p>
							</td>
						</tr>
					</table>
				</div>

				<div class="card" style="max-width:90%;padding:2px 20px 14px;">
					<h2><?php esc_html_e( 'Style', 'vanquish-multiple-addresses-for-woocommerce' ); ?></h2>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><?php esc_html_e( 'Button colour', 'vanquish-multiple-addresses-for-woocommerce' ); ?></th>
							<td>
								<input type="text"
									class="vanmuad-color-field"
									name="vanmuad_accent_color"
									value="<?php echo esc_attr( $settings->get( 'accent_color', '' ) ); ?>"
									data-default-color="<?php echo esc_attr( Settings::DEFAULT_ACCENT ); ?>" />
								<p class="description">
									<?php esc_html_e( 'Colour of the address buttons on the checkout and in the account address book. Leave empty for a neutral grey.', 'vanquish-multiple-addresses-for-woocommerce' ); ?>
								</p>
							</td>
						</tr>
					</table>
				</div>

				<div class="card" style="max-width:90%;padding:2px 20px 14px;">
					<h2><?php esc_html_e( 'Checkout', 'vanquish-multiple-addresses-for-woocommerce' ); ?></h2>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><?php esc_html_e( 'Managing addresses', 'vanquish-multiple-addresses-for-woocommerce' ); ?></th>
							<td>
								<?php Html::toggle( 'vanmuad_checkout_allow_add', $settings->is_enabled( 'checkout_allow_add', true ), __( 'Let customers add and edit addresses during checkout', 'vanquish-multiple-addresses-for-woocommerce' ) ); ?>
								<p class="description"><?php esc_html_e( 'When off, customers can still pick a saved address at checkout but manage the book from their account.', 'vanquish-multiple-addresses-for-woocommerce' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Default selection', 'vanquish-multiple-addresses-for-woocommerce' ); ?></th>
							<td>
								<?php Html::toggle( 'vanmuad_preselect_default_address', $settings->is_enabled( 'preselect_default_address', false ), __( 'Preselect the customer\'s default address instead of the address already in the form', 'vanquish-multiple-addresses-for-woocommerce' ) ); ?>
								<p class="description"><?php esc_html_e( 'When off, the checkout keeps the address WooCommerce already filled in and the customer picks a saved one only if they want to.', 'vanquish-multiple-addresses-for-woocommerce' ); ?></p>
							</td>
						</tr>
					</table>
				</div>

				<?php
				/**
				 * Extension point for premium settings fields.
				 *
				 * @param Settings $settings The settings service.
				 */
				do_action( 'vanmuad_settings_extra', $settings );
				?>

				<?php submit_button(); ?>
			</form>

			<?php
			// Outside the settings form on purpose: it posts to admin-post.php
			// with its own nonce, and nesting forms is invalid HTML.
			ResetSettings::render();
			?>
		</div>
		<?php
	}

	/**
	 * Handle the form submission.
	 *
	 * @return void
	 */
	private function maybe_save() {
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
			return;
		}

		if ( ! isset( $_POST['vanmuad_settings_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['vanmuad_settings_nonce'] ) ), 'vanmuad_save_settings' ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		// sanitize_hex_color() returns '' for anything that is not a valid hex
		// colour, which is also how "use the default" is stored.
		$accent = isset( $_POST['vanmuad_accent_color'] )
			? sanitize_hex_color( sanitize_text_field( wp_unslash( $_POST['vanmuad_accent_color'] ) ) )
			: '';

		( new Settings() )->save(
			array(
				'accent_color'              => (string) $accent,
				'selector_on_billing'       => isset( $_POST['vanmuad_selector_on_billing'] ),
				'selector_on_shipping'      => isset( $_POST['vanmuad_selector_on_shipping'] ),
				'checkout_allow_add'        => isset( $_POST['vanmuad_checkout_allow_add'] ),
				'preselect_default_address' => isset( $_POST['vanmuad_preselect_default_address'] ),
			)
		);

		/**
		 * Settings form submitted and accepted.
		 *
		 * Fired only after the nonce and the capability were verified, so premium
		 * listeners can read $_POST and save their own options.
		 */
		do_action( 'vanmuad_settings_saved' );

		$this->saved = true;
	}
}
