<?php
/**
 * Cart drawer helpers and AJAX add-all.
 *
 * @package Foliora
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Free-shipping remainder in dollars.
 *
 * @return float
 */
function foliora_free_ship_remaining() {
	$min = 50;
	if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
		return $min;
	}
	$sub = (float) WC()->cart->get_displayed_subtotal();
	return max( 0, $min - $sub );
}

/**
 * Free-shipping progress 0–100.
 *
 * @return int
 */
function foliora_free_ship_percent() {
	$min = 50;
	if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
		return 0;
	}
	$sub = (float) WC()->cart->get_displayed_subtotal();
	return (int) min( 100, round( ( $sub / $min ) * 100 ) );
}

/**
 * AJAX: add several products at once (complete-your-setup).
 */
function foliora_ajax_add_setup() {
	if ( ! function_exists( 'WC' ) ) {
		wp_send_json_error( array( 'message' => 'Shop is not ready.' ) );
	}
	check_ajax_referer( 'foliora_cart', 'nonce' );

	$ids = isset( $_POST['product_ids'] ) ? (array) wp_unslash( $_POST['product_ids'] ) : array();
	$ids = array_filter( array_map( 'absint', $ids ) );

	foreach ( $ids as $id ) {
		$product = wc_get_product( $id );
		if ( ! $product ) {
			continue;
		}
		if ( $product->is_type( 'variable' ) ) {
			$children = $product->get_children();
			if ( $children ) {
				WC()->cart->add_to_cart( $id, 1, $children[0] );
			}
		} else {
			WC()->cart->add_to_cart( $id, 1 );
		}
	}

	WC_AJAX::get_refreshed_fragments();
}
add_action( 'wp_ajax_foliora_add_setup', 'foliora_ajax_add_setup' );
add_action( 'wp_ajax_nopriv_foliora_add_setup', 'foliora_ajax_add_setup' );
