<?php

namespace fluXtore\Core\Admin\Ajax;

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

if ( ! class_exists( 'fluXtore_Ajax_Order_Bumps' ) ) {
    class fluXtore_Ajax_Order_Bumps {
        /**
         * @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_actions();
        }

        private function register_actions() {
            add_action( 'wp_ajax_save_custom_fields', [ $this, 'save_custom_fields' ] );
            add_action( 'wp_ajax_nopriv_save_custom_fields', [ $this, 'save_custom_fields' ] );

            add_action( 'wp_ajax_save_custom_fields1', [ $this, 'save_toggle_state' ] );
            add_action( 'wp_ajax_nopriv_save_custom_fields1', [ $this, 'save_toggle_state' ] );

            add_action( 'wp_ajax_response_get_form', [ $this, 'get_form_data' ] );
            add_action( 'wp_ajax_nopriv_response_get_form', [ $this, 'get_form_data' ] );
        }

        public function save_custom_fields() {
            global $wpdb;

            $post_id            = isset( $_POST['postidtwo'] ) ? intval( wp_unslash( $_POST['postidtwo'] ) ) : 0;
            $product_title      = isset( $_POST['producttitle'] ) ? sanitize_text_field( wp_unslash( $_POST['producttitle'] ) ) : '';
            $price_value        = isset( $_POST['priceValue'] ) ? sanitize_text_field( wp_unslash( $_POST['priceValue'] ) ) : '';
            $discount_price     = isset( $_POST['discountPrice'] ) ? sanitize_text_field( wp_unslash( $_POST['discountPrice'] ) ) : '';
            $order_dump_text    = isset( $_POST['orderDumpText'] ) ? sanitize_text_field( wp_unslash( $_POST['orderDumpText'] ) ) : '';
            $order_toggle_text  = isset( $_POST['orderBumpToggleText'] ) ? sanitize_text_field( wp_unslash( $_POST['orderBumpToggleText'] ) ) : '';
            $order_check_data   = isset( $_POST['ordercheckdata'] ) ? sanitize_text_field( wp_unslash( $_POST['ordercheckdata'] ) ) : '';
            $parent_class       = isset( $_POST['parentClass'] ) ? sanitize_text_field( wp_unslash( $_POST['parentClass'] ) ) : '';
            $matched_class      = isset( $_POST['matchedClass'] ) ? sanitize_text_field( wp_unslash( $_POST['matchedClass'] ) ) : '';
            $id_base_check      = isset( $_POST['idbaseinsertcheked'] ) ? sanitize_text_field( wp_unslash( $_POST['idbaseinsertcheked'] ) ) : '';

            if ( ! $post_id ) {
                wp_send_json_error( [ 'message' => __( 'Invalid step identifier.', 'fluxtore' ) ] );
            }

            $product_id = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = 'product' LIMIT 1",
                    $product_title
                )
            );

            $this->maybe_update_meta( $post_id, $id_base_check, $order_check_data );
            $this->maybe_update_product_meta( $post_id, $matched_class, $product_id );
            $this->maybe_update_grouped_meta( $post_id, $parent_class, $product_id, $price_value, $discount_price, $order_dump_text, $order_toggle_text, $order_check_data );

            wp_send_json_success(
                [
                    'message'     => __( 'Data updated successfully', 'fluxtore' ),
                    'product_id'  => $product_id,
                    'parentclass' => $parent_class,
                    'post_id'     => $post_id,
                ]
            );
        }

        public function save_toggle_state() {
            $id_base_check   = isset( $_POST['idbaseinsertcheked'] ) ? sanitize_text_field( wp_unslash( $_POST['idbaseinsertcheked'] ) ) : '';
            $order_checkdata = isset( $_POST['ordercheckdata'] ) ? sanitize_text_field( wp_unslash( $_POST['ordercheckdata'] ) ) : '';
            $post_id         = isset( $_POST['postidtwo'] ) ? intval( wp_unslash( $_POST['postidtwo'] ) ) : 0;

            if ( ! $post_id || ! $id_base_check ) {
                wp_send_json_error( [ 'message' => __( 'Missing data.', 'fluxtore' ) ] );
            }

            switch ( $id_base_check ) {
                case 'ordercheckboxdata1':
                case 'ordercheckboxdata2':
                case 'ordercheckboxdata3':
                case 'ordercheckboxdata4':
                    update_post_meta( $post_id, $id_base_check, $order_checkdata );
                    break;
            }

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

        public function get_form_data() {
            $post_id = isset( $_POST['postidtwo'] ) ? intval( wp_unslash( $_POST['postidtwo'] ) ) : 0;

            if ( ! $post_id ) {
                wp_send_json_error( [ 'message' => __( 'Post ID is missing.', 'fluxtore' ) ] );
            }

            $data = [];

            for ( $i = 1; $i <= 4; $i++ ) {
                $data["meta_discount{$i}"]           = get_post_meta( $post_id, "__fluxtore__order_bump_discount{$i}", true );
                $data["meta_bump_text{$i}"]          = get_post_meta( $post_id, "__fluxtore__order_bump_text{$i}", true );
                $data["meta_bump_price{$i}"]         = get_post_meta( $post_id, "__fluxtore__order_bump_price{$i}", true );
                $data["meta_bump_toggle{$i}"]        = get_post_meta( $post_id, "__fluxtore__order_bump_toggle{$i}", true );
                $data["meta_checked_value{$i}"]      = get_post_meta( $post_id, "ordercheckdata{$i}", true );
                $data["meta_order_bump_productid_{$i}"] = get_post_meta( $post_id, "__fluxtore__order_bump_product{$i}", true );

                if ( ! empty( $data["meta_order_bump_productid_{$i}"] ) ) {
                    $product                               = wc_get_product( $data["meta_order_bump_productid_{$i}"] );
                    $data["meta_order_bump_product_name_{$i}"] = $product ? $product->get_name() : __( 'Product not found', 'fluxtore' );
                } else {
                    $data["meta_order_bump_product_name_{$i}"] = __( 'No product assigned', 'fluxtore' );
                }
            }

            if ( empty( array_filter( $data ) ) ) {
                wp_send_json_error( [ 'message' => __( 'No data found for this post.', 'fluxtore' ) ] );
            }

            wp_send_json_success( [ 'message' => __( 'Data fetched successfully', 'fluxtore' ), 'data' => $data ] );
        }

        private function maybe_update_meta( $post_id, $id_base_check, $order_checkdata ) {
            switch ( $id_base_check ) {
                case 'ordercheckboxdata1':
                case 'ordercheckboxdata2':
                case 'ordercheckboxdata3':
                case 'ordercheckboxdata4':
                    $this->update_meta_if_not_empty( $post_id, $id_base_check, $order_checkdata );
                    break;
            }
        }

        private function maybe_update_product_meta( $post_id, $matched_class, $product_id ) {
            switch ( $matched_class ) {
                case 'add-new_button-data':
                    $this->update_meta_if_not_empty( $post_id, '__fluxtore__order_bump_product1', $product_id );
                    break;
                case 'add-new_button-data2':
                    $this->update_meta_if_not_empty( $post_id, '__fluxtore__order_bump_product2', $product_id );
                    break;
                case 'add-new_button-data3':
                    $this->update_meta_if_not_empty( $post_id, '__fluxtore__order_bump_product3', $product_id );
                    break;
                case 'add-new_button-data4':
                    $this->update_meta_if_not_empty( $post_id, '__fluxtore__order_bump_product4', $product_id );
                    break;
            }
        }

        private function maybe_update_grouped_meta( $post_id, $parent_class, $product_id, $price_value, $discount_price, $order_dump_text, $order_toggle_text, $order_checkdata ) {
            $map = [
                'order_bump-toggle_text'  => 1,
                'Real_price'              => 1,
                'discount_price-p'        => 1,
                'order_bump-toggle_text2' => 2,
                'Real_price2'             => 2,
                'discount_price-p2'       => 2,
                'order_bump-toggle_text3' => 3,
                'Real_price3'             => 3,
                'discount_price-p3'       => 3,
                'order_bump-toggle_text4' => 4,
                'Real_price4'             => 4,
                'discount_price-p4'       => 4,
            ];

            if ( ! isset( $map[ $parent_class ] ) ) {
                return;
            }

            $index = $map[ $parent_class ];

            $this->update_meta_if_not_empty( $post_id, "__fluxtore__order_bump_product{$index}", $product_id );
            $this->update_meta_if_not_empty( $post_id, "__fluxtore__order_bump_price{$index}", $price_value );
            $this->update_meta_if_not_empty( $post_id, "__fluxtore__order_bump_discount{$index}", $discount_price );
            $this->update_meta_if_not_empty( $post_id, "__fluxtore__order_bump_text{$index}", $order_dump_text );
            $this->update_meta_if_not_empty( $post_id, "__fluxtore__order_bump_toggle{$index}", $order_toggle_text );
            $this->update_meta_if_not_empty( $post_id, "ordercheckdata{$index}", $order_checkdata );
        }

        private function update_meta_if_not_empty( $post_id, $meta_key, $meta_value ) {
            if ( '' === $meta_key || null === $meta_value ) {
                return;
            }

            if ( '' !== $meta_value || '0' === $meta_value ) {
                update_post_meta( $post_id, $meta_key, $meta_value );
            }
        }
    }
}

fluXtore_Ajax_Order_Bumps::init();
