<?php


if (class_exists('WooCommerce')) {

add_action('template_redirect', 'remove_woocommerce_sidebar_on_product_page');
function remove_woocommerce_sidebar_on_product_page() {
    if ( is_product() ) {
        remove_action('woocommerce_sidebar', 'woocommerce_get_sidebar', 10);
    }
}

add_action('template_redirect', 'remove_woocommerce_breadcrumb_on_product_page');
function remove_woocommerce_breadcrumb_on_product_page() {
    if ( is_product() ) {
        remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);
    }
}

add_action('template_redirect', function () {
    if (isset($_POST['buy_now']) && isset($_POST['add-to-cart'])) {
        global $woocommerce;

        $product_id = absint($_POST['add-to-cart']);
        $quantity = isset($_POST['quantity']) ? absint($_POST['quantity']) : 1;

        $woocommerce->cart->empty_cart(); // Optional: clear cart for single-product checkout
        $woocommerce->cart->add_to_cart($product_id, $quantity);
        wp_safe_redirect(wc_get_checkout_url());
        exit;
    }
});



// Woocommerce Cart Link
function glowify_woocommerce_cart_link() {
    global $woocommerce;
    ?>
    <div class="cs_header_cart_fragment"><!-- Add a parent wrapper -->
        <span class="cs_header_cart_label">
            <?php echo sprintf(_n('%d', '%d', $woocommerce->cart->cart_contents_count, 'glowify-wp'), $woocommerce->cart->cart_contents_count); ?>
        </span>

        <span class="cs_header_cart_amount">
            (<?php echo wc_price(WC()->cart->get_cart_total()); ?>)
        </span>
    </div>
    
    <?php
}

/**
* Show cart contents / total Ajax
*/
add_filter('woocommerce_add_to_cart_fragments', 'glowify_woocommerce_header_add_to_cart_fragment');
function glowify_woocommerce_header_add_to_cart_fragment($fragments) {
    // Update cart contents count
    ob_start();
    ?>
    <span class="cs_header_cart_label">
        <?php echo sprintf(_n('%d', '%d', WC()->cart->cart_contents_count, 'glowify-wp'), WC()->cart->cart_contents_count); ?>
    </span>
    <?php
    $fragments['span.cs_header_cart_label'] = ob_get_clean();

    // Update cart total price
    ob_start();
    $cart_total = WC()->cart->get_cart_total();
    ?>
    <span class="cs_header_cart_amount">(<?php echo $cart_total; ?>)</span>
    <?php
    $fragments['span.cs_header_cart_amount'] = ob_get_clean();

    return $fragments;
}


