<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://conicplex.com
 * @since      1.0.0
 *
 * @package    BDPCP
 * @subpackage BDPCP/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    BDPCP
 * @subpackage BDPCP/admin
 * @author     ConicPlex <hello@conicplex.com>
 */
class BDPCP_Admin
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles($hook)
	{
		// Enqueue admin styles 
		if ($hook === 'plugins.php') {
			wp_enqueue_style($this->plugin_name . '-deactivation', plugin_dir_url(__FILE__) . 'css/bdpcp-deactivation.css', array(), $this->version, 'all');
		}
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts($hook)
	{
		// Enqueue admin script
		if ($hook === 'plugins.php') {
			wp_enqueue_script($this->plugin_name . '-deactivation', plugin_dir_url(__FILE__) . 'js/bdpcp-deactivation.js', array('jquery'), $this->version, false);

			// Localize the script for ajax data
			wp_localize_script($this->plugin_name . '-deactivation', 'bdpcp_deactivation', array(
				'nonce' => wp_create_nonce('bdpcp_deactivation_nonce_action'),
			));
		}
	}

	public function bdpcp_init_handle()
	{
		require_once BDPCP_ROOT_PATH . 'admin/class-bdpcp-bookable-product-type.php';
	}

	public function bdpcp_product_type_selector_handle($types)
	{
		$types['bdpcp_bookable_product'] = 'Bookable Product by ConicPlex';
		return $types;
	}

	public function bdpcp_woocommerce_product_data_tabs_handle($tabs)
	{
		$tabs['bdpcp_bookable_product'] = [
			'label'    => 'Bookable Options by ConicPlex',
			'target'   => 'bdpcp_bookable_product_options_product_data',
			'class'    => ['show_if_bdcp_bookable_product'],
			'priority' => 21,
		];
		return $tabs;
	}

	public function bdpcp_woocommerce_product_data_panels_handle()
	{
		include BDPCP_ROOT_PATH . 'admin/partials/bdpcp-admin-display.php';
	}

	public function bdpcp_woocommerce_product_class_handle($className, $product_type)
	{
		if ($product_type == 'bdpcp_bookable_product') {
			$className = 'WC_Product_BDPCPBookableProduct';
		}
		return $className;
	}

	public function bdpcp_woocommerce_admin_process_product_object_handle($product)
	{
		if ($product->get_type() === 'bdpcp_bookable_product') {

			if (!isset($_POST['bdpcp_admin_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['bdpcp_admin_nonce'])), 'bdpcp_admin_nonce')) {
				return;
			}

			$setting_booking_everyday = isset($_POST['bdpcp_booking_everyday']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_everyday'])) : 0;
			$setting_booking_is_manual_time_slot = isset($_POST['bdpcp_booking_is_manual_time_slot']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_is_manual_time_slot'])) : 0;

			$setting_booking_dates = isset($_POST['bdpcp_booking_dates']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_dates'])) : null;
			$setting_booking_week_off = isset($_POST['bdpcp_booking_week_off'])
				? array_map('intval', array_map('sanitize_text_field', wp_unslash($_POST['bdpcp_booking_week_off'])))
				: [];
			$time_slots = isset($_POST['bdpcp_time_slots']) ? array_map('sanitize_text_field', wp_unslash($_POST['bdpcp_time_slots'])) : [];
			$total_slots = isset($_POST['bdpcp_total_slots']) ? array_map('sanitize_text_field', wp_unslash($_POST['bdpcp_total_slots'])) : [];
			$duration = isset($_POST['bdpcp_duration']) ? floatval($_POST['bdpcp_duration']) : 0;
			$base_price = isset($_POST['bdpcp_base_price']) ? floatval($_POST['bdpcp_base_price']) : 0;
			$fixed_base_fee = isset($_POST['bdpcp_fixed_base_fee']) ? floatval($_POST['bdpcp_fixed_base_fee']) : 0;

			$unit_type = isset($_POST['bdpcp_unit_type']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_unit_type'])) : '';

			$people_name = isset($_POST['bdpcp_people_name']) ? array_map('sanitize_text_field', wp_unslash($_POST['bdpcp_people_name'])) : [];
			$people_price = isset($_POST['bdpcp_people_price']) ? array_map('floatval', $_POST['bdpcp_people_price']) : [];
			$people_min_slot = isset($_POST['bdpcp_people_min_slot']) ? array_map('intval', $_POST['bdpcp_people_min_slot']) : [];
			$people_max_slot = isset($_POST['bdpcp_people_max_slot']) ? array_map('intval', $_POST['bdpcp_people_max_slot']) : [];

			$hours = isset($_POST['bdpcp_hours']) ? intval($_POST['bdpcp_hours']) : 0;
			$hour_price = isset($_POST['bdpcp_hour_price']) ? floatval($_POST['bdpcp_hour_price']) : 0;
			$hour_min_slot = isset($_POST['bdpcp_hour_min_slot']) ? intval($_POST['bdpcp_hour_min_slot']) : 0;
			$hour_max_slot = isset($_POST['bdpcp_hour_max_slot']) ? intval($_POST['bdpcp_hour_max_slot']) : 0;
			$hour_editable = isset($_POST['bdpcp_hour_editable']) ? intval($_POST['bdpcp_hour_editable']) : 0;

			$start_time = isset($_POST['bdpcp_booking_start_time']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_start_time'])) : '';
			$end_time = isset($_POST['bdpcp_booking_end_time']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_end_time'])) : '';
			$buffer_time = isset($_POST['bdpcp_booking_buffer_time']) ? intval(wp_unslash($_POST['bdpcp_booking_buffer_time'])) : 0;
			$time_duration = isset($_POST['bdpcp_booking_time_duration']) ? intval(wp_unslash($_POST['bdpcp_booking_time_duration'])) : 0;

			$time_duration_type = isset($_POST['bdpcp_time_duration_type']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_time_duration_type'])) : '';
			$buffer_time_type = isset($_POST['bdpcp_buffer_time_type']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_buffer_time_type'])) : '';
			$max_slot_per_time = isset($_POST['bdpcp_max_slot_per_time']) ? intval(wp_unslash($_POST['bdpcp_max_slot_per_time'])) : 0;
			$bdpcp_is_multiple_time_select = isset($_POST['bdpcp_is_multiple_time_select']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_is_multiple_time_select'])) : 0;

			$booking_day_off = isset($_POST['bdpcp_booking_day_off']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_day_off'])) : '';

			$start_date = '';
			$end_date = '';
			if (!empty($setting_booking_dates)) {
				$setting_booking_dates = explode(' to ', $setting_booking_dates);
				$start_date = gmdate('Y-m-d', strtotime($setting_booking_dates[0]));
				$end_date = gmdate('Y-m-d', strtotime($setting_booking_dates[1]));
			}

			$price_data = [];
			if ($unit_type == 'hour') {
				$price_data['hour'] = [
					'hours' => $hours,
					'price' => $hour_price,
					'min_slot' => $hour_min_slot,
					'max_slot' => $hour_max_slot,
					'editable' => $hour_editable,
				];
			} else if ($unit_type == 'people') {
				if (!empty($people_name)) {
					foreach ($people_name as $key => $val) {
						if (!empty($val)) {
							$price_data[$val] = [
								'price' => $people_price[$key],
								'min_slot' => $people_min_slot[$key],
								'max_slot' => $people_max_slot[$key],
							];
						}
					}
				}
			}

			$slot_data = [];
			if (empty($setting_booking_is_manual_time_slot)) {
				$start_time = gmdate('H:i', strtotime($start_time));
				$end_time = gmdate('H:i', strtotime($end_time));
			} else {
				foreach ($time_slots as $key => $val) {
					$slot_data[$val] = [
						'total_slot' => $total_slots[$key],
					];
				}
				$start_time = '';
				$end_time = '';
			}

			$booking_day_off = explode(', ', $booking_day_off);

			$product->update_meta_data('_bdcp_booking_everyday', $setting_booking_everyday);
			$product->update_meta_data('_bdcp_start_date', $start_date);
			$product->update_meta_data('_bdcp_end_date', $end_date);
			$product->update_meta_data('_bdcp_time_slots', $slot_data);
			$product->update_meta_data('_bdcp_booking_week_off', $setting_booking_week_off);
			$product->update_meta_data('_bdcp_duration', $duration);
			$product->update_meta_data('_bdcp_base_price', $base_price);
			$product->update_meta_data('_bdcp_fixed_base_fee', $fixed_base_fee);
			$product->update_meta_data('_bdcp_unit_type', $unit_type);
			$product->update_meta_data('_bdcp_price_details', $price_data);
			$product->update_meta_data('_price', $base_price);
			$product->update_meta_data('_sale_price', $base_price);
			$product->update_meta_data('_bdcp_is_manual_time_slot', $setting_booking_is_manual_time_slot);
			$product->update_meta_data('_bdcp_start_time', $start_time);
			$product->update_meta_data('_bdcp_end_time', $end_time);
			$product->update_meta_data('_bdcp_buffer_time', $buffer_time);
			$product->update_meta_data('_bdcp_time_duration', $time_duration);
			$product->update_meta_data('_bdcp_time_duration_type', $time_duration_type);
			$product->update_meta_data('_bdcp_buffer_time_type', $buffer_time_type);
			$product->update_meta_data('_bdcp_max_slot_per_time', $max_slot_per_time);
			$product->update_meta_data('_bdcp_is_multiple_time_select', $bdpcp_is_multiple_time_select);
			$product->update_meta_data('_bdcp_booking_day_off', $booking_day_off);
		}
	}

	public function bdpcp_woocommerce_before_order_itemmeta_handle($item_id, $item, $product)
	{

		$order = wc_get_order($item->get_order_id());
		if ($order && !empty($order->get_meta('_bdcp_order'))) {

			$setting_price_details = $order->get_meta('_bdcp_price_details');

			$booking_date = $order->get_meta('_bdcp_booking_date');
			$booking_times = $order->get_meta('_bdcp_booking_time', false);
			$type_count = $order->get_meta('_bdcp_unit_type_count');

			$html = '<div style="font-size: 12px;">';
			$html .= '<div>Date: ' . gmdate('d-m-Y', strtotime($booking_date)) . '</div>';
			foreach ($booking_times as $booking_time) {
				$html .= '<div>Time: ' . gmdate('h:i A', strtotime($booking_time->value)) . '</div>';
			}
			if (!empty($type_count)) {
				foreach ($type_count as $key => $value) {
					$type_price = $setting_price_details[$key];
					$html .= '<div>' . $value . ' ' . ucfirst($key) . ' × ' . wc_price($type_price['price']) . (count($booking_times) > 1 ? ' × ' . count($booking_times) . ' Times' : '') . ' = ' . wc_price($value * $type_price['price'] * count($booking_times)) . '</div>';
				}
			}
			$html .= '</div>';
			echo wp_kses_post($html);
		}
	}

	public function bdpcp_admin_menu_handle()
	{
		$menu_icon_path = BDPCP_ROOT_PATH . 'assets/bdpcp-menu-icon.svg';

		if (file_exists($menu_icon_path)) {
			$menu_icon = 'data:image/svg+xml;base64,' . base64_encode(file_get_contents($menu_icon_path));
		} else {
			$menu_icon = 'dashicons-calendar-alt'; // Fallback to a default WordPress icon
		}

		add_menu_page(
			_x('BookingDaddy Pro', 'Page Title', 'bookingdaddy-pro'),
			_x('BookingDaddy Pro', 'Menu Name', 'bookingdaddy-pro'),
			'manage_options',
			'bookingdaddy-pro',
			array($this, 'bdpcp_orders_page'),
			$menu_icon,
			40
		);

		add_submenu_page(
			'bookingdaddy-pro',
			_x('Booking - BookingDaddy Pro', 'Page Title', 'bookingdaddy-pro'),
			_x('Booking', 'Sub Menu Name', 'bookingdaddy-pro'),
			'manage_options',
			'bookingdaddy-pro',
			array($this, 'bdpcp_orders_page'),
		);

		add_submenu_page(
			'bookingdaddy-pro',
			_x('Settings - BookingDaddy Pro', 'Page Title', 'bookingdaddy-pro'),
			_x('Settings', 'Sub Menu Name', 'bookingdaddy-pro'),
			'manage_options',
			'bdpcp-settings',
			array($this, 'bdpcp_setting_page'),
		);
	}

	public function bdpcp_setting_page()
	{
		include_once BDPCP_ROOT_PATH . 'admin/partials/bdpcp-settings-display.php';
	}

	public function bdpcp_orders_page()
	{
		include_once BDPCP_ROOT_PATH . 'admin/partials/bdpcp-orders-display.php';
	}

	function register_elementor_widget($widgets_manager)
	{

		// Check if Elementor plugin is installed and activated
		if (!did_action('elementor/loaded')) {
			add_action('admin_notices', function () {

				$message = esc_html__('Kindly install and activate the Elementor plugin to display Booxos Shop Connect products.', 'booxos-shop-connect');

				printf('<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', esc_html($message));
			});
			return false;
		}

		require_once BDPCP_ROOT_PATH . 'admin/class-bdpcp-admin-elementor-widget.php';

		$widgets_manager->register(new \BDPCP_Product_Widget([], ['plugin_name' => $this->plugin_name, 'version' => $this->version]));
	}
}
