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

/**
 * AJAX Handler: Add product to WooCommerce cart
 */
function doosearchas_add_to_cart() {
    check_ajax_referer('doosearchas_search_nonce', 'nonce');
    if (isset($_POST['product_id'])) {
        $product_id = intval(wp_unslash($_POST['product_id']));
        WC()->cart->add_to_cart($product_id);       
        wp_send_json(array('success' => true));
    }
    wp_send_json(array('success' => false));
}
add_action('wp_ajax_doosearchas_cb_add_to_cart', 'doosearchas_add_to_cart');
add_action('wp_ajax_nopriv_doosearchas_cb_add_to_cart', 'doosearchas_add_to_cart');

/**
 * AJAX Handler: Update quantity of an item in the WooCommerce cart
 */
function doosearchas_update_cart_quantity() {
    check_ajax_referer('doosearchas_search_nonce', 'nonce');
    if (isset($_POST['cart_item_key']) && isset($_POST['quantity'])) {
        $cart_item_key = sanitize_text_field(wp_unslash($_POST['cart_item_key']));
        $quantity = intval(wp_unslash($_POST['quantity']));
        if (WC()->cart->set_quantity($cart_item_key, $quantity, true)) {
            $response = array(
                'success' => true,
                'cart_total' => WC()->cart->get_cart_total()
            );
        } else {
            $response = array('success' => false);
        }
        wp_send_json($response);
    }
}
add_action('wp_ajax_doosearchas_cb_update_cart_quantity', 'doosearchas_update_cart_quantity');
add_action('wp_ajax_nopriv_doosearchas_cb_update_cart_quantity', 'doosearchas_update_cart_quantity');

/**
 * AJAX Handler: Remove an item from the WooCommerce cart
 */
function doosearchas_remove_cart_item() {
    check_ajax_referer('doosearchas_search_nonce', 'nonce');
    if (isset($_POST['cart_item_key'])) {
        $cart_item_key = sanitize_text_field(wp_unslash($_POST['cart_item_key']));
        WC()->cart->remove_cart_item($cart_item_key);
        wp_send_json(array(
            'success' => true,
        ));
    } else {
        wp_send_json(array(
            'success' => false,
        ));
    }
}
add_action('wp_ajax_doosearchas_cb_remove_cart_item', 'doosearchas_remove_cart_item');
add_action('wp_ajax_nopriv_doosearchas_cb_remove_cart_item', 'doosearchas_remove_cart_item');

/**
 * AJAX Handler: Retrieve cart information (count, total, items)
 */
function doosearchas_get_cart_info() {
    check_ajax_referer('doosearchas_search_nonce', 'nonce');
    $cart_count = WC()->cart->get_cart_contents_count();
    $cart_total = WC()->cart->get_cart_total();
    $cart_items = array();
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $_product = $cart_item['data'];
        $product_id = $_product->get_id();
        $image_id = $_product->get_image_id();
        if ($image_id) {
            $image_html = wp_get_attachment_image($image_id, 'woocommerce_thumbnail', false, ['loading' => 'lazy']);
        } else {
            $placeholder_url = wc_placeholder_img_src();
            $placeholder_id = attachment_url_to_postid($placeholder_url);
            if ($placeholder_id) {
                $image_html = wp_get_attachment_image($placeholder_id, 'woocommerce_thumbnail', false, ['loading' => 'lazy']);
            } else {
                // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Fallback image not in Media Library
                $image_html = '<img src="' . esc_url($placeholder_url) . '" class="woocommerce-placeholder wp-post-image" loading="lazy" alt="Placeholder" />';
            }
        }
        $cart_items[] = array(
            'key'        => $cart_item_key,
            'product_id' => $product_id,
            'name'       => $_product->get_name(),
            'quantity'   => $cart_item['quantity'],
            'price'      => wc_price($_product->get_price()),
            'image_html' => $image_html,
        );
    }
    wp_send_json(array(
        'success'     => true,
        'cart_count'  => $cart_count,
        'cart_total'  => $cart_total,
        'cart_items'  => $cart_items,
    ));
}
add_action('wp_ajax_doosearchas_cb_get_cart_info', 'doosearchas_get_cart_info');
add_action('wp_ajax_nopriv_doosearchas_cb_get_cart_info', 'doosearchas_get_cart_info');

/**
 * Ensure WooCommerce cart fragments script is loaded for live cart updates
 */
function doosearchas_ensure_wc_cart_fragments() {
    if (class_exists('WooCommerce')) {
        wp_enqueue_script('wc-cart-fragments');
    }
}
add_action('wp_enqueue_scripts', 'doosearchas_ensure_wc_cart_fragments');