<?php

namespace Ilabs\Inpost_International\Backend;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly.


use Exception;
use Ilabs\Inpost_International\Helpers\Helper;
use Ilabs\Inpost_International\API\API;

/**
 * Ajax_Handler
 */
class Ajax_Handler {

	/**
	 * Helper instance for utility functions.
	 *
	 * @since 1.0.0
	 * @var Helper An instance of the Helper class that provides utility methods.
	 */
	private $helper;


	/**
	 * Constructor
	 */
	public function __construct() {

		$this->helper = Helper::init();

		add_action( 'wp_ajax_inpost_international', array( $this, 'ajax_callback' ) );
		
		add_action( 'wp_ajax_inpost_intl_save_locker_to_wc_session', array( $this, 'save_locker_to_wc_session' ) );
		add_action( 'wp_ajax_nopriv_inpost_intl_save_locker_to_wc_session', array( $this, 'save_locker_to_wc_session' ) );
	}

	/**
	 * Ajax callbacks
	 *
	 * @return void
	 */
	public function ajax_callback() {

		check_ajax_referer( 'inpost_international_ajax', 'security' );

		if ( ! empty( $_POST['inpost_intl_action'] ) ) {
			$action_type = sanitize_text_field( wp_unslash( $_POST['inpost_intl_action'] ) );
			$order_id    = null;
			if ( ! empty( $_POST['inpost_intl_action'] ) && ! empty( $_POST['order_id'] ) ) {
				$order_id = sanitize_text_field( wp_unslash( $_POST['order_id'] ) );
			}

			if ( 'create_pickup_order' === $action_type ) {

				$total_weight    = 0;
				$total_shipments = 0;
				$pickup_time     = array();
				if ( ! empty( $_POST['total_weight'] ) ) {
					$total_weight = sanitize_text_field( wp_unslash( $_POST['total_weight'] ) );
				}
				if ( ! empty( $_POST['total_shipments'] ) ) {
					$total_shipments = sanitize_text_field( wp_unslash( $_POST['total_shipments'] ) );
				}
				if ( ! empty( $_POST['pickup_time'] ) ) {
					$pickup_time = map_deep( wp_unslash( $_POST['pickup_time'] ), 'sanitize_text_field' );

				}
				if ( ! empty( $_POST['selected_dpoint'] ) ) {
					$selected_dpoint = sanitize_text_field( wp_unslash( $_POST['selected_dpoint'] ) );
				} else {
					$selected_dpoint = '0';
				}

				$backend = new Backend();

				$data                  = array();
				$data['address']       = $this->helper->get_dispatch_point_selected( $selected_dpoint );
				$data['contactPerson'] = $backend->get_sender_data();
				$data['pickupTime']    = $pickup_time['pickup_time'];
				$data['volume']        = array(
					'itemType'    => 'PARCEL',
					'count'       => $total_shipments,
					'totalWeight' => array(
						'amount' => $total_weight,
						'unit'   => 'KG',
					),
				);
				$data['references']    = array(
					'custom' => array(
						'invoiceNumber' => '',
					),
				);

				$api      = new Api();
				$response = $api->create_pickup_order( $data );

				wp_send_json_success( $response );
			}

			if ( 'get_cutoff_pickup_time' === $action_type ) {

				if ( ! empty( $_POST['postal_code'] ) ) {
					$postal_code = sanitize_text_field( wp_unslash( $_POST['postal_code'] ) );
					$api         = new Api();
					$response    = $api->get_cutoff_pickup_time( $postal_code );
					header( 'Content-Type: application/json' );
					if ( empty( $response ) ) {
						$response = array(
							'error'         => 1,
							'error_details' => 'Something went wrong',
						);
						echo wp_json_encode( $response );
					} else {
						echo wp_json_encode( $response );
					}

					wp_die();
				}
			}

			if ( 'product_table_update_product' === $action_type ) {
				$this->update_product_meta();
			}

			if ( 'inpost_intl_disconnect' === $action_type ) {
				$auth_settings = get_option( 'inpost_international_settings_auth' );
				if ( ! empty( $auth_settings['api_token'] ) ) {
					unset( $auth_settings['api_token'] );
				}
				if ( ! empty( $auth_settings['api_token_expiration'] ) ) {
					unset( $auth_settings['api_token_expiration'] );
				}
				if ( ! empty( $auth_settings['api_refresh_token'] ) ) {
					unset( $auth_settings['api_refresh_token'] );
				}
				if ( ! empty( $auth_settings['api_refresh_token_expiration'] ) ) {
					unset( $auth_settings['api_refresh_token_expiration'] );
				}
				update_option( 'inpost_international_settings_auth', $auth_settings );
				wp_send_json_success( 'OK' );
			}

			if ( 'inpost_intl_enabled_only_for_admins' === $action_type ) {
				$enabled = false;
				if ( ! empty( $_POST['enabled'] ) ) {
					$enabled = true;
				}
				update_option( 'inpost_international_only_for_admins', $enabled );
				wp_send_json_success( 'OK' );
			}

			if ( 'inpost_intl_allow_all' === $action_type ) {
				$products_table_section_settings = get_option( 'inpost_international_settings_products' );
				if ( ! $products_table_section_settings ) {
					$products_table_section_settings = array();
				}
				if ( ! empty( $_POST['allow_all'] ) ) {
					$products_table_section_settings['allow_all'] = 1;
				} else {
					$products_table_section_settings['allow_all'] = null;
				}
				update_option( 'inpost_international_settings_products', $products_table_section_settings );
				wp_send_json_success( 'OK' );
			}

			if ( 'inpost_international_get_status' === $action_type ) {
				if ( ! empty( $_POST['tracking_number'] ) ) {
					$tracking_number = sanitize_text_field( wp_unslash( $_POST['tracking_number'] ) );
					$api             = new Api();
					$response        = $api->get_tracking_data( $tracking_number );
					header( 'Content-Type: application/json' );
					if ( empty( $response ) ) {
						$response = array(
							'error'         => 1,
							'error_details' => 'Something went wrong',
						);
						echo wp_json_encode( $response );
					} else {
						echo wp_json_encode( $response );
					}
					wp_die();
				}
			}

			if ( 'inpost_intl_bulk_create_labels' === $action_type ) {

				$uuid = '';
				if ( ! empty( $_POST['uuid'] ) ) {
					$uuid = sanitize_text_field( wp_unslash( $_POST['uuid'] ) );
				}

				$response = $this->handle_get_label_ajax( $order_id, $uuid );

				header( 'Content-Type: application/json' );
				if ( empty( $response ) ) {
					$response = array(
						'error'         => 1,
						'error_details' => 'Something went wrong',
					);

				}
				echo wp_json_encode( $response );

				wp_die();

			}

			if ( $order_id && 'inpost_intl_bulk_create_shipments' === $action_type ) {

				if ( ! $this->helper->wc_order_package_created( $order_id ) ) {
					$backend                   = new Backend();
					$create_order_request_data = $backend->prepare_shipment_for_api( $order_id );
					$api                       = new Api();
					$response                  = $api->create_package( $create_order_request_data, $order_id );

					if ( ! empty( $response['status'] ) || ! empty( $response['trackingNumber'] ) ) {

						$response = array(
							'status'          => 'ok',
							'tracking_number' => $response['trackingNumber'],
							'uuid'            => $response['uuid'],
						);

					} else {
						// just send response to extract errors.
						if ( ! $response ) {
							$response = array(
								'error'         => 1,
								'error_details' => 'Something went wrong',
							);
						} elseif ( is_array( $response ) ) {
							$response['error'] = 1;
						}
					}

					header( 'Content-Type: application/json' );
					echo wp_json_encode( $response );
					wp_die();
				}
			}

			if ( 'inpost_international_get_label' === $action_type ) {

				$uuid = '';
				if ( ! empty( $_POST['uuid'] ) ) {
					$uuid = sanitize_text_field( wp_unslash( $_POST['uuid'] ) );
				}
				$response = $this->handle_get_label_ajax( $order_id, $uuid );

				header( 'Content-Type: application/json' );
				if ( empty( $response ) ) {
					$response = array(
						'error'         => 1,
						'error_details' => 'Something went wrong',
					);
					echo wp_json_encode( $response );
				} else {
					echo wp_json_encode( $response );
				}
				wp_die();

			}
			if ( $order_id && 'inpost_international_create_package' === $action_type ) {
				$backend                   = new Backend();
				$create_order_request_data = $backend->prepare_shipment_for_api( $order_id );

				$api      = new Api();
				$response = $api->create_package( $create_order_request_data, $order_id );

				if ( ! empty( $response['status'] ) || ! empty( $response['trackingNumber'] ) ) {
					// change whole metabox.
					header( 'Content-Type: text/html' );
					$backend->order_metabox_content( $order_id, $response );

				} else {
					// just send response to extract errors.
					if ( ! $response ) {
						$response = array(
							'error'         => 1,
							'error_details' => 'Something went wrong',
						);
					} elseif ( is_array( $response ) ) {
						$response['error'] = 1;
					}

					header( 'Content-Type: application/json' );
					echo wp_json_encode( $response );
				}

				wp_die();

			}
		}
	}

	/**
	 * Handle ajax to get label
	 *
	 * @param mixed  $order_id $order_id.
	 * @param string $uuid $uuid.
	 *
	 * @return array
	 */
	public function handle_get_label_ajax( $order_id, $uuid = '' ) {

		$response = array();

		$api = new Api();

		if ( ! empty( $uuid ) ) {
			$response = $api->get_label( $uuid );

		} else {

			$order = wc_get_order( $order_id );
			if ( $order && ! is_wp_error( $order ) ) {
				$package_meta = $order->get_meta( 'inpost_international_package' );
				if ( ! empty( $package_meta ) ) {
					try {
						$package_data = json_decode( $package_meta, true );
						$package_data = ! empty( $package_data['api_response'] ) ? $package_data : array();
						if ( ! empty( $package_data['api_response']['uuid'] ) ) {
							$uuid     = $package_data['api_response']['uuid'];
							$response = $api->get_label( $uuid );
						}
					} catch ( Exception $e ) {
						// save to log.
						inpost_intl_core()->inpost_logger(
							'Inpost International: error on reading package in order meta',
							__METHOD__ . ': ' . __LINE__,
							$e->getMessage(),
							'inpost-international-order-meta-' . $order_id,
							'debug'
						);

						$response = array(
							'error'       => 1,
							'error_title' => $e->getMessage(),
						);
					}
				}
			}
		}

		return $response;
	}


	/**
	 * Update product meta data
	 *
	 * @return void
	 */
	public function update_product_meta() {

		check_ajax_referer( 'inpost_international_ajax', 'security' );

		if ( isset( $_POST['product_data'] ) && is_array( $_POST['product_data'] ) && isset( $_POST['product_id'] ) ) {
			$product_id = sanitize_text_field( wp_unslash( $_POST['product_id'] ) );

			$wc_product = wc_get_product( $product_id );

			if ( ! $wc_product || is_wp_error( $wc_product ) ) {
				$error = sprintf(
				/* translators: %s: product ID */
					esc_html__( 'Product #%s does not exist', 'inpost-international' ),
					$product_id
				);
				wp_send_json( array( 'error' => $error ) );
				wp_die();
			}

			$template_meta_key        = 'inpost_international_parcel_template';
			$allowed_methods_meta_key = 'inpost_international_shipping_methods_allowed';
			if ( isset( $_POST['product_data']['allowed_methods'] ) ) {
				$allowed_methods = array_map( 'sanitize_text_field', wp_unslash( $_POST['product_data']['allowed_methods'] ) );
				update_post_meta( $product_id, $allowed_methods_meta_key, $allowed_methods );
			} else {
				$allowed_methods = array();
				update_post_meta( $product_id, $allowed_methods_meta_key, $allowed_methods );
			}
			if ( isset( $_POST['product_data']['template'] ) && ! empty( $_POST['product_data']['template'] ) ) {
				$template = sanitize_text_field( wp_unslash( $_POST['product_data']['template'] ) );
				update_post_meta( $product_id, $template_meta_key, $template );
			}
		}

		if ( isset( $_POST['all_data'] ) ) {
			$data_return = map_deep( wp_unslash( $_POST['all_data'] ), 'sanitize_text_field' );

		} else {
			wp_send_json( array( 'error' => esc_html__( 'Error in data', 'inpost-international' ) ) );
		}

		echo wp_json_encode( $data_return );
		wp_die();
	}



    public function save_locker_to_wc_session() {

        check_ajax_referer( 'inpost_intl_frontend', 'security' );

        $locker = ! empty( $_POST['inpost_intl_locker']) ? sanitize_text_field( wp_unslash(  $_POST['inpost_intl_locker'] ) )  : null;

        if( $locker ) {

            if ( is_object(  WC() ) && property_exists( WC(), 'session' ) ) {
                WC()->session->set( 'inpost_intl_locker', $locker );
                wp_send_json_success('Locker saved to session');
            } else {
                wp_send_json_error('WC session not available');

            }

        } else {
            wp_send_json_error( array( 'message' => 'Empty locker' ) );
        }

        wp_die();
    }


    
}
