<?php

namespace CodeConfig\EAW\Ajax;

use CodeConfig\EAW\App\CartManager\SidebarCartContent;

defined('ABSPATH') || exit('No direct script access allowed');

class Sidebar
{
    public static function getSidebarProductPriceStyle()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result = [
            'status'  => '',
            'message' => '',
        ];

        $style  = sanitize_text_field(wp_unslash($_POST['style'] ?? ''));

        if ($style) {
            ob_start();
            SidebarCartContent::get_sidebar_content_pd_html(WC()->cart, $style);
            $html              = ob_get_clean();
            $result['status']  = $html ? 'success' : '';
            $result['message'] = $html;
        }

        wp_send_json($result);
    }

    public static function getSidebarFootMessageHtml()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result         = [
            'status'  => '',
            'message' => '',
        ];

        $custom_message = wp_kses_post(wp_unslash($_POST['custom_message'] ?? ''));
        if ($custom_message) {
            ob_start();
            SidebarCartContent::get_scFootMsg_html($custom_message);
            $html              = ob_get_clean();
            $result['status']  = $html ? 'success' : '';
            $result['message'] = $html;
        }
        wp_send_json($result);
    }

    public static function getSidebarFootPdPlusHtml()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');
        $result = [
            'status'  => '',
            'message' => '',
        ];

        $type   = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));
        if ($type) {
            $html              = SidebarCartContent::get_product_plus('', $type);
            $result['status']  = $html ? 'success' : '';
            $result['message'] = $html;
        }
        wp_send_json($result);
    }

    public static function getChangeQuantity()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $eaw_cart = isset($_POST['eaw_cart']) ? wc_clean(sanitize_text_field(wp_unslash($_POST['eaw_cart']))) : '';
        if (empty($eaw_cart)) {
            wp_send_json(['error' => true]);
        }
        $cart = WC()->cart->get_cart();

        foreach ($eaw_cart as $cart_item_key => $qty) {
            if (! isset($cart[$cart_item_key]) || ! ($product = $cart[$cart_item_key]['data'] ?? '')) {
                continue;
            }
            $cart_qty = $cart[$cart_item_key]['quantity'] ?? '';
            if ($product->is_sold_individually() && $cart_qty == 1) {
                continue;
            }
            $qty = $qty['qty'] ?? 0;
            $qty = $qty < 0 ? 0 : ($product->is_sold_individually() && floatval($qty) > 1 ? 1 : $qty);
            // Sanitize.
            $qty = apply_filters('woocommerce_stock_amount_cart_item', wc_stock_amount(preg_replace('/[^0-9\.]/', '', $qty)), $cart_item_key);
            if ('' === $qty || $qty == ($cart[$cart_item_key]['quantity'] ?? '')) {
                continue;
            }
            WC()->cart->set_quantity(strval($cart_item_key), $qty, true);
        }

        WC()->cart->calculate_totals();
        \WC_AJAX::get_refreshed_fragments();
        die();
    }

    public static function removeItem()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

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

        if ($cart_item_key && false !== WC()->cart->remove_cart_item($cart_item_key)) {
            do_action('woocommerce_remove_cart_item', $cart_item_key);
            \WC_AJAX::get_refreshed_fragments();
        } else {
            wp_send_json_error();
        }
        die();
    }

    public static function applyCoupon()
    {

        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result = [
            'status'  => 'error',
            'message' => '',
        ];

        $coupon_code = sanitize_text_field(wp_unslash($_POST['eaw_coupon_code'] ?? ''));

        if ($coupon_code) {
            WC()->cart->add_discount(wc_format_coupon_code($coupon_code));
            $notices = WC()->session->get('wc_notices', []);
            if (empty($notices['error'])) {
                $result['status'] = 'success';
            }
        } else {
            wc_add_notice(\WC_Coupon::get_generic_coupon_error(\WC_Coupon::E_WC_COUPON_PLEASE_ENTER), 'error');
        }

        $result['message'] = wc_print_notices(true);
        wp_send_json($result);
    }

    public static function removeCoupon()
    {

        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result = [
            'status'  => 'error',
            'message' => '',
        ];

        $coupon = wc_format_coupon_code(wc_clean(sanitize_text_field(wp_unslash($_POST['eaw_coupon_code'] ?? ''))));

        if (empty($coupon)) {
            $result['message'] = esc_html__('Sorry there was a problem removing this coupon.', 'essential-addons-for-woocommerce');
        } else {
            WC()->cart->remove_coupon($coupon);
            $notices = WC()->session->get('wc_notices', []);
            if (empty($notices['error'])) {
                $result['status']  = 'success';
                $result['message'] = esc_html__('Coupon has been removed.', 'essential-addons-for-woocommerce');
                WC()->cart->calculate_totals();
            }
        }

        wp_send_json($result);
    }

    public static function addToCart()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        if (!did_action('woocommerce_add_to_cart')) {
            \WC_Form_Handler::add_to_cart_action();
        }

        if (! empty(wc_get_notices('error'))) {
            wp_send_json(['error' => true, 'message' => wc_print_notices(true)]);
        } elseif (!empty($_POST['add-to-cart'])) {
            do_action('woocommerce_ajax_added_to_cart', apply_filters('woocommerce_add_to_cart_product_id', absint(sanitize_text_field(wp_unslash($_POST['add-to-cart'])))));
        }

        if (function_exists('facebook_for_woocommerce')) {
            add_filter('woocommerce_add_to_cart_fragments', fn ($fragments) => facebook_for_woocommerce()->get_integration()->events_tracker->add_add_to_cart_event_fragment($fragments), 10, 1);
        }

        \WC_AJAX::get_refreshed_fragments();
    }

    public static function getProductVariation()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result     = [
            'status' => 'error',
            'html'   => '',
        ];

        $product_id =  sanitize_text_field(wp_unslash($_POST['product_id'] ?? ''));

        $product = wc_get_product($product_id);
        if ($product && $product->is_type('variable') && $product->is_in_stock()) {
            ob_start();
            wc_get_template(
                'variation-popup.php',
                ['product' => $product],
                'essential-addons-for-woocommerce' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR,
                CCPEAW_TEMPLATES . 'atc/'
            );
            $html             = ob_get_clean();
            $result['status'] = 'success';
            $result['html']   = $html;
            wp_send_json($result);
        }
        wp_send_json($result);
    }
}
