<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * WooCommerce Cart Functions
 *
 * @package pawfect
 */

// Disable redirect to cart page after adding product via filter (not update_option)\nadd_filter('woocommerce_add_to_cart_redirect', '__return_false');

// Additional filter to prevent redirects
add_filter('wc_add_to_cart_params', 'pawfect_modify_add_to_cart_params');
function pawfect_modify_add_to_cart_params($params) {
    $params['cart_redirect_after_add'] = 'no';
    return $params;
}

// Add cart fragments for AJAX cart updates
add_filter('woocommerce_add_to_cart_fragments', 'pawfect_cart_count_fragments');

function pawfect_cart_count_fragments($fragments) {
    // Check if WooCommerce and cart are properly initialized
    if (!function_exists('WC') || !WC()->cart) {
        return $fragments;
    }

    $cart_count = WC()->cart->get_cart_contents_count();

    $visibility_class = $cart_count > 0 ? 'pawfect-scale-100 pawfect-opacity-100' : 'pawfect-scale-0 pawfect-opacity-0';

    $fragments['.pawfect-cart-badge'] = '<span class="pawfect-cart-badge pawfect-absolute pawfect--top-2 pawfect--right-2 pawfect-text-white pawfect-text-xs pawfect-font-bold pawfect-rounded-full pawfect-w-5 pawfect-h-5 pawfect-flex pawfect-items-center pawfect-justify-center pawfect-transition-all pawfect-duration-300 ' . $visibility_class . '" style="background-color: var(--pawfect-primary, #F4A259);">' . $cart_count . '</span>';

    // Also update cart count in other places if needed
    $fragments['.pawfect-cart-count'] = $cart_count;

    // Update cart dropdown content - wrap in div to ensure proper replacement
    $fragments['.pawfect-cart-dropdown-content'] = '<div class="pawfect-cart-dropdown-content">' . pawfect_get_cart_dropdown_content() . '</div>';

    return $fragments;
}