/* Sidebar MiniCart Ajax  */
add_action( 'wp_ajax_nopriv_get_mini_cart_html', 'get_mini_cart_html' );
add_action( 'wp_ajax_get_mini_cart_html', 'get_mini_cart_html' );
function get_mini_cart_html() {
	ob_start();
    $cart_total = WC()->cart->get_cart_total();
	
	// Output your cart HTML again
	if ( class_exists('WooCommerce') ) :
		?>
		<div class="cs_cart_card">
            <div class="cs_cart_card_head cs_gray_bg">
            <h3 class="mb-0 cs_fs_18 cs_semibold">
                Your Cart <span class="cs_header_cart_amount">(<?php echo $cart_total; ?>)</span>
            </h3>
            <button class="cs_cart_close">Close</button>
            </div>
            <div class="cs_cart_card_body">
            <div class="cs_cart_card_body_in">
            <?php if ( function_exists( 'WC' ) && WC()->cart ) : ?>
                <ul class="cs_cart_card_list cs_mp_0">
                    <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) :
                    $product = $cart_item['data'];
                    if ( ! $product || ! $product->exists() ) continue;
                    $product_id = $cart_item['product_id'];
                    $product_name = $product->get_name();
                    $quantity = $cart_item['quantity'];
                    $thumbnail = $product->get_image( 'woocommerce_thumbnail' );
                    $price = wc_price( $product->get_price() );
                    $line_total = wc_price( $cart_item['line_total'] );
                    ?>
                    <li>
                    <div class="cs_cart_card_item">
                        <div class="cs_cart_card_item_left">
                        <?php echo $thumbnail; ?>
                        </div>
                        <div class="cs_cart_card_item_right">
                        <h3 class="cs_fs_18 cs_medium"><?php echo esc_html( $product_name ); ?></h3>
                        <p class="mb-0"><?php echo $quantity; ?> x <span class="cs_primary_color cs_medium"><?php echo $price; ?></span></p>
                        <button class="cs_cart_card_item_remove" data-cart-item-key="<?php echo esc_attr($cart_item_key); ?>" ><i class="fa-regular fa-circle-xmark"></i></button>
                        </div>
                    </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php else : ?>
                <p class="cs_empty_cart"><?php esc_html_e('Your cart is empty or not available right now.','glowify-wp');?></p>
                <?php endif; ?>

            </div>
            </div>
            <div class="cs_cart_card_footer">
            <div class="cs_cart_card_subtotal">
                <span>Subtotal:</span> 
                <span class="cs_primary_color cs_semibold"><span class="cs_header_cart_amount"><?php echo $cart_total; ?></span></span>
            </div>
            <a href="<?php echo esc_url(wc_get_cart_url()); ?>" class="cs_btn cs_style_2 cs_medium cs_type_1 w-100">
                <span>View Cart</span>
            </a>
            <div class="cs_height_10 cs_height_lg_10"></div>
            <a href="<?php echo esc_url(wc_get_checkout_url()); ?>" class="cs_btn cs_style_1 cs_medium cs_type_1 w-100">
                <span>Checkout</span>
            </a>
            </div>
        </div>
		<?php
	endif;

	$html = ob_get_clean();
	wp_send_json_success( array( 'html' => $html ) );
}

/* Sidebar MiniCart Ajax Remove Item  */
add_action( 'wp_ajax_remove_cart_item', 'remove_cart_item' );
add_action( 'wp_ajax_nopriv_remove_cart_item', 'remove_cart_item' );

function remove_cart_item() {
    // Check if the cart item key is set
    if( isset($_POST['cart_item_key']) ) {
        $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
        
        // Remove the item from the cart
        if( WC()->cart->remove_cart_item($cart_item_key) ) {
            // Get updated cart fragments to refresh header cart
            $fragments = apply_filters('woocommerce_add_to_cart_fragments', array());
            
            // Return success response with fragments
            wp_send_json_success(array(
                'fragments' => $fragments
            ));
        } else {
            // If unable to remove, send an error message
            wp_send_json_error(array('message' => 'Failed to remove the item.'));
        }
    } else {
        wp_send_json_error(array('message' => 'Cart item key missing.'));
    }
}

/* Sidebar MiniCart Ajax  Remove Item */
add_action('wp_ajax_remove_selected_cart_items', 'glowify_remove_selected_cart_items');
add_action('wp_ajax_nopriv_remove_selected_cart_items', 'glowify_remove_selected_cart_items');

function glowify_remove_selected_cart_items() {
    // Check nonce for security
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'remove-cart-items')) {
        wp_send_json_error('Security check failed');
        die();
    }

    // Check if cart items are provided
    if (!isset($_POST['cart_items']) || !is_array($_POST['cart_items'])) {
        wp_send_json_error('No items selected');
        die();
    }

    // Remove each selected item from cart
    foreach ($_POST['cart_items'] as $cart_item_key) {
        WC()->cart->remove_cart_item(sanitize_text_field($cart_item_key));
    }

    // Return success
    wp_send_json_success(array(
        'message' => 'Items removed successfully',
        'fragments' => apply_filters('woocommerce_add_to_cart_fragments', array())
    ));

    die();
}


}