<?php
/**
 * Product panel class.
 *
 * @package HBFWC
 */

namespace HBFWC\Admin;

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

use function HBFWC\HBF_WC;

/**
 * Admin product panel class.
 */
class Product_Panel {

	/**
	 * Class construction.
	 * Hook-in method.
	 */
	public function __construct() {
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_accommodation_product_tabs' ) );
		add_action( 'woocommerce_product_data_panels', array( $this, 'add_accommodation_product_panels' ) );
		add_action( 'save_post', array( $this, 'save_panel' ), 10 );
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ), 10 );
	}

	/**
	 * Modify the product data tabs.
	 *
	 * @param array $tabs The tabs.
	 * @return array new tabs set.
	 */
	public function add_accommodation_product_tabs( array $tabs ): array {
		// Accommodation do not need shipping.
		if ( isset( $tabs['shipping'] ) ) {
			$classes                   = $tabs['shipping']['class'];
			$classes[]                 = 'hide_if_accommodation';
			$tabs['shipping']['class'] = $classes;
		}

		$new_tabs = array();
		// General.
		$new_tabs['hbfwc_general_tab'] = array(
			'label'  => esc_html__( 'General', 'hotel-booking-for-woocommerce' ),
			'target' => 'hbfwc_general_product_data',
			'class'  => array( 'show_if_accommodation' ),
		);

		// Rate plans.
		$new_tabs['hbfwc_rateplans_tab'] = array(
			'label'  => esc_html__( 'Price &amp; Rates', 'hotel-booking-for-woocommerce' ),
			'target' => 'hbfwc_rateplans_product_data',
			'class'  => array( 'show_if_accommodation' ),
		);

		// Amenities.
		$new_tabs['hbfwc_amenities_tab'] = array(
			'label'  => esc_html__( 'Amenities', 'hotel-booking-for-woocommerce' ),
			'target' => 'hbfwc_amenities_product_data',
			'class'  => array( 'show_if_accommodation' ),
		);

		$tabs = $new_tabs + $tabs;
		return $tabs;
	}

	/**
	 * The tabs content.
	 *
	 * @return void
	 */
	public function add_accommodation_product_panels() {
		$product = wc_get_product();
		wp_nonce_field( 'hbfwc_save_product_panel', 'hbfwc_product_panel_nonce' );
		include dirname( HBF_WC()->plugin_file ) . '/includes/admin/views/product-general-tab.php';
		include dirname( HBF_WC()->plugin_file ) . '/includes/admin/views/product-rateplans-tab.php';
		include dirname( HBF_WC()->plugin_file ) . '/includes/admin/views/product-amenities-tab.php';
	}

	/**
	 * Save the product data.
	 *
	 * @param int $post_id The current post ID.
	 *
	 * @return void
	 */
	public function save_panel( $post_id ) {
		if ( ! isset( $_POST['hbfwc_product_panel_nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hbfwc_product_panel_nonce'] ) ), 'hbfwc_save_product_panel' )
		) {
			return;
		}

		// Autosaving, bail.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( wp_is_post_revision($post_id) ) {
			return;
		}

		if ( isset( $_POST['product-type'] ) && 'accommodation' !== sanitize_text_field( wp_unslash( $_POST['product-type'] ) ) ) {
			return;
		}

		if ( ! isset( $_POST['_max_adults'] ) ) {
			return;
		}

		$attached_term_ids = array( absint( get_option( 'hbfwc_default_rate_id', 0 ) ) );

		if ( ! empty( $_POST['hbfwc_rate_ids'] ) ) {
			$rates = array();

			foreach ( array_map( 'sanitize_text_field', wp_unslash( $_POST['hbfwc_rate_ids'] ?? [] ) ) as $rate_id ) {
				$rate_id = absint( sanitize_text_field( $rate_id ) );
				// Term is gone? So be it.
				if ( ! get_term_by( 'term_id', $rate_id, 'rate_plan' ) || ! isset( $_POST['hbfwc_rate'][ $rate_id ] ) ) {
					continue;
				}

				foreach ( array_map( 'sanitize_text_field', wp_unslash( $_POST['hbfwc_rate'][ $rate_id ] ) ) as $rate_key => $rate_val ) {
					$rate_val = in_array( $rate_key, array( 'pricing_value', 'pricing_sale_value' ), true ) ? wc_format_decimal( $rate_val, wc_get_price_decimals() ) : $rate_val;
					$rate_val = apply_filters( 'hbfwc_room_saved_rate_item_value', $rate_val, $rate_key, $rate_id );
					$rates[ "rate_{$rate_id}" ][ $rate_key ] = $rate_val;
				}
				$attached_term_ids[] = $rate_id;
			}

			update_post_meta( $post_id, '_hbfwc_rate_plans', $rates );
		} else {

			delete_post_meta( $post_id, '_hbfwc_rate_plans' );
		}

		wp_set_post_terms( $post_id, $attached_term_ids, 'rate_plan' );

		$def_prices = array( '_hbfwc_regular_price', '_hbfwc_sale_price' );

		foreach ( $def_prices as $dp ) {
			$dp_name = str_replace( '_hbfwc', '', $dp );
			$dp_val  = sanitize_text_field( wp_unslash( $_POST[ $dp ] ?? '' ) );

			if ( ! empty( $dp_val ) ) {
				update_post_meta( $post_id, $dp_name, wc_format_decimal( $dp_val, wc_get_price_decimals() ) );
				if ( '_regular_price' === $dp_name ) {
					update_post_meta( $post_id, '_price', wc_format_decimal( $dp_val, wc_get_price_decimals() ) );
				}
			} else {
				delete_post_meta( $post_id, $dp_name );
			}
		}

		$general_options = array( '_allotment', '_min_stay', '_max_adults', '_max_children', '_no_of_beds', '_room_size' );

		foreach ( $general_options as $gen_ops ) {
			if ( ! empty( $_POST[ $gen_ops ] ) ) {
				update_post_meta( $post_id, $gen_ops, sanitize_text_field( wp_unslash( $_POST[ $gen_ops ] ) ) );
			} else {
				delete_post_meta( $post_id, $gen_ops );
			}
		}

		// Amenities terms.
		$amenities   = isset( $_POST['amenity'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['amenity'] ) ) : array();
		$amenity_ids = array();
		if ( $amenities ) {
			foreach ( $amenities as $amenity ) {
				$amenity_ids[] = absint( $amenity );
			}
		}

		if ( ! empty( $amenity_ids ) ) {
			wp_set_post_terms( $post_id, $amenity_ids, 'amenities' );
		} else {
			$used_ams = wp_get_post_terms( $post_id, 'amenities', array( 'fields' => 'ids' ) );
			if ( $used_ams ) {
				wp_remove_object_terms( $post_id, $used_ams, 'amenities' );
			}
		}
	}

	/**
	 * Enqueue some required js and css files.
	 *
	 * @param string $hook Current admin hook.
	 */
	public function admin_scripts( $hook ) {
		if ( ( 'post.php' === $hook && isset( $_GET['post'] ) && wc_get_product( absint( wp_unslash( $_GET['post'] ) ) ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			|| ( 'post-new.php' === $hook && isset( $_GET['post_type'] ) && 'product' === $_GET['post_type'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			wp_enqueue_style( 'hbfwc-fontawesome-6', HBF_WC()->plugin_url() . '/assets/css/libs/font-awesome-6.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-fontawesome-6-brands', HBF_WC()->plugin_url() . '/assets/css/libs/font-awesome-6-brands.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-ionicons', HBF_WC()->plugin_url() . '/assets/css/libs/ionicons.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-themify', HBF_WC()->plugin_url() . '/assets/css/libs/themify-icons.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-panel', HBF_WC()->plugin_url() . '/assets/client/admin/product-panel.css', array(), HBF_WC()->version, 'all' );

			wp_enqueue_script( 'hbfwc-panel', HBF_WC()->plugin_url() . '/assets/client/admin/js/panel.js', array( 'jquery', 'wp-i18n' ), HBF_WC()->version, array( 'in_footer' => true ) );
			$params = array(
				'ajax_url'    => admin_url( 'admin-ajax.php' ),
				'new_amenity' => wp_create_nonce( 'create-new-amenity' ),
			);
			wp_localize_script( 'hbfwc-panel', 'hbfwc_options', $params );

		} elseif ( isset( $_GET['page'] ) && 'availability' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			wp_enqueue_style( 'hbfwc-availability', HBF_WC()->plugin_url() . '/assets/client/admin/availability.css', array(), HBF_WC()->version, 'all' );
			wp_enqueue_style( 'hbfwc-daterangepicker', HBF_WC()->plugin_url() . '/assets/css/daterangepicker.css', array(), '3.14.1', 'screen' );

			wp_enqueue_script( 'hbfwc-daterangepicker', HBF_WC()->plugin_url() . '/assets/js/daterangepicker.min.js', array( 'moment' ), '3.14.1', array( 'in_footer' => true ) );
			wp_enqueue_script( 'hbfwc-availability', HBF_WC()->plugin_url() . '/assets/client/admin/js/availability.js', array( 'hbfwc-daterangepicker' ), HBF_WC()->version, array( 'in_footer' => true ) );
			$params = array(
				'post_id'            => ( isset( $_GET['accommodation_id'] ) ? absint( wp_unslash( $_GET['accommodation_id'] ) ) : 0 ), // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				'ajax_url'           => admin_url( 'admin-ajax.php' ),
				'modify_qty'         => wp_create_nonce( 'update-quantity' ),
				'modify_status'      => wp_create_nonce( 'update-status' ),
				'modify_rate_status' => wp_create_nonce( 'update-rate-status' ),
				'modify_price'       => wp_create_nonce( 'update-room-price' ),
				'bulk_update'        => wp_create_nonce( 'run-bulk-update' ),
				'thousand_sep'       => wc_get_price_thousand_separator(),
			);
			wp_localize_script( 'hbfwc-availability', 'hbfwc_admin_availability', $params );

		} elseif ( isset( $_GET['page'] ) && 'amenities' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			wp_enqueue_style( 'hbfwc-fontawesome-6', HBF_WC()->plugin_url() . '/assets/css/libs/font-awesome-6.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-fontawesome-6-brands', HBF_WC()->plugin_url() . '/assets/css/libs/font-awesome-6-brands.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-ionicons', HBF_WC()->plugin_url() . '/assets/css/libs/ionicons.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-themify', HBF_WC()->plugin_url() . '/assets/css/libs/themify-icons.min.css', array(), '1.0.0', 'screen' );
			wp_enqueue_style( 'hbfwc-admin-amenities', HBF_WC()->plugin_url() . '/assets/client/admin/amenities.css', array(), HBF_WC()->version, 'all' );

			wp_enqueue_script( 'hbfwc-amenity', HBF_WC()->plugin_url() . '/assets/client/admin/js/amenity.js', array( 'jquery' ), HBF_WC()->version, array( 'in_footer' => true ) );

		} elseif ( isset( $_GET['page'] ) && 'rate_plans' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			wp_enqueue_script( 'hbfwc-rate-plans', HBF_WC()->plugin_url() . '/assets/client/admin/js/rate-plans.js', array( 'jquery' ), HBF_WC()->version, array( 'in_footer' => true ) );
		} elseif ( ( 'post.php' === $hook && isset( $_GET['post'] ) && 'booking_addon' === get_post_type( absint( wp_unslash( $_GET['post'] ) ) ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			|| ( 'post-new.php' === $hook && isset( $_GET['post_type'] ) && 'booking_addon' === $_GET['post_type'] ) ) {

			wp_enqueue_script( 'select2' );
			wp_enqueue_style( 'select2' );

			// WooCommerce enhanced select
			wp_enqueue_script( 'wc-enhanced-select' );
			
			wp_enqueue_style( 'woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css' );
			wp_enqueue_style( 'hbfwc-booking-addon', HBF_WC()->plugin_url() . '/assets/client/admin/booking-addon.css', array(), HBF_WC()->version, 'all' );
			wp_enqueue_script( 'hbfwc-booking-addon', HBF_WC()->plugin_url() . '/assets/client/admin/js/booking-addon.js', array( 'jquery', 'jquery-tiptip' ), HBF_WC()->version, array( 'in_footer' => true ) );
			$params = array(
				'thousand_sep' => wc_get_price_thousand_separator(),
				'decimal_sep'  => wc_get_price_decimal_separator()
			);
			wp_localize_script( 'hbfwc-booking-addon', 'hbfwc_admin_booking_addon', $params );
		} else if ( isset( $_GET['page'] ) && sanitize_text_field( wp_unslash($_GET['page']) ) === 'wc-orders' && isset( $_GET['action'] ) && sanitize_text_field( wp_unslash($_GET['action']) ) === 'edit' ) {
			wp_enqueue_style( 'hbfwc_woocommerce_order_styles', HBF_WC()->plugin_url() . '/assets/client/admin/wc-order.css' );
		} else if ( isset( $_GET['page'] ) && sanitize_text_field( wp_unslash($_GET['page']) ) === 'wc-settings' && isset( $_GET['tab'] ) && sanitize_text_field( wp_unslash($_GET['tab']) ) === 'hbfwc' ) {
			wp_enqueue_style( 'hbfwc-settings', HBF_WC()->plugin_url() . '/assets/client/admin/settings.css', array(), HBF_WC()->version, 'all' );
		}
	}
}

new Product_Panel();
