<?php
/**
 * Cart Functionality
 * 
 * Implements the cart options from admin panel:
 * - Ajax Add to Cart
 * - Redirect to Cart After Add
 * - Mini Cart Drawer
 *
 * @package storzen
 * @since   1.0.3
 */

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

/**
 * Get cart option value from admin panel
 *
 * @param string $key Option key
 * @param mixed $default Default value
 * @return mixed
 */
function storzen_get_cart_option($key, $default = false) {
	// Cart settings moved into the "cart" module on the Modules page.
	// Toggle-type settings are stored as booleans there; normalize them
	// to the 1/0 shape the rest of this file already expects.
	if (function_exists('storzen_module_setting')) {
		$value = storzen_module_setting('cart', $key);
		if (null === $value) {
			return $default;
		}
		if (is_bool($value)) {
			return $value ? 1 : 0;
		}
		return $value;
	}
	return $default;
}

// ── 1. Ajax Add to Cart ──────────────────────────────────────────────────────

/**
 * Disable WooCommerce's default AJAX add to cart when our option is disabled
 */
function storzen_control_wc_ajax_cart() {
	// Only disable WooCommerce AJAX if our AJAX cart is explicitly disabled
	if (storzen_get_cart_option('ajax_cart', false) != 1) {
		// Disable WooCommerce's AJAX add to cart on shop pages
		add_filter('woocommerce_loop_add_to_cart_args', 'storzen_disable_wc_ajax_args', 10, 2);
		// Also disable WooCommerce's AJAX add to cart support completely
		add_filter('woocommerce_product_supports', 'storzen_disable_ajax_support', 10, 3);
		// Enqueue script to force standard cart behavior
		add_action('wp_enqueue_scripts', 'storzen_enqueue_force_standard_cart', 999);
	}
}
add_action('init', 'storzen_control_wc_ajax_cart', 5);

/**
 * Enqueue script to force standard (non-AJAX) add to cart
 */
function storzen_enqueue_force_standard_cart() {
	wp_enqueue_script(
		'storzen-force-standard-cart',
		STORZEN_JS . '/force-standard-cart.js',
		array('jquery'),
		STORZEN_VERSION,
		true
	);
}

/**
 * Remove AJAX support from product to disable WooCommerce's AJAX
 */
function storzen_disable_wc_ajax_args($args, $product) {
	// Remove the ajax_add_to_cart class
	if (isset($args['class'])) {
		$args['class'] = str_replace('ajax_add_to_cart', '', $args['class']);
	}
	return $args;
}

/**
 * Disable AJAX add to cart support for products
 */
function storzen_disable_ajax_support($supports, $feature, $product) {
	// Disable ajax_add_to_cart support when our AJAX is disabled
	if ($feature === 'ajax_add_to_cart') {
		return false;
	}
	return $supports;
}

/**
 * Enable AJAX add to cart for all product types on shop pages
 */
function storzen_enable_ajax_add_to_cart() {
	// Check if AJAX cart is explicitly enabled (1 = enabled, 0 or empty = disabled)
	if (storzen_get_cart_option('ajax_cart', false) == 1) {
		add_filter('woocommerce_loop_add_to_cart_link', 'storzen_ajax_add_to_cart_link', 10, 2);
	} else {
		// When our AJAX cart is disabled, also remove AJAX classes from buttons
		add_filter('woocommerce_loop_add_to_cart_link', 'storzen_remove_ajax_add_to_cart_class', 10, 2);
	}
}
add_action('init', 'storzen_enable_ajax_add_to_cart');

/**
 * Remove AJAX class from add to cart buttons when AJAX cart is disabled
 */
function storzen_remove_ajax_add_to_cart_class($html, $product) {
	// Remove ajax_add_to_cart class to prevent WooCommerce's default AJAX behavior
	$html = str_replace('ajax_add_to_cart', '', $html);
	return $html;
}

/**
 * Add AJAX class to add to cart buttons
 */
function storzen_ajax_add_to_cart_link($html, $product) {
	// Double-check the option is enabled
	if (storzen_get_cart_option('ajax_cart', false) != 1) {
		return $html;
	}

	// Add ajax_add_to_cart class for simple products
	if ($product->is_type('simple') && $product->is_purchasable() && $product->is_in_stock()) {
		$html = str_replace('add_to_cart_button', 'add_to_cart_button ajax_add_to_cart', $html);
	}

	return $html;
}

