<?php
/**
 * Cart Shortcode
 *
 * Used on the cart page, the cart shortcode displays the cart contents and interface for coupon codes and other cart bits and pieces.
 *
 * @package Kkart\Shortcodes\Cart
 * @version 2.3.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Shortcode cart class.
 */
class KKART_Shortcode_Cart {

	/**
	 * Calculate shipping for the cart.
	 *
	 * @throws Exception When some data is invalid.
	 */
	public static function calculate_shipping() {
		try {
			KKART()->shipping()->reset_shipping();

			$address = array();

			$address['country']  = isset( $_POST['calc_shipping_country'] ) ? kkart_clean( wp_unslash( $_POST['calc_shipping_country'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
			$address['state']    = isset( $_POST['calc_shipping_state'] ) ? kkart_clean( wp_unslash( $_POST['calc_shipping_state'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
			$address['postcode'] = isset( $_POST['calc_shipping_postcode'] ) ? kkart_clean( wp_unslash( $_POST['calc_shipping_postcode'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
			$address['city']     = isset( $_POST['calc_shipping_city'] ) ? kkart_clean( wp_unslash( $_POST['calc_shipping_city'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.

			$address = apply_filters( 'kkart_cart_calculate_shipping_address', $address );

			if ( $address['postcode'] && ! KKART_Validation::is_postcode( $address['postcode'], $address['country'] ) ) {
				throw new Exception( __( 'Please enter a valid postcode / ZIP.', 'kkart' ) );
			} elseif ( $address['postcode'] ) {
				$address['postcode'] = kkart_format_postcode( $address['postcode'], $address['country'] );
			}

			if ( $address['country'] ) {
				if ( ! KKART()->customer->get_billing_first_name() ) {
					KKART()->customer->set_billing_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
				}
				KKART()->customer->set_shipping_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
			} else {
				KKART()->customer->set_billing_address_to_base();
				KKART()->customer->set_shipping_address_to_base();
			}

			KKART()->customer->set_calculated_shipping( true );
			KKART()->customer->save();

			kkart_add_notice( __( 'Shipping costs updated.', 'kkart' ), 'notice' );

			do_action( 'kkart_calculated_shipping' );

		} catch ( Exception $e ) {
			if ( ! empty( $e ) ) {
				kkart_add_notice( $e->getMessage(), 'error' );
			}
		}
	}

	/**
	 * Output the cart shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 */
	public static function output( $atts ) {
		if ( ! apply_filters( 'kkart_output_cart_shortcode_content', true ) ) {
			return;
		}

		// Constants.
		kkart_maybe_define_constant( 'KKART_CART', true );

		$atts        = shortcode_atts( array(), $atts, 'kkart_cart' );
		$nonce_value = kkart_get_var( $_REQUEST['kkart-shipping-calculator-nonce'], kkart_get_var( $_REQUEST['_wpnonce'], '' ) ); // @codingStandardsIgnoreLine.

		// Update Shipping. Nonce check uses new value and old value (kkart-cart). @todo remove in 4.0.
		if ( ! empty( $_POST['calc_shipping'] ) && ( wp_verify_nonce( $nonce_value, 'kkart-shipping-calculator' ) || wp_verify_nonce( $nonce_value, 'kkart-cart' ) ) ) { // WPCS: input var ok.
			self::calculate_shipping();

			// Also calc totals before we check items so subtotals etc are up to date.
			KKART()->cart->calculate_totals();
		}

		// Check cart items are valid.
		do_action( 'kkart_check_cart_items' );

		// Calc totals.
		KKART()->cart->calculate_totals();

		if ( KKART()->cart->is_empty() ) {do_action( 'kkart_cart_is_empty' );

			if ( kkart_get_page_id( 'shop' ) > 0 ) : ?>
				<p class="return-to-shop">
					<a class="button kkart-backward" href="<?php echo esc_url( apply_filters( 'kkart_return_to_shop_redirect', kkart_get_page_permalink( 'shop' ) ) ); ?>">
						<?php
							echo esc_html( apply_filters( 'kkart_return_to_shop_text', __( 'Return to shop', 'kkart' ) ) );
						?>
					</a>
				</p>
			<?php endif;
		} else {
			
			do_action( 'kkart_before_cart' ); ?>

			<form class="kkart-cart-form" action="<?php echo esc_url( kkart_get_cart_url() ); ?>" method="post">
				<?php do_action( 'kkart_before_cart_table' ); ?>

				<table class="shop_table shop_table_responsive cart kkart-cart-form__contents" cellspacing="0">
					<thead>
						<tr>
							<th class="product-remove">&nbsp;</th>
							<th class="product-thumbnail">&nbsp;</th>
							<th class="product-name"><?php esc_html_e( 'Product', 'kkart' ); ?></th>
							<th class="product-price"><?php esc_html_e( 'Price', 'kkart' ); ?></th>
							<th class="product-quantity"><?php esc_html_e( 'Quantity', 'kkart' ); ?></th>
							<th class="product-subtotal"><?php esc_html_e( 'Subtotal', 'kkart' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php do_action( 'kkart_before_cart_contents' ); ?>

						<?php
						foreach ( KKART()->cart->get_cart() as $cart_item_key => $cart_item ) {
							$_product   = apply_filters( 'kkart_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
							$product_id = apply_filters( 'kkart_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

							if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'kkart_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
								$product_permalink = apply_filters( 'kkart_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
								?>
								<tr class="kkart-cart-form__cart-item <?php echo esc_attr( apply_filters( 'kkart_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">

									<td class="product-remove">
										<?php
											echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
												'kkart_cart_item_remove_link',
												sprintf(
													'<a href="%s" class="remove" aria-label="%s" data-product_id="%s" data-product_sku="%s">&times;</a>',
													esc_url( kkart_get_cart_remove_url( $cart_item_key ) ),
													esc_html__( 'Remove this item', 'kkart' ),
													esc_attr( $product_id ),
													esc_attr( $_product->get_sku() )
												),
												$cart_item_key
											);
										?>
									</td>

									<td class="product-thumbnail">
									<?php
									$thumbnail = apply_filters( 'kkart_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

									if ( ! $product_permalink ) {
										echo $thumbnail; // PHPCS: XSS ok.
									} else {
										printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
									}
									?>
									</td>

									<td class="product-name" data-title="<?php esc_attr_e( 'Product', 'kkart' ); ?>">
									<?php
									if ( ! $product_permalink ) {
										echo wp_kses_post( apply_filters( 'kkart_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . '&nbsp;' );
									} else {
										echo wp_kses_post( apply_filters( 'kkart_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key ) );
									}

									do_action( 'kkart_after_cart_item_name', $cart_item, $cart_item_key );

									// Meta data.
									echo kkart_get_formatted_cart_item_data( $cart_item ); // PHPCS: XSS ok.

									// Backorder notification.
									if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
										echo wp_kses_post( apply_filters( 'kkart_cart_item_backorder_notification', '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'kkart' ) . '</p>', $product_id ) );
									}
									?>
									</td>

									<td class="product-price" data-title="<?php esc_attr_e( 'Price', 'kkart' ); ?>">
										<?php
											echo apply_filters( 'kkart_cart_item_price', KKART()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); // PHPCS: XSS ok.
										?>
									</td>

									<td class="product-quantity" data-title="<?php esc_attr_e( 'Quantity', 'kkart' ); ?>">
									<?php
									if ( $_product->is_sold_individually() ) {
										$product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
									} else {
										$product_quantity = kkart_quantity_input(
											array(
												'input_name'   => "cart[{$cart_item_key}][qty]",
												'input_value'  => $cart_item['quantity'],
												'max_value'    => $_product->get_max_purchase_quantity(),
												'min_value'    => '0',
												'product_name' => $_product->get_name(),
											),
											$_product,
											false
										);
									}

									echo apply_filters( 'kkart_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item ); // PHPCS: XSS ok.
									?>
									</td>

									<td class="product-subtotal" data-title="<?php esc_attr_e( 'Subtotal', 'kkart' ); ?>">
										<?php
											echo apply_filters( 'kkart_cart_item_subtotal', KKART()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // PHPCS: XSS ok.
										?>
									</td>
								</tr>
								<?php
							}
						}
						?>

						<?php do_action( 'kkart_cart_contents' ); ?>

						<tr>
							<td colspan="6" class="actions">

								<?php if ( kkart_coupons_enabled() ) { ?>
									<div class="coupon">
										<label for="coupon_code"><?php esc_html_e( 'Coupon:', 'kkart' ); ?></label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php esc_attr_e( 'Coupon code', 'kkart' ); ?>" /> <button type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'kkart' ); ?>"><?php esc_attr_e( 'Apply coupon', 'kkart' ); ?></button>
										<?php do_action( 'kkart_cart_coupon' ); ?>
									</div>
								<?php } ?>

								<button type="submit" class="button" name="update_cart" value="<?php esc_attr_e( 'Update cart', 'kkart' ); ?>"><?php esc_html_e( 'Update cart', 'kkart' ); ?></button>

								<?php do_action( 'kkart_cart_actions' ); ?>

								<?php wp_nonce_field( 'kkart-cart', 'kkart-cart-nonce' ); ?>
							</td>
						</tr>

						<?php do_action( 'kkart_after_cart_contents' ); ?>
					</tbody>
				</table>
				<?php do_action( 'kkart_after_cart_table' ); ?>
			</form>

			<?php do_action( 'kkart_before_cart_collaterals' ); ?>

			<div class="cart-collaterals">
				<?php
					/**
					 * Cart collaterals hook.
					 *
					 * @hooked kkart_cross_sell_display
					 * @hooked kkart_cart_totals - 10
					 */
					do_action( 'kkart_cart_collaterals' );
				?>
			</div>

			<?php do_action( 'kkart_after_cart' );
		}
	}
}
