<?php

namespace fluXtore\Core\Frontend;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'fluXtore_Order_Bump' ) ) {
    class fluXtore_Order_Bump {
        /**
         * @var self|null
         */
        private static $instance = null;

        private function __construct() {}

        public static function init() {
            if ( null !== self::$instance ) {
                return;
            }

            self::$instance = new self();
            self::$instance->register_hooks();
        }

        private function register_hooks() {
            add_action( 'wp_ajax_fluxtore_add_bump_product', [ $this, 'add_bump_product' ] );
            add_action( 'wp_ajax_nopriv_fluxtore_add_bump_product', [ $this, 'add_bump_product' ] );

            add_action( 'wp_ajax_fluxtore_remove_bump_product', [ $this, 'remove_bump_product' ] );
            add_action( 'wp_ajax_nopriv_fluxtore_remove_bump_product', [ $this, 'remove_bump_product' ] );

            add_action( 'wp_ajax_fluxtore_add_bump_product_all', [ $this, 'add_multiple_products' ] );
            add_action( 'wp_ajax_nopriv_fluxtore_add_bump_product_all', [ $this, 'add_multiple_products' ] );

            add_action( 'woocommerce_cart_loaded_from_session', [ $this, 'restore_bump_products' ] );

            add_filter( 'woocommerce_add_cart_item_data', [ $this, 'store_custom_price' ], 10, 3 );
            add_action( 'woocommerce_before_calculate_totals', [ $this, 'apply_custom_price' ] );
        }

        public function add_bump_product() {
            check_ajax_referer( 'fluxtore_bump_nonce', 'nonce' );

            if ( ! isset( $_POST['product_id'], $_POST['product_price'] ) ) {
                wp_send_json_error( __( 'Missing product ID or price', 'fluxtore' ) );
            }

            $product_id = intval( wp_unslash( $_POST['product_id'] ) );
            $new_price  = floatval( wp_unslash( $_POST['product_price'] ) );
            $cart       = WC()->cart;

            $bump_offers = WC()->session->get( 'fluxtore_bump_offers', [] );
            if ( ! is_array( $bump_offers ) ) {
                $bump_offers = [];
            }

            $found = false;
            foreach ( $cart->get_cart() as $cart_item ) {
                if ( $cart_item['product_id'] === $product_id && isset( $cart_item['custom_price'] ) && floatval( $cart_item['custom_price'] ) === $new_price ) {
                    $found = true;
                    break;
                }
            }

            if ( ! $found ) {
                $cart->add_to_cart( $product_id, 1, 0, [], [ 'custom_price' => $new_price ] );
                $bump_offers[] = [
                    'product_id' => $product_id,
                    'price'      => $new_price,
                ];
                WC()->session->set( 'fluxtore_bump_offers', $bump_offers );
            }

            WC()->cart->calculate_totals();
            WC()->cart->set_session();

            wp_send_json_success( [ 'message' => __( 'Product added successfully', 'fluxtore' ) ] );
        }

        public function remove_bump_product() {
            check_ajax_referer( 'fluxtore_bump_nonce', 'nonce' );

            if ( ! isset( $_POST['product_id'] ) ) {
                wp_send_json_error( __( 'Missing product ID', 'fluxtore' ) );
            }

            $product_id  = intval( wp_unslash( $_POST['product_id'] ) );
            $cart        = WC()->cart;
            $bump_offers = WC()->session->get( 'fluxtore_bump_offers', [] );

            if ( ! is_array( $bump_offers ) ) {
                $bump_offers = [];
            }

            $removed = false;

            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( $cart_item['product_id'] === $product_id ) {
                    WC()->cart->remove_cart_item( $cart_item_key );
                    $removed = true;
                    break;
                }
            }

            if ( $removed ) {
                $bump_offers = array_values( array_filter( $bump_offers, function ( $offer ) use ( $product_id ) {
                    return (int) $offer['product_id'] !== $product_id;
                } ) );

                WC()->session->set( 'fluxtore_bump_offers', $bump_offers );
                WC()->cart->calculate_totals();
                WC()->cart->set_session();

                wp_send_json_success( [ 'message' => __( 'Product removed successfully', 'fluxtore' ) ] );
            }

            wp_send_json_error( __( 'Product not found in cart', 'fluxtore' ) );
        }

        public function add_multiple_products() {
            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'fluxtore_bump_nonce' ) ) {
                wp_send_json_error( [ 'message' => __( 'Security check failed', 'fluxtore' ) ] );
            }

            $cart = WC()->cart;

            if ( ! isset( $_POST['productValues'] ) || ! is_array( $_POST['productValues'] ) ) {
                wp_send_json_error( [ 'message' => __( 'Missing product data', 'fluxtore' ) ] );
            }

            foreach ( $_POST['productValues'] as $product ) {
                $product_id   = intval( $product['product_id'] );
                $custom_price = floatval( $product['product_price'] );

                if ( $product_id <= 0 || $custom_price <= 0 ) {
                    continue;
                }

                $found = false;

                foreach ( $cart->get_cart() as $cart_item ) {
                    if ( (int) $cart_item['product_id'] === $product_id ) {
                        $found = true;
                        break;
                    }
                }

                if ( ! $found ) {
                    $cart->add_to_cart( $product_id, 1, 0, [], [ 'custom_price' => $custom_price ] );
                }
            }

            WC()->cart->calculate_totals();
            WC()->cart->set_session();
            WC()->session->set( 'cart', WC()->cart->get_cart() );

            wp_send_json_success( [ 'message' => __( 'Cart updated successfully', 'fluxtore' ) ] );
        }

        public function restore_bump_products() {
            $bump_offers = WC()->session->get( 'fluxtore_bump_offers', [] );

            if ( ! is_array( $bump_offers ) ) {
                $bump_offers = [];
            }

            $cart = WC()->cart;

            foreach ( $bump_offers as $offer ) {
                $product_id   = isset( $offer['product_id'] ) ? intval( $offer['product_id'] ) : 0;
                $custom_price = isset( $offer['price'] ) ? floatval( $offer['price'] ) : 0;

                if ( $product_id <= 0 || $custom_price <= 0 ) {
                    continue;
                }

                $found = false;

                foreach ( $cart->get_cart() as $cart_item ) {
                    if ( (int) $cart_item['product_id'] === $product_id ) {
                        $found = true;
                        break;
                    }
                }

                if ( ! $found ) {
                    $cart->add_to_cart( $product_id, 1, 0, [], [ 'custom_price' => $custom_price ] );
                }
            }
        }

        public function store_custom_price( $cart_item_data, $product_id, $variation_id ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
            if ( isset( $_POST['product_price'] ) ) {
                $cart_item_data['custom_price'] = floatval( wp_unslash( $_POST['product_price'] ) );
            }

            return $cart_item_data;
        }

        public function apply_custom_price( $cart ) {
            if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
                return;
            }

            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( isset( $cart_item['custom_price'] ) ) {
                    $cart_item['data']->set_price( $cart_item['custom_price'] );
                }
            }
        }
    }
}

fluXtore_Order_Bump::init();