/**
 * Enqueue AJAX add to cart script and styles
 */
function storzen_ajax_cart_script() {
	// Only load AJAX cart scripts if the option is explicitly enabled
	if (storzen_get_cart_option('ajax_cart', false) != 1) {
		return;
	}

	wp_enqueue_style(
		'storzen-ajax-cart',
		STORZEN_CSS . '/ajax-cart.css',
		array('storzen-main'),
		STORZEN_VERSION
	);

	wp_enqueue_script(
		'storzen-ajax-cart',
		STORZEN_JS . '/ajax-cart.js',
		array('jquery'),
		STORZEN_VERSION,
		true
	);

	wp_localize_script(
		'storzen-ajax-cart',
		'storzenCart',
		array(
			'ajaxUrl' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('storzen_cart_nonce'),
			'cartUrl' => wc_get_cart_url(),
			'redirectToCart' => storzen_get_cart_option('cart_redirect', false) == 1,
			'miniCartEnabled' => storzen_get_cart_option('mini_cart_drw', false) == 1,
		)
	);
}
add_action('wp_enqueue_scripts', 'storzen_ajax_cart_script');

// ── 2. Redirect to Cart After Add ───────────────────────────────────────────

/**
 * Handle redirect and mini cart after adding product
 * Works independently of AJAX setting
 */
function storzen_redirect_to_cart_after_add($url) {
	// Get option values
	$redirect_enabled = storzen_get_cart_option('cart_redirect', false) == 1;
	$mini_cart_enabled = storzen_get_cart_option('mini_cart_drw', false) == 1;
	$ajax_enabled = storzen_get_cart_option('ajax_cart', false) == 1;
	
	
	// Priority 1: Redirect to cart (works regardless of AJAX setting)
	if ($redirect_enabled) {
		// Make sure WooCommerce is loaded
		if (function_exists('wc_get_cart_url')) {
			$cart_url = wc_get_cart_url();
			return $cart_url;
		}
		// Fallback to standard cart URL
		return home_url('/cart/');
	}
	
	// Priority 2: Mini cart drawer (only when AJAX is disabled and redirect is not enabled)
	if ($mini_cart_enabled && !$ajax_enabled && !$redirect_enabled) {
		// Add query parameter to trigger drawer opening after page reload
		return add_query_arg('open_mini_cart', '1', $url);
	}
	
	// Default: return original URL
	return $url;
}

// Register the filter - runs on both AJAX and non-AJAX add to cart
add_filter('woocommerce_add_to_cart_redirect', 'storzen_redirect_to_cart_after_add', 99);