// Generate cart dropdown content
function pawfect_get_cart_dropdown_content() {
    if (!function_exists('WC') || !WC()->cart) {
        return '<div class="pawfect-p-6 pawfect-text-center pawfect-text-gray-500">' . esc_html__('Cart is not available', 'pawfect') . '</div>';
    }

    $cart_items = WC()->cart->get_cart();
    $cart_count = WC()->cart->get_cart_contents_count();
    $cart_total = WC()->cart->get_cart_total();

    if (empty($cart_items)) {
        return '
        <div class="pawfect-p-6 pawfect-text-center">
           
            <svg xmlns="http://www.w3.org/2000/svg" class="pawfect-w-12 pawfect-h-12 pawfect-mx-auto pawfect-mb-4 pawfect-text-gray-300" fill="currentColor" viewBox="0 0 256 256"><path d="M216,68H172V64a44,44,0,0,0-88,0v4H40A12,12,0,0,0,28,80V200a12,12,0,0,0,12,12H216a12,12,0,0,0,12-12V80A12,12,0,0,0,216,68ZM92,64a36,36,0,0,1,72,0v4H92ZM220,200a4,4,0,0,1-4,4H40a4,4,0,0,1-4-4V80a4,4,0,0,1,4-4H84V96a4,4,0,0,0,8,0V76h72V96a4,4,0,0,0,8,0V76h44a4,4,0,0,1,4,4Z"></path></svg>
            <p class="pawfect-text-gray-500 pawfect-mb-4">' . __('Your cart is empty', 'pawfect') . '</p>
            <a href="' . esc_url(wc_get_page_permalink('shop')) . '" class="pawfect-btn">
                ' . __('Start Shopping', 'pawfect') . '
            </a>
        </div>';
    }

    $content = '<div class="pawfect-cart-dropdown-items pawfect-max-h-80 pawfect-overflow-y-auto">';

    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];
        $product_id = $cart_item['product_id'];
        $quantity = $cart_item['quantity'];
        $product_name = $product->get_name();
        $product_price = WC()->cart->get_product_price($product);
        $product_permalink = $product->get_permalink($cart_item);
        $thumbnail = $product->get_image('thumbnail');

        $content .= '
        <div class="pawfect-flex pawfect-items-center pawfect-gap-3 pawfect-p-4 pawfect-border-b pawfect-border-gray-100 pawfect-group">
            <div class="pawfect-w-16 pawfect-h-16 pawfect-flex-shrink-0">
                <a href="' . esc_url($product_permalink) . '" class="pawfect-block pawfect-w-full pawfect-h-full pawfect-rounded-lg pawfect-overflow-hidden">
                    ' . wp_kses_post($thumbnail) . '
                </a>
            </div>
            <div class="pawfect-flex-1 pawfect-min-w-0">
                <a href="' . esc_url($product_permalink) . '" class="pawfect-cart-product-link pawfect-transition-colors">
                    <span class="pawfect-font-medium pawfect-text-gray-900 pawfect-text-sm pawfect-line-clamp-2 pawfect-mb-1">
                        ' . esc_html($product_name) . '
                    </span>
                </a>
                <div class="pawfect-flex pawfect-items-center pawfect-justify-between pawfect-text-sm">
                    <span class="pawfect-text-gray-500">' . __('Qty:', 'pawfect') . ' ' . $quantity . '</span>
                    <span class="pawfect-font-semibold pawfect-text-pawfect-primary">' . wp_kses_post($product_price) . '</span>
                </div>
            </div>
            <button class="pawfect-remove-cart-item pawfect-transition-all pawfect-text-gray-600 hover:pawfect-text-red-500 pawfect-p-2 pawfect-bg-gray-100 hover:pawfect-bg-red-100 pawfect-rounded-full pawfect-ml-2"
                    data-cart-item-key="' . esc_attr($cart_item_key) . '"
                    title="' . esc_attr__('Remove item', 'pawfect') . '">
                <svg class="pawfect-w-3 pawfect-h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>';
    }

    $content .= '</div>';

    // Cart footer with total and buttons
    $content .= '
    <div class="pawfect-p-4 pawfect-bg-gray-50 pawfect-border-t pawfect-border-gray-100">
        <div class="pawfect-flex pawfect-items-center pawfect-justify-between pawfect-mb-4">
            <span class="pawfect-font-medium pawfect-text-gray-900">' . __('Total:', 'pawfect') . '</span>
            <span class="pawfect-font-bold pawfect-text-lg pawfect-text-pawfect-primary">' . wp_kses_post($cart_total) . '</span>
        </div>
        <div class="pawfect-grid pawfect-grid-cols-2 pawfect-gap-3">
            <a href="' . esc_url(wc_get_cart_url()) . '" class="pawfect-btn-secondary">
                ' . __('View Cart', 'pawfect') . '
            </a>
            <a href="' . esc_url(wc_get_checkout_url()) . '" class="pawfect-btn">
                ' . __('Checkout', 'pawfect') . '
            </a>
        </div>
    </div>';

    return $content;
}

// Update add to cart button text after adding to cart
add_filter('woocommerce_product_add_to_cart_text', 'pawfect_custom_add_to_cart_text', 10, 2);

function pawfect_custom_add_to_cart_text($text, $product) {
    if ($product->is_type('simple') && $product->is_purchasable() && $product->is_in_stock()) {
        // Check if WooCommerce and cart are properly initialized
        if (function_exists('WC') && WC()->cart && !WC()->cart->is_empty()) {
            // Check if product is already in cart
            $cart = WC()->cart->get_cart();
            foreach ($cart as $cart_item_key => $cart_item) {
                if ($cart_item['product_id'] == $product->get_id()) {
                    return __('Added to Cart', 'pawfect');
                }
            }
        }
        return __('Add to Cart', 'pawfect');
    }
    return $text;
}

// Add custom AJAX search functionality
add_action('wp_ajax_pawfect_product_search', 'pawfect_ajax_product_search');
add_action('wp_ajax_nopriv_pawfect_product_search', 'pawfect_ajax_product_search');

function pawfect_ajax_product_search() {
    check_ajax_referer('pawfect_search_nonce', 'nonce');

    $search_term = sanitize_text_field( wp_unslash( $_POST['search_term'] ) );

    if (empty($search_term) || strlen($search_term) < 2) {
        wp_die();
    }

    // Search products
    $product_args = array(
        'post_type' => 'product',
        'posts_per_page' => 4,
        's' => $search_term,
        'post_status' => 'publish'
    );

    // Search blog posts
    $blog_args = array(
        'post_type' => 'post',
        'posts_per_page' => 4,
        's' => $search_term,
        'post_status' => 'publish'
    );

    // Search pages
    $page_args = array(
        'post_type' => 'page',
        'posts_per_page' => 2,
        's' => $search_term,
        'post_status' => 'publish'
    );

    $products = new WP_Query($product_args);
    $posts = new WP_Query($blog_args);
    $pages = new WP_Query($page_args);

    $has_results = $products->have_posts() || $posts->have_posts() || $pages->have_posts();

    if ($has_results) {
        echo '<div class="pawfect-p-4">';
        echo '<div class="pawfect-text-sm pawfect-text-gray-500 pawfect-mb-4">Search results for "' . esc_html($search_term) . '"</div>';
        echo '<div class="pawfect-space-y-3">';

        // Display Products
        if ($products->have_posts()) {
            echo '<div class="pawfect-text-xs pawfect-text-gray-400 pawfect-uppercase pawfect-font-semibold pawfect-mb-2">' . esc_html__('Products', 'pawfect') . '</div>';
            while ($products->the_post()) {
                $products->the_post();
                $product = wc_get_product(get_the_ID());
                $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'thumbnail');

                echo '<a href="' . esc_url(get_permalink()) . '" class="pawfect-flex pawfect-items-center pawfect-gap-3 pawfect-p-3 pawfect-rounded-lg hover:pawfect-bg-gray-50 pawfect-transition-colors pawfect-block">';

                if ($image) {
                    echo '<img src="' . esc_url($image[0]) . '" alt="' . esc_attr(get_the_title()) . '" class="pawfect-w-12 pawfect-h-12 pawfect-object-cover pawfect-rounded-lg">';
                } else {
                    echo '<div class="pawfect-w-12 pawfect-h-12 pawfect-bg-gray-200 pawfect-rounded-lg pawfect-flex pawfect-items-center pawfect-justify-center">';
                    echo '<svg class="pawfect-w-6 pawfect-h-6 pawfect-text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">';
                    echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>';
                    echo '</svg>';
                    echo '</div>';
                }

                echo '<div class="pawfect-flex-1">';
                echo '<h4 class="pawfect-font-medium pawfect-text-gray-900 pawfect-line-clamp-1">' . esc_html(get_the_title()) . '</h4>';
                echo '<p class="pawfect-text-sm pawfect-text-pawfect-primary pawfect-font-semibold">' . wp_kses_post($product->get_price_html()) . '</p>';
                echo '</div>';

                echo '</a>';
            }
        }

        // Display Blog Posts
        if ($posts->have_posts()) {
            if ($products->have_posts()) {
                echo '<div class="pawfect-border-t pawfect-border-gray-100 pawfect-pt-3 pawfect-mt-3"></div>';
            }
            echo '<div class="pawfect-text-xs pawfect-text-gray-400 pawfect-uppercase pawfect-font-semibold pawfect-mb-2">' . esc_html__('Blog Posts', 'pawfect') . '</div>';
            while ($posts->have_posts()) {
                $posts->the_post();
                $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'thumbnail');

                echo '<a href="' . esc_url(get_permalink()) . '" class="pawfect-flex pawfect-items-center pawfect-gap-3 pawfect-p-3 pawfect-rounded-lg hover:pawfect-bg-gray-50 pawfect-transition-colors pawfect-block">';

                if ($image) {
                    echo '<img src="' . esc_url($image[0]) . '" alt="' . esc_attr(get_the_title()) . '" class="pawfect-w-12 pawfect-h-12 pawfect-object-cover pawfect-rounded-lg">';
                } else {
                    echo '<div class="pawfect-w-12 pawfect-h-12 pawfect-bg-gray-200 pawfect-rounded-lg pawfect-flex pawfect-items-center pawfect-justify-center">';
                    echo '<svg class="pawfect-w-6 pawfect-h-6 pawfect-text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">';
                    echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.291-1.007-5.824-2.562M15 6.306a7.962 7.962 0 00-6 0M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9-4.03-9-9-9z"></path>';
                    echo '</svg>';
                    echo '</div>';
                }

                echo '<div class="pawfect-flex-1">';
                echo '<h4 class="pawfect-font-medium pawfect-text-gray-900 pawfect-line-clamp-1">' . esc_html(get_the_title()) . '</h4>';
                echo '<p class="pawfect-text-sm pawfect-text-gray-500">' . esc_html(get_the_date()) . '</p>';
                echo '</div>';

                echo '</a>';
            }
        }

        // Display Pages
        if ($pages->have_posts()) {
            if ($products->have_posts() || $posts->have_posts()) {
                echo '<div class="pawfect-border-t pawfect-border-gray-100 pawfect-pt-3 pawfect-mt-3"></div>';
            }
            echo '<div class="pawfect-text-xs pawfect-text-gray-400 pawfect-uppercase pawfect-font-semibold pawfect-mb-2">' . esc_html__('Pages', 'pawfect') . '</div>';
            while ($pages->have_posts()) {
                $pages->the_post();

                echo '<a href="' . esc_url(get_permalink()) . '" class="pawfect-flex pawfect-items-center pawfect-gap-3 pawfect-p-3 pawfect-rounded-lg hover:pawfect-bg-gray-50 pawfect-transition-colors pawfect-block">';

                echo '<div class="pawfect-w-12 pawfect-h-12 pawfect-bg-gray-200 pawfect-rounded-lg pawfect-flex pawfect-items-center pawfect-justify-center">';
                echo '<svg class="pawfect-w-6 pawfect-h-6 pawfect-text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">';
                echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>';
                echo '</svg>';
                echo '</div>';

                echo '<div class="pawfect-flex-1">';
                echo '<h4 class="pawfect-font-medium pawfect-text-gray-900 pawfect-line-clamp-1">' . esc_html(get_the_title()) . '</h4>';
                echo '<p class="pawfect-text-sm pawfect-text-gray-500">' . esc_html__('Page', 'pawfect') . '</p>';
                echo '</div>';

                echo '</a>';
            }
        }

        echo '</div>';
        echo '<div class="pawfect-mt-4 pawfect-pt-4 pawfect-border-t pawfect-border-gray-100">';
        echo '<a href="' . esc_url(home_url('/?s=' . urlencode($search_term))) . '" class="pawfect-text-pawfect-primary pawfect-text-sm pawfect-font-medium hover:pawfect-underline">' . esc_html__('View all results', 'pawfect') . ' &rarr;</a>';
        echo '</div>';
        echo '</div>';
    } else {
        echo '<div class="pawfect-p-6 pawfect-text-center pawfect-text-gray-500">';
        echo '<svg class="pawfect-w-12 pawfect-h-12 pawfect-mx-auto pawfect-mb-4 pawfect-text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">';
        echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>';
        echo '</svg>';
        echo '<p>' . sprintf( esc_html__( 'No results found for "%s"', 'pawfect' ), esc_html($search_term) ) . '</p>';
        echo '<p class="pawfect-text-sm pawfect-mt-2">' . esc_html__('Try searching with different keywords.', 'pawfect') . '</p>';
        echo '</div>';
    }
    
    wp_reset_postdata();
    wp_die();
}

// Enable AJAX add to cart for all products
add_filter('woocommerce_loop_add_to_cart_args', 'pawfect_loop_add_to_cart_args', 10, 2);

function pawfect_loop_add_to_cart_args($args, $product) {
    $args['attributes']['data-product_id'] = $product->get_id();
    $args['attributes']['data-product_sku'] = $product->get_sku();
    $args['class'] = $args['class'] . ' pawfect-ajax-add-to-cart';
    return $args;
}

// Enqueue WooCommerce and search AJAX scripts
add_action('wp_enqueue_scripts', 'pawfect_enqueue_ajax_scripts');

function pawfect_enqueue_ajax_scripts() {
    // Search AJAX
    wp_localize_script('pawfect-main', 'pawfect_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'search_nonce' => wp_create_nonce('pawfect_search_nonce'),
        'cart_nonce' => wp_create_nonce('pawfect_cart_nonce'),
        'i18n' => array(
            'adding'              => __( 'Adding...', 'pawfect' ),
            'added_to_cart'       => __( 'Added to Cart', 'pawfect' ),
            'add_to_cart'         => __( 'Add to Cart', 'pawfect' ),
            'product_added'       => __( 'Product added to cart!', 'pawfect' ),
            'error_adding'        => __( 'Error adding to cart', 'pawfect' ),
            'error_try_again'     => __( 'Error - Try Again', 'pawfect' ),
            'searching'           => __( 'Searching...', 'pawfect' ),
            'search_placeholder'  => __( 'Start typing to search for products...', 'pawfect' ),
            'search_unavailable'  => __( 'Search temporarily unavailable. Please try again.', 'pawfect' ),
            'search_requires_woo' => __( 'Search functionality requires WooCommerce to be active.', 'pawfect' ),
            'security_missing'    => __( 'Security token missing. Please refresh the page.', 'pawfect' ),
            'subscribing'         => __( 'Subscribing...', 'pawfect' ),
            'config_error'        => __( 'Configuration error. Please refresh the page.', 'pawfect' ),
            'nonce_failed'        => __( 'Nonce validation failed. Please refresh the page.', 'pawfect' ),
            'generic_error'       => __( 'An error occurred. Please try again.', 'pawfect' ),
            'go_to_top'           => __( 'Go to top', 'pawfect' ),
        ),
    ));

    // WooCommerce Add to Cart AJAX
    if (class_exists('WooCommerce')) {
        wp_localize_script('pawfect-main', 'wc_add_to_cart_params', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'wc_ajax_url' => WC_AJAX::get_endpoint('%%endpoint%%'),
            'i18n_view_cart' => esc_attr__('View cart', 'pawfect'),
            'cart_url' => apply_filters('woocommerce_add_to_cart_redirect', function_exists('wc_get_cart_url') ? wc_get_cart_url() : '', null),
            'is_cart' => function_exists('is_cart') ? is_cart() : false,
            'cart_redirect_after_add' => get_option('woocommerce_cart_redirect_after_add')
        ));
    }
}

