<?php
/**
 * Empty Cart Behavior Settings Validation
 *
 * @package     EDD\Admin\Settings
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.5.0
 */

namespace EDD\Pro\Admin\Settings;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

use EDD\Admin\Settings\EmptyCartBehavior as LiteEmptyCartBehavior;

/**
 * Empty Cart Behavior Settings Validation class.
 *
 * @since 3.5.0
 */
class EmptyCartBehavior extends LiteEmptyCartBehavior {
	/**
	 * Validate empty cart behavior settings.
	 *
	 * @since 3.5.0
	 * @param string $value The value to validate.
	 * @return string The validated value.
	 */
	public static function validate_empty_cart_behavior( $value ) {
		// Allowed behaviors are 'message' and 'redirect_page' or 'redirect_url'.
		$allowed_behaviors = array( 'message', 'redirect_page', 'redirect_url' );
		if ( ! in_array( $value, $allowed_behaviors, true ) ) {
			$value = 'message';
		}

		return $value;
	}

	/**
	 * Validate empty cart redirect page.
	 *
	 * @since 3.5.0
	 * @param string $value The value to validate.
	 * @return string The validated value.
	 */
	public static function validate_empty_cart_redirect_page( $value ) {
		if ( empty( $value ) || ! is_numeric( $value ) ) {
			add_settings_error(
				'edd-notices',
				'edd-empty-cart-redirect-page-not-numeric',
				__( 'Please provide the ID of a published page for the redirect target.', 'easy-digital-downloads' ),
				'error'
			);
			return 0;
		}

		$page_id = absint( $value );
		$page    = get_post( $page_id );

		if ( ! $page || 'page' !== $page->post_type || 'publish' !== $page->post_status ) {
			add_settings_error(
				'edd-notices',
				'edd-empty-cart-redirect-page',
				__( 'The selected redirect page is not valid. Please select a valid published page.', 'easy-digital-downloads' ),
				'error'
			);
			return 0;
		}

		// Check to see if this page has the checkout block or shortcode...or else we end up in a loop.
		if ( has_block( 'edd/checkout', $page_id ) || has_shortcode( $page->post_content, 'download_checkout' ) ) {
			add_settings_error(
				'edd-notices',
				'edd-empty-cart-redirect-page',
				__( 'The selected redirect page has the checkout block or shortcode. Please select a different page.', 'easy-digital-downloads' ),
				'error'
			);

			return 0;
		}

		return $value;
	}

	/**
	 * Validate empty cart redirect URL.
	 *
	 * @since 3.5.0
	 * @param string $value The value to validate.
	 * @return string The validated value.
	 */
	public static function validate_empty_cart_redirect_url( $value ) {
		if ( empty( $value ) || ! is_string( $value ) ) {
			return '';
		}

		// URLs should not have any spaces in them.
		$value = trim( str_replace( ' ', '', $value ) );

		// Validate the URL.
		if ( ! filter_var( $value, FILTER_VALIDATE_URL ) ) {
			// Because we are using a URL text field, we shouldn't get here, but just in case.
			add_settings_error(
				'edd-notices',
				'edd-empty-cart-redirect-url',
				__( 'The provided redirect URL is not valid. Please enter a valid URL.', 'easy-digital-downloads' ),
				'error'
			);
		}

		// Normalize the $value and compare it to the store's checkout.
		$checkout_url = untrailingslashit( edd_get_checkout_uri() );
		if ( strpos( untrailingslashit( $value ), $checkout_url ) !== false ) {
			add_settings_error(
				'edd-notices',
				'edd-empty-cart-redirect-url',
				__( 'You cannot set the redirect URL to the checkout page. Please enter a different URL.', 'easy-digital-downloads' ),
				'error'
			);

			$value = '';
		}

		return $value;
	}

