<?php
/**
 * Square Checkout API settings (merchant + location) admin screen.
 *
 * @see https://developer.squareup.com/docs/checkout-api/checkout-settings
 *
 * @package SHC4WC
 */

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

class SHC4WC_Checkout_Settings {
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ), 11 );
		add_action( 'admin_init', array( $this, 'maybe_save_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public function register_menu() {
		add_submenu_page(
			SHC4WC_Admin_Menu::MENU_SLUG,
			__( 'Checkout Settings', 'payments-connect-square' ),
			__( 'Checkout Settings', 'payments-connect-square' ),
			'manage_options',
			SHC4WC_Admin_Menu::CHECKOUT_SLUG,
			array( $this, 'render_page' )
		);
	}

	public function enqueue_assets( $hook ) {
		if ( 'payments-square-connect_page_' . SHC4WC_Admin_Menu::CHECKOUT_SLUG !== $hook ) {
			return;
		}
		wp_add_inline_style(
			'common',
			'.shc4wc-beta-badge{display:inline-block;margin-left:8px;padding:2px 8px;border-radius:3px;font-size:11px;font-weight:600;line-height:1.6;vertical-align:middle;background:#2271b1;color:#fff;text-transform:uppercase;letter-spacing:.04em;}'
		);
	}

	public function maybe_save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = (string) filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( SHC4WC_Admin_Menu::CHECKOUT_SLUG !== $page ) {
			return;
		}

		if ( ! isset( $_POST['shc4wc_checkout_settings_nonce'] ) ) {
			return;
		}

		check_admin_referer( 'shc4wc_save_checkout_settings', 'shc4wc_checkout_settings_nonce' );

		$tab = isset( $_POST['shc4wc_checkout_tab'] ) ? sanitize_key( wp_unslash( $_POST['shc4wc_checkout_tab'] ) ) : 'merchant';
		$api = new SHC4WC_API( SHC4WC_Plugin::get_settings() );

		if ( 'merchant' === $tab ) {
			$result = $api->update_merchant_checkout_settings(
				array(
					'payment_methods' => array(
						'apple_pay'    => array(
							'enabled' => ! empty( $_POST['shc4wc_apple_pay'] ),
						),
						'google_pay'   => array(
							'enabled' => ! empty( $_POST['shc4wc_google_pay'] ),
						),
						'cash_app' => array(
							'enabled' => ! empty( $_POST['shc4wc_cash_app_pay'] ),
						),
					),
				)
			);
			if ( ! is_wp_error( $result ) ) {
				$api->clear_accepted_payment_methods_cache();
			}
		} else {
			$location_id = $this->get_active_location_id();
			if ( '' === $location_id ) {
				wp_safe_redirect(
					SHC4WC_Admin_Menu::page_url(
						SHC4WC_Admin_Menu::CHECKOUT_SLUG,
						array(
							'tab'    => 'location',
							'status' => 'missing_location',
						)
					)
				);
				exit;
			}

			$percentages = array();
			if ( isset( $_POST['shc4wc_tip_percentages'] ) ) {
				$raw = sanitize_text_field( wp_unslash( $_POST['shc4wc_tip_percentages'] ) );
				foreach ( preg_split( '/\s*,\s*/', $raw ) as $part ) {
					$part = absint( $part );
					if ( $part > 0 && $part <= 100 ) {
						$percentages[] = $part;
					}
				}
			}

			$location_settings = array(
				'customer_notes_enabled' => ! empty( $_POST['shc4wc_customer_notes'] ),
			);

			if ( ! empty( $percentages ) ) {
				$location_settings['tipping'] = array(
					'percentages'            => array_values( array_unique( $percentages ) ),
					'smart_tipping_enabled'  => ! empty( $_POST['shc4wc_smart_tipping'] ),
					'default_percent'        => min( 100, max( 0, absint( $_POST['shc4wc_default_tip_percent'] ?? 0 ) ) ),
				);
			}

			$button_color = isset( $_POST['shc4wc_button_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['shc4wc_button_color'] ) ) : '';
			$button_shape = isset( $_POST['shc4wc_button_shape'] ) ? sanitize_key( wp_unslash( $_POST['shc4wc_button_shape'] ) ) : '';
			$branding     = array();
			if ( $button_color ) {
				$branding['button_color'] = $button_color;
			}
			if ( in_array( $button_shape, array( 'ROUNDED', 'SQUARE', 'PILL' ), true ) ) {
				$branding['button_shape'] = $button_shape;
			}
			if ( ! empty( $branding ) ) {
				$location_settings['branding'] = $branding;
			}

			$policy_title = isset( $_POST['shc4wc_policy_title'] ) ? sanitize_text_field( wp_unslash( $_POST['shc4wc_policy_title'] ) ) : '';
			$policy_body  = isset( $_POST['shc4wc_policy_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['shc4wc_policy_description'] ) ) : '';
			if ( '' !== $policy_title && '' !== $policy_body ) {
				$location_settings['policies'] = array(
					array(
						'title'       => $policy_title,
						'description' => $policy_body,
					),
				);
			}

			$result = $api->update_location_checkout_settings( $location_id, $location_settings );
		}

		$status = is_wp_error( $result ) ? 'error' : 'saved';
		wp_safe_redirect(
			SHC4WC_Admin_Menu::page_url(
				SHC4WC_Admin_Menu::CHECKOUT_SLUG,
				array(
					'tab'    => $tab,
					'status' => $status,
				)
			)
		);
		exit;
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$tab      = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'merchant'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$settings = SHC4WC_Plugin::get_settings();
		$api      = new SHC4WC_API( $settings );
		$connected = SHC4WC_Plugin::has_oauth_connection();
		$is_sandbox = ( ! isset( $settings['environment'] ) || 'live' !== $settings['environment'] );
		$location_id = $this->get_active_location_id();

		$merchant = array();
		$location = array();
		$load_error = '';

		if ( $connected && ! $is_sandbox ) {
			if ( 'merchant' === $tab || 'location' === $tab ) {
				$m = $api->retrieve_merchant_checkout_settings();
				if ( is_wp_error( $m ) ) {
					$load_error = $m->get_error_message();
				} else {
					$merchant = isset( $m['merchant_settings'] ) ? $m['merchant_settings'] : array();
				}
			}
			if ( 'location' === $tab && '' !== $location_id && '' === $load_error ) {
				$l = $api->retrieve_location_checkout_settings( $location_id );
				if ( is_wp_error( $l ) ) {
					$load_error = $l->get_error_message();
				} else {
					$location = isset( $l['location_settings'] ) ? $l['location_settings'] : array();
				}
			}
		}

		$this->render_status_notice();

		?>
		<div class="wrap">
			<h1>
				<?php esc_html_e( 'Checkout Settings', 'payments-connect-square' ); ?>
				<span class="shc4wc-beta-badge"><?php esc_html_e( 'Beta', 'payments-connect-square' ); ?></span>
			</h1>
			<p>
				<?php
				printf(
					/* translators: %s: Square documentation URL. */
					esc_html__( 'Manage Square hosted checkout options for payment links. These settings are stored in Square and apply to checkout pages created by this plugin. %s', 'payments-connect-square' ),
					'<a href="https://developer.squareup.com/docs/checkout-api/checkout-settings" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Square Checkout Settings docs', 'payments-connect-square' ) . '</a>'
				);
				?>
			</p>

			<?php if ( ! $connected ) : ?>
				<div class="notice notice-warning"><p>
					<?php
					printf(
						/* translators: %s: connect settings URL. */
						esc_html__( 'Set up Payments Square Connect first on the %s screen.', 'payments-connect-square' ),
						'<a href="' . esc_url( SHC4WC_Admin_Menu::page_url() ) . '">' . esc_html__( 'Payments Square Connect', 'payments-connect-square' ) . '</a>'
					);
					?>
				</p></div>
			<?php elseif ( $is_sandbox ) : ?>
				<div class="notice notice-info"><p>
					<?php esc_html_e( 'Square Checkout Settings API is not supported in Sandbox. Switch to Live in Connect settings to manage these options.', 'payments-connect-square' ); ?>
				</p></div>
			<?php elseif ( $load_error ) : ?>
				<div class="notice notice-error"><p><?php echo esc_html( $load_error ); ?></p></div>
			<?php endif; ?>

			<nav class="nav-tab-wrapper wp-clearfix">
				<a href="<?php echo esc_url( SHC4WC_Admin_Menu::page_url( SHC4WC_Admin_Menu::CHECKOUT_SLUG, array( 'tab' => 'merchant' ) ) ); ?>" class="nav-tab <?php echo 'merchant' === $tab ? 'nav-tab-active' : ''; ?>">
					<?php esc_html_e( 'Merchant settings', 'payments-connect-square' ); ?>
				</a>
				<a href="<?php echo esc_url( SHC4WC_Admin_Menu::page_url( SHC4WC_Admin_Menu::CHECKOUT_SLUG, array( 'tab' => 'location' ) ) ); ?>" class="nav-tab <?php echo 'location' === $tab ? 'nav-tab-active' : ''; ?>">
					<?php esc_html_e( 'Location settings', 'payments-connect-square' ); ?>
				</a>
			</nav>

			<?php
			if ( 'location' === $tab ) {
				$this->render_location_tab( $location, $location_id, $connected && ! $is_sandbox );
			} else {
				$this->render_merchant_tab( $merchant, $connected && ! $is_sandbox );
			}
			?>
		</div>
		<?php
	}

	private function render_status_notice() {
		$status = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 'saved' === $status ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Checkout settings saved.', 'payments-connect-square' ) . '</p></div>';
		} elseif ( 'error' === $status ) {
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Could not save checkout settings. Check debug log for details.', 'payments-connect-square' ) . '</p></div>';
		} elseif ( 'missing_location' === $status ) {
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Select a Square location on the Connect screen before saving location settings.', 'payments-connect-square' ) . '</p></div>';
		}
	}

	private function render_merchant_tab( array $merchant, $editable ) {
		$methods = isset( $merchant['payment_methods'] ) && is_array( $merchant['payment_methods'] ) ? $merchant['payment_methods'] : array();
		?>
		<form method="post" action="" style="margin-top:1em;max-width:720px;">
			<?php wp_nonce_field( 'shc4wc_save_checkout_settings', 'shc4wc_checkout_settings_nonce' ); ?>
			<input type="hidden" name="shc4wc_checkout_tab" value="merchant" />
			<h2><?php esc_html_e( 'Payment methods', 'payments-connect-square' ); ?></h2>
			<p class="description"><?php esc_html_e( 'Control which wallets and payment methods appear on Square hosted checkout pages.', 'payments-connect-square' ); ?></p>
			<table class="form-table" role="presentation">
				<?php
				$this->render_toggle_row( 'shc4wc_apple_pay', __( 'Apple Pay', 'payments-connect-square' ), $methods, 'apple_pay', $editable );
				$this->render_toggle_row( 'shc4wc_google_pay', __( 'Google Pay', 'payments-connect-square' ), $methods, 'google_pay', $editable );
				$this->render_toggle_row( 'shc4wc_cash_app_pay', __( 'Cash App Pay', 'payments-connect-square' ), $methods, 'cash_app', $editable );
				?>
				<tr>
					<th scope="row"><?php esc_html_e( 'Afterpay / Clearpay', 'payments-connect-square' ); ?></th>
					<td>
						<?php
						$afterpay = ! empty( $methods['afterpay_clearpay']['enabled'] );
						echo esc_html( $afterpay ? __( 'Enabled on Square account', 'payments-connect-square' ) : __( 'Disabled on Square account', 'payments-connect-square' ) );
						?>
						<p class="description"><?php esc_html_e( 'Afterpay and Clearpay can only be enabled or disabled in the Square Dashboard.', 'payments-connect-square' ); ?></p>
					</td>
				</tr>
			</table>
			<?php submit_button( __( 'Save merchant settings', 'payments-connect-square' ), 'primary', 'submit', true, $editable ? array() : array( 'disabled' => 'disabled' ) ); ?>
		</form>
		<?php
	}

	private function render_location_tab( array $location, $location_id, $editable ) {
		$tipping  = isset( $location['tipping'] ) && is_array( $location['tipping'] ) ? $location['tipping'] : array();
		$branding = isset( $location['branding'] ) && is_array( $location['branding'] ) ? $location['branding'] : array();
		$policies = isset( $location['policies'] ) && is_array( $location['policies'] ) ? $location['policies'] : array();
		$policy   = ! empty( $policies[0] ) && is_array( $policies[0] ) ? $policies[0] : array();
		$tips     = ! empty( $tipping['percentages'] ) && is_array( $tipping['percentages'] ) ? implode( ', ', $tipping['percentages'] ) : '10, 15, 20';
		?>
		<form method="post" action="" style="margin-top:1em;max-width:720px;">
			<?php wp_nonce_field( 'shc4wc_save_checkout_settings', 'shc4wc_checkout_settings_nonce' ); ?>
			<input type="hidden" name="shc4wc_checkout_tab" value="location" />
			<p>
				<strong><?php esc_html_e( 'Location:', 'payments-connect-square' ); ?></strong>
				<?php echo $location_id ? esc_html( $location_id ) : esc_html__( 'Not selected — choose one on the Connect screen.', 'payments-connect-square' ); ?>
			</p>

			<h2><?php esc_html_e( 'Checkout experience', 'payments-connect-square' ); ?></h2>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><?php esc_html_e( 'Customer notes', 'payments-connect-square' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="shc4wc_customer_notes" value="1" <?php checked( ! empty( $location['customer_notes_enabled'] ) ); ?> <?php disabled( ! $editable ); ?> />
							<?php esc_html_e( 'Allow buyers to leave notes during checkout', 'payments-connect-square' ); ?>
						</label>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Tipping', 'payments-connect-square' ); ?></h2>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><label for="shc4wc_tip_percentages"><?php esc_html_e( 'Tip percentages', 'payments-connect-square' ); ?></label></th>
					<td>
						<input type="text" class="regular-text" id="shc4wc_tip_percentages" name="shc4wc_tip_percentages" value="<?php echo esc_attr( $tips ); ?>" <?php disabled( ! $editable ); ?> />
						<p class="description"><?php esc_html_e( 'Comma-separated values, e.g. 10, 15, 20', 'payments-connect-square' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="shc4wc_default_tip_percent"><?php esc_html_e( 'Default tip %', 'payments-connect-square' ); ?></label></th>
					<td>
						<input type="number" min="0" max="100" id="shc4wc_default_tip_percent" name="shc4wc_default_tip_percent" value="<?php echo esc_attr( (string) ( $tipping['default_percent'] ?? 15 ) ); ?>" <?php disabled( ! $editable ); ?> />
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Smart tipping', 'payments-connect-square' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="shc4wc_smart_tipping" value="1" <?php checked( ! empty( $tipping['smart_tipping_enabled'] ) ); ?> <?php disabled( ! $editable ); ?> />
							<?php esc_html_e( 'Enable smart tipping presets', 'payments-connect-square' ); ?>
						</label>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Branding', 'payments-connect-square' ); ?></h2>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><label for="shc4wc_button_color"><?php esc_html_e( 'Button color', 'payments-connect-square' ); ?></label></th>
					<td>
						<input type="color" id="shc4wc_button_color" name="shc4wc_button_color" value="<?php echo esc_attr( $branding['button_color'] ?? '#006aff' ); ?>" <?php disabled( ! $editable ); ?> />
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="shc4wc_button_shape"><?php esc_html_e( 'Button shape', 'payments-connect-square' ); ?></label></th>
					<td>
						<select id="shc4wc_button_shape" name="shc4wc_button_shape" <?php disabled( ! $editable ); ?>>
							<?php
							$shape = $branding['button_shape'] ?? 'ROUNDED';
							foreach ( array(
								'ROUNDED' => __( 'Rounded', 'payments-connect-square' ),
								'PILL'    => __( 'Pill', 'payments-connect-square' ),
								'SQUARE'  => __( 'Square', 'payments-connect-square' ),
							) as $value => $label ) {
								printf(
									'<option value="%1$s" %2$s>%3$s</option>',
									esc_attr( $value ),
									selected( $shape, $value, false ),
									esc_html( $label )
								);
							}
							?>
						</select>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Policy', 'payments-connect-square' ); ?></h2>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><label for="shc4wc_policy_title"><?php esc_html_e( 'Policy title', 'payments-connect-square' ); ?></label></th>
					<td><input type="text" class="regular-text" id="shc4wc_policy_title" name="shc4wc_policy_title" value="<?php echo esc_attr( $policy['title'] ?? '' ); ?>" <?php disabled( ! $editable ); ?> /></td>
				</tr>
				<tr>
					<th scope="row"><label for="shc4wc_policy_description"><?php esc_html_e( 'Policy description', 'payments-connect-square' ); ?></label></th>
					<td><textarea class="large-text" rows="4" id="shc4wc_policy_description" name="shc4wc_policy_description" <?php disabled( ! $editable ); ?>><?php echo esc_textarea( $policy['description'] ?? '' ); ?></textarea></td>
				</tr>
			</table>

			<?php submit_button( __( 'Save location settings', 'payments-connect-square' ), 'primary', 'submit', true, $editable ? array() : array( 'disabled' => 'disabled' ) ); ?>
		</form>
		<?php
	}

	private function render_toggle_row( $field_id, $label, array $methods, $method_key, $editable ) {
		$enabled = ! empty( $methods[ $method_key ]['enabled'] );
		if ( ! $enabled && 'cash_app' === $method_key && ! empty( $methods['cash_app_pay']['enabled'] ) ) {
			$enabled = true;
		}
		echo '<tr><th scope="row">' . esc_html( $label ) . '</th><td>';
		printf(
			'<label><input type="checkbox" name="%1$s" id="%1$s" value="1" %2$s %3$s /> %4$s</label>',
			esc_attr( $field_id ),
			checked( $enabled, true, false ),
			$editable ? '' : 'disabled="disabled"',
			esc_html__( 'Enabled', 'payments-connect-square' )
		);
		echo '</td></tr>';
	}

	private function get_active_location_id() {
		$settings = SHC4WC_Plugin::get_settings();
		return ! empty( $settings['location_id'] ) ? sanitize_text_field( (string) $settings['location_id'] ) : '';
	}
}