// Ensure cart fragments work properly
add_action('wp_enqueue_scripts', 'pawfect_enqueue_wc_cart_fragments');

function pawfect_enqueue_wc_cart_fragments() {
    if (class_exists('WooCommerce')) {
        wp_enqueue_script('wc-cart-fragments');

        // Ensure jQuery is loaded for cart fragments
        wp_enqueue_script('jquery');

        // Add inline script to ensure cart fragments are initialized
        wp_add_inline_script('wc-cart-fragments', '
            jQuery(document).ready(function($) {
                // Force refresh cart fragments on page load if needed
                if (typeof wc_cart_fragments_params !== "undefined") {
                    $(document.body).trigger("wc_fragment_refresh");
                }
            });
        ');
    }
}

// AJAX handler for removing cart items
add_action('wp_ajax_pawfect_remove_cart_item', 'pawfect_remove_cart_item');
add_action('wp_ajax_nopriv_pawfect_remove_cart_item', 'pawfect_remove_cart_item');

function pawfect_remove_cart_item() {
    check_ajax_referer('pawfect_cart_nonce', 'nonce');

    if (!function_exists('WC') || !WC()->cart) {
        wp_send_json_error('Cart not available');
        return;
    }

    $cart_item_key = sanitize_text_field( wp_unslash( $_POST['cart_item_key'] ) );

    if (empty($cart_item_key)) {
        wp_send_json_error('Invalid cart item');
        return;
    }

    $removed = WC()->cart->remove_cart_item($cart_item_key);

    if ($removed) {
        WC()->cart->calculate_totals();

        // Get updated cart fragments
        $fragments = apply_filters('woocommerce_add_to_cart_fragments', array());

        wp_send_json_success(array(
            'cart_count' => WC()->cart->get_cart_contents_count(),
            'cart_total' => WC()->cart->get_cart_total(),
            'message' => __('Item removed from cart', 'pawfect'),
            'fragments' => $fragments
        ));
    } else {
        wp_send_json_error('Failed to remove item');
    }
}