// Force redirect using template_redirect hook (runs earlier)
add_action('template_redirect', 'storzen_check_and_redirect_to_cart', 1);
function storzen_check_and_redirect_to_cart() {
	// Check if redirect is enabled
	if (storzen_get_cart_option('cart_redirect', false) != 1) {
		return;
	}
	
	// Check if product was just added to cart (via ?add-to-cart parameter)
	if ( isset( $_GET['add-to-cart'] ) && is_numeric( $_GET['add-to-cart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Standard WooCommerce add-to-cart URL parameter.
		// Check if this is NOT an AJAX request
		$is_ajax = (defined('DOING_AJAX') && DOING_AJAX) || 
		           (function_exists('wp_doing_ajax') && wp_doing_ajax()) ||
		           ( ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && 'xmlhttprequest' === strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- AJAX detection only, not processing form data.
		
		if (!$is_ajax) {
			// Get cart URL
			$cart_url = function_exists('wc_get_cart_url') ? wc_get_cart_url() : home_url('/cart/');
			
			// Redirect immediately before any output
			wp_safe_redirect($cart_url);
			exit;
		}
	}
}

// Backup method: Hook into add_to_cart action
add_action('woocommerce_add_to_cart', 'storzen_force_redirect_after_add', 10, 6);
function storzen_force_redirect_after_add($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
	// Only redirect if setting is enabled
	if (storzen_get_cart_option('cart_redirect', false) == 1) {
		// Check if this is NOT an AJAX request
		$is_ajax = (defined('DOING_AJAX') && DOING_AJAX) || 
		           (function_exists('wp_doing_ajax') && wp_doing_ajax()) ||
		           ( ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && 'xmlhttprequest' === strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- AJAX detection only, not processing form data.
		
		// Only redirect for non-AJAX requests
		if (!$is_ajax && !headers_sent()) {
			// Get cart URL
			$cart_url = function_exists('wc_get_cart_url') ? wc_get_cart_url() : home_url('/cart/');
			
			// Redirect immediately
			wp_safe_redirect($cart_url);
			exit;
		}
	}
}

// Also ensure it works for AJAX add to cart
add_filter('wc_add_to_cart_message_html', 'storzen_suppress_message_if_redirect', 10, 2);
function storzen_suppress_message_if_redirect($message, $products) {
	// If redirect is enabled, we don't need the message since we're redirecting
	if (storzen_get_cart_option('cart_redirect', false) == 1) {
		return '';
	}
	return $message;
}

// Replace "Add to Cart" with "View Cart" button after product is added
add_filter('woocommerce_loop_add_to_cart_link', 'storzen_replace_added_to_cart_button', 999, 2);
function storzen_replace_added_to_cart_button($html, $product) {
	// Check if product is already in cart
	if (WC()->cart && WC()->cart->find_product_in_cart(WC()->cart->generate_cart_id($product->get_id()))) {
		// Replace with View Cart button (icon only, no text)
		$cart_url = function_exists('wc_get_cart_url') ? wc_get_cart_url() : home_url('/cart/');
		
		$html = sprintf(
			'<a href="%s" class="button product_type_simple added_to_cart wc-forward" rel="nofollow" aria-label="View Cart" title="View Cart">%s</a>',
			esc_url($cart_url),
			'<i class="fas fa-cart-shopping" aria-hidden="true"></i>'
		);
	}
	
	return $html;
}

// ── 3. Mini Cart Drawer ──────────────────────────────────────────────────────

/**
 * Add mini cart drawer HTML to footer
 */
function storzen_mini_cart_drawer() {
	if (storzen_get_cart_option('mini_cart_drw', false) != 1) {
		return;
	}

	if (!class_exists('WooCommerce')) {
		return;
	}
	?>
	<div class="szp-mini-cart-overlay"></div>
	<div class="szp-mini-cart-drawer">
		<div class="szp-mini-cart-header">
			<h3><?php esc_html_e('Shopping Cart', 'storzen'); ?></h3>
			<button class="szp-mini-cart-close">
				<i class="fas fa-times"></i>
			</button>
		</div>
		<div class="szp-mini-cart-body">
			<?php woocommerce_mini_cart(); ?>
		</div>
	</div>
	<?php
}
add_action('wp_footer', 'storzen_mini_cart_drawer');

/**
 * Update mini cart fragments
 */
function storzen_mini_cart_fragments($fragments) {
	if (storzen_get_cart_option('mini_cart_drw', false) != 1) {
		return $fragments;
	}

	ob_start();
	woocommerce_mini_cart();
	$mini_cart = ob_get_clean();

	$fragments['.szp-mini-cart-body'] = '<div class="szp-mini-cart-body">' . $mini_cart . '</div>';

	return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'storzen_mini_cart_fragments');

/**
 * Enqueue mini cart drawer styles and scripts
 */
function storzen_mini_cart_assets() {
	if (storzen_get_cart_option('mini_cart_drw', false) != 1) {
		return;
	}

	wp_enqueue_style(
		'storzen-mini-cart',
		STORZEN_CSS . '/mini-cart.css',
		array('storzen-main'),
		STORZEN_VERSION
	);

	wp_enqueue_script(
		'storzen-mini-cart',
		STORZEN_JS . '/mini-cart.js',
		array('jquery'),
		STORZEN_VERSION,
		true
	);

	// Localize script for mini cart
	wp_localize_script(
		'storzen-mini-cart',
		'storzenMiniCart',
		array(
			'ajaxUrl' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('storzen_mini_cart_nonce'),
			'autoOpen' => (storzen_get_cart_option('ajax_cart', false) == 1),
		)
	);
}
add_action('wp_enqueue_scripts', 'storzen_mini_cart_assets');

// NOTE: The Cart Cross Sell module is now registered in the Modules registry
// (key: "cart") and instantiated by Storzen_Modules::load_active_modules().
// Its constructor self-gates the popup on the `xs_enable` setting, so no
// separate loader is needed here.