	/**
	 * Get the empty cart behavior setting.
	 *
	 * @since 3.5.0
	 * @return array The empty cart behavior setting.
	 */
	public static function get_empty_cart_behavior_setting() {
		$options = array(
			'message'       => self::get_behavior_option_label( 'message' ),
			'redirect_page' => self::get_behavior_option_label( 'redirect_page' ),
			'redirect_url'  => self::get_behavior_option_label( 'redirect_url' ),
		);

		$description = self::get_behavior_setting_description();
		return self::build_empty_cart_behavior_setting( $options, $description );
	}

	/**
	 * Get the empty cart redirect page setting.
	 *
	 * @since 3.5.0
	 * @return array The empty cart redirect page setting.
	 */
	public static function get_empty_cart_redirect_page_setting() {
		// Get current behavior to determine initial visibility.
		$current_behavior = edd_get_option( 'empty_cart_behavior', 'message' );
		$class            = '';

		if ( 'redirect_page' !== $current_behavior ) {
			$class = 'edd-hidden';
		}

		$pages = edd_get_pages( false, array( edd_get_option( 'purchase_page', 0 ) ) );

		// Run through array_filter with the ARRAY_FILTER_USE_KEY flag to remove empty keys.
		$pages = array_filter(
			$pages,
			function( $key ) {
				return ! empty( $key );
			},
			ARRAY_FILTER_USE_KEY
		);

		return array(
			'id'               => 'empty_cart_redirect_page',
			'name'             => __( 'Redirect Page', 'easy-digital-downloads' ),
			'desc'             => __( 'Select the page to redirect to when the cart is empty.', 'easy-digital-downloads' ),
			'type'             => 'select',
			'options'          => $pages,
			'std'              => edd_get_option( 'products_page', 0 ),
			'chosen'           => true,
			'show_option_none' => false,
			'show_option_all'  => false,
			'class'            => $class,
			'placeholder'      => __( 'Select a page', 'easy-digital-downloads' ),
		);
	}

	/**
	 * Get the empty cart redirect URL setting.
	 *
	 * @since 3.5.0
	 * @return array The empty cart redirect URL setting.
	 */
	public static function get_empty_cart_redirect_url_setting() {
		// Get current behavior to determine initial visibility.
		$current_behavior = edd_get_option( 'empty_cart_behavior', 'message' );
		$class            = '';

		if ( 'redirect_url' !== $current_behavior ) {
			$class = 'edd-hidden';
		}

		// If the current setting host is different than the current site, add a tooltip as a warning.
		$redirect_host = parse_url( edd_get_option( 'empty_cart_redirect_url', '' ), PHP_URL_HOST );
		$site_host     = parse_url( home_url(), PHP_URL_HOST );

		$desc = __( 'Enter the URL to redirect to when the cart is empty. Include http:// or https://.', 'easy-digital-downloads' );

		if ( ! empty( $redirect_host ) && $redirect_host !== $site_host ) {
			$desc .= '<div class="notice notice-warning edd-notice inline"><p>';
			$desc .= '<strong>' . __( 'External URL Detected', 'easy-digital-downloads' ) . '</strong><br />';
			$desc .= sprintf(
				/* translators: 1: Host of the redirect URL, 2: Host of the current site */
				__( 'The host %1$s is not the same as your site %2$s. If this is intentional, you can ignore this warning, otherwise, please verify the URL and save your changes.', 'easy-digital-downloads' ),
				'<strong>' . $redirect_host . '</strong>',
				'<strong>' . $site_host . '</strong>'
			);
			$desc .= '</p></div>';
		}

		return array(
			'id'          => 'empty_cart_redirect_url',
			'name'        => __( 'Redirect URL', 'easy-digital-downloads' ),
			'desc'        => $desc,
			'type'        => 'text',
			'subtype'     => 'url',
			'size'        => 'regular',
			'std'         => '',
			'class'       => $class,
			'placeholder' => 'https://',
		);
	}

	/**
	 * Get the description for the empty cart behavior setting.
	 *
	 * @since 3.5.0
	 * @return string The description for the setting.
	 */
	protected static function get_behavior_setting_description() {
		return __( 'Choose what should happen when a customer visits the checkout page with an empty cart.', 'easy-digital-downloads' );
	}
}
