<?php

/**
 * WooCommerce Mini Cart Class.
 *
 * @package Kubelio\WooCommerce
 * @since 1.0.0
 */

namespace Kubelio\WooCommerce;

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

/**
 * Mini_Cart Class
 */
class Mini_Cart {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_filter('woocommerce_add_to_cart_fragments', array($this, 'cart_fragments'));

		// Mini-cart quantity update via WC AJAX
		add_action('wc_ajax_update_cart_item', array($this, 'ajax_update_mini_cart_qty'));
	}

	/**
	 * Update cart count badge via AJAX
	 *
	 * @param array $fragments AJAX fragments.
	 * @return array
	 */
	public function cart_fragments($fragments) {
		$count = (WC()->cart) ? WC()->cart->get_cart_contents_count() : 0;
		$fragments['.rt-cart-info__badge'] = '<span class="rt-cart-info__badge"><span class="rt_cart_info_count">' . $count . '</span></span>';
		$fragments['.rt-mini-cart-panel-count'] = '<span class="rt-mini-cart-panel-count rt_mini_cart_panel_count">(' . sprintf(/* translators: %d: number of cart items. */ _n('item: %d', 'items: %d', $count, 'kubelio'), $count) . ')</span>';
		return $fragments;
	}

	/**
	 * Handle AJAX quantity update for mini-cart widget.
	 */
	public function ajax_update_mini_cart_qty() {
		check_ajax_referer('woocommerce-cart', 'nonce');

		$cart_item_key = isset($_POST['cart_item_key']) ? sanitize_text_field(wp_unslash($_POST['cart_item_key'])) : '';
		$quantity      = isset($_POST['quantity']) ? absint($_POST['quantity']) : 1;

		if (! $cart_item_key || ! WC()->cart) {
			wp_send_json_error(array('message' => 'Invalid request'));
		}

		$cart_item = WC()->cart->get_cart_item($cart_item_key);
		if (! $cart_item) {
			wp_send_json_error(array('message' => 'Cart item not found'));
		}

		$old_qty  = $cart_item['quantity'];
		$_product = $cart_item['data'];

		// A quantity of 0 means "remove the item" — don't clamp it back up to the product minimum.
		if ($quantity > 0) {
			$min = $_product->get_min_purchase_quantity();
			$max = $_product->get_max_purchase_quantity();
			if ($quantity < $min) $quantity = $min;
			if ($max > 0 && $quantity > $max) $quantity = $max;
		}

		// WC_Cart::set_quantity() removes the cart item when $quantity is 0.
		WC()->cart->set_quantity($cart_item_key, $quantity, true);

		// Recalculate
		WC()->cart->calculate_totals();

		// Build subtotal HTML for this item
		$item_subtotal = WC()->cart->get_product_subtotal($_product, $quantity);

		// Get mini cart fragments
		ob_start();
		woocommerce_mini_cart();
		$mini_cart = ob_get_clean();

		$fragments = array(
			'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>'
		);
		$fragments = apply_filters('woocommerce_add_to_cart_fragments', $fragments);

		wp_send_json_success(
			array(
				'item_subtotal' => $item_subtotal,
				'old_qty'       => $old_qty,
				'fragments'     => $fragments,
				'cart_hash'     => WC()->cart->get_cart_hash(),
			)
		);
	}
}
