<?php

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

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

	/**
	 * 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 the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

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

		add_shortcode('bookingdaddy-pro', array($this, 'bookingdaddy_display'));
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{
		// wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/bdpcp-public.css', array(), $this->version, 'all');

		wp_register_style($this->plugin_name . '-elementor', BDPCP_ROOT_URL . 'public/css/bdpcp-public.css', array(), $this->version, 'all');
		wp_register_style($this->plugin_name . '-flatpickr-elementor', BDPCP_ROOT_URL . 'public/css/flatpickr.min.css', array(), $this->version, 'all');
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{
		wp_register_script($this->plugin_name . '-elementor', BDPCP_ROOT_URL . 'public/js/bdpcp-public.js', array('jquery'), $this->version, false);
		// wp_localize_script($this->plugin_name . '-elementor', 'bdpcp_object', array(
		// 	'ajaxurl' => admin_url('admin-ajax.php'),
		// 	'is_multiple_time_select' => $bdpcp_is_multiple_time_select,
		// 	'booking_week_off' => $bdpcp_booking_week_off,
		// 	'start_date' => gmdate('d-m-Y', strtotime($bdpcp_start_date)),
		// 	'end_date' => gmdate('d-m-Y', strtotime($bdpcp_end_date)),
		// 	'booking_everyday' => $bdpcp_booking_everyday,
		// 	'right_arrow' => BDPCP_ROOT_URL . 'public/images/right-arrow.svg',
		// 	'max_slot_per_time' => $bdpcp_max_slot_per_time,
		// 	'nonce' => wp_create_nonce('bdpcp_nonce_action'),
		// 	'booking_day_off' => $bdpcp_booking_day_off,
		// ));
		wp_register_script($this->plugin_name . '-flatpickr-elementor', BDPCP_ROOT_URL . 'public/js/flatpickr.js', array('jquery'), $this->version, false);
	}

	function bdpcp_count_amount_handle()
	{
		check_ajax_referer('bdpcp_nonce_action', 'nonce');

		$current_date_time = gmdate('d-m-Y H:i:s');
		$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
		$booking_date = isset($_POST['booking_date']) ? sanitize_text_field(wp_unslash($_POST['booking_date'])) : '';
		$booking_time = isset($_POST['booking_time']) ? (array)json_decode(sanitize_text_field(wp_unslash($_POST['booking_time'])), true) : [];
		$booking_date = gmdate('Y-m-d', strtotime($booking_date));

		$product = wc_get_product($product_id);
		$meta_keys = [
			'_bdcp_time_slots',
			'_bdcp_price_details',
			'_bdcp_is_manual_time_slot',
			'_bdcp_start_time',
			'_bdcp_end_time',
			'_bdcp_buffer_time',
			'_bdcp_time_duration',
			'_bdcp_time_duration_type',
			'_bdcp_buffer_time_type',
			'_bdcp_base_price',
			'_bdcp_fixed_base_fee',
			'_bdcp_unit_type',
			'_bdcp_max_slot_per_time'
		];
		$meta_data = array_map(fn($key) => $product->get_meta($key), $meta_keys);
		list(
			$time_slots,
			$price_details,
			$is_manual_time_slot,
			$start_time,
			$end_time,
			$buffer_time,
			$time_duration,
			$time_duration_type,
			$buffer_time_type,
			$base_price,
			$fixed_base_fee,
			$unit_type,
			$max_slot_per_time
		) = $meta_data;
		ksort($time_slots);

		$people_type_count = isset($_POST['people_type_count']) && is_array($_POST['people_type_count'])
			? map_deep(wp_unslash($_POST['people_type_count']), 'sanitize_text_field')
			: [];

		$bdpcp_settings = get_option('_bdcp_settings', []);
		$bdpcp_setting_default = fn($key) => esc_html($bdpcp_settings[$key] ?? [
			'form_background_color' => '#ffffff',
			'form_border_radius' => 8,
			'form_border_color' => '#808080',
			'form_label_size' => 14,
			'form_label_color' => '#212529',
			'form_control_background_color' => '#ffffff',
			'form_control_border_radius' => 8,
			'form_control_text_color' => '#000000',
			'book_button_text' => 'Book Now',
			'book_button_background_color' => '#212529',
			'book_button_text_color' => '#F8F9FA',
			'unit_type_background_color' => '#212529',
			'unit_type_text_color' => '#F8F9FA',
			'date_selection_label' => 'Select Date',
			'time_selection_label' => 'Select Time',
			'duration_label' => 'Duration',
			'sub_total_label' => 'Sub Total',
			'additional_fee_label' => 'Additional Fee',
			'total_amount_label' => 'Total Amount',
			'date_selection_error' => 'Please select date.',
			'time_selection_error' => 'Please select time.',
			'unit_selection_error' => 'Please select slot.'
		][$key]);

		$order_args = [
			'limit' => -1,
			'status' => ['processing'],
			'meta_query' => [
				['key' => '_bdcp_booking_date', 'value' => $booking_date, 'compare' => '='],
				['key' => '_bdcp_order', 'value' => 1, 'compare' => '='],
				['key' => '_bdcp_product_id', 'value' => $product_id, 'compare' => '=']
			]
		];
		$orders = wc_get_orders($order_args);

		$orderTimeSlots = [];
		foreach ($orders as $order) {
			$order_booking_times = $order->get_meta('_bdcp_booking_time', false);
			foreach ($order_booking_times as $order_booking_time) {
				$orderTimeSlots[$order_booking_time->value] = ($orderTimeSlots[$order_booking_time->value] ?? 0) + $order->get_meta('_bdcp_total_slots');
			}
		}

		$time_and_count = [];
		if (empty($is_manual_time_slot)) {
			$start = strtotime($start_time);
			$end = strtotime($end_time);
			$duration = $time_duration * ($time_duration_type === 'hour' ? 3600 : 60);
			$buffer = $buffer_time * ($buffer_time_type === 'hour' ? 3600 : 60);

			while ($start < $end) {
				$slot_start = gmdate('H:i', $start);
				$booked_count = $orderTimeSlots[$slot_start] ?? 0;

				if (($booked_count < $max_slot_per_time && strtotime($current_date_time) < strtotime("$booking_date $slot_start")) || $max_slot_per_time < 0) {
					$time_and_count[] = [
						'slot_start' => $slot_start,
						'slot_start_display' => gmdate('h:i A', $start),
						'left_slots' => $max_slot_per_time - $booked_count,
					];
				}
				$start += $duration + $buffer;
			}
		} else {
			foreach ($time_slots as $key => $value) {
				$booked_count = $orderTimeSlots[$key] ?? 0;
				if (($booked_count < $value['total_slot'] && strtotime($current_date_time) < strtotime("$booking_date $key")) || $value['total_slot'] < 0) {
					$time_and_count[] = [
						'slot_start' => $key,
						'slot_start_display' => gmdate('h:i A', strtotime("$booking_date $key")),
						'left_slots' => $value['total_slot'] - $booked_count,
					];
				}
			}
		}

		$price_details_html = '';
		$total_amount = 0;
		if (!empty($unit_type)) {
			foreach ($people_type_count as $value) {
				$type = $value['type'];
				$count = $value['count'];
				if (!empty($count)) {
					$typePrice = $price_details[$type]['price'];
					$sub_amount = $typePrice * $count * count($booking_time);
					$total_amount += $sub_amount;

					$price_details_html .= '<div class="bdpcp-price-item">
												<div>' . wc_price($typePrice) . ' × ' . $count . ' ' . ucfirst($type) . (count($booking_time) > 1 ? ' × ' . count($booking_time) . ' Time Slots' : '') . '</div>
												<div>' . wc_price($sub_amount) . '</div>
											</div>';
				}
			}
		} else {
			$total_amount = $base_price * count($booking_time);
			$price_details_html .= '<div class="bdpcp-price-item">
										<div>' . $bdpcp_setting_default('sub_total_label') . '</div>
										<div>' . wc_price($total_amount) . '</div>
									</div>';
		}

		$total_amount += $fixed_base_fee;
		if (!empty($fixed_base_fee)) {
			$price_details_html .= '<div class="bdpcp-price-item">
										<div>' . $bdpcp_setting_default('additional_fee_label') . '</div>
										<div>' . wc_price($fixed_base_fee) . '</div>
									</div>';
		}
		$price_details_html .= '<div class="bdpcp-price-item">
									<div>' . $bdpcp_setting_default('total_amount_label') . '</div>
									<div>' . wc_price($total_amount) . '</div>
								</div>';

		wp_send_json_success([
			'time_slots' => $time_and_count,
			'total_amount' => wc_price($total_amount),
			'price_details_html' => $price_details_html
		]);
	}

	public function bdpcp_woocommerce_before_add_to_cart_form_handle()
	{
		global $product;
		if ($product->get_type() == 'bdpcp_bookable_product') {
			include_once(BDPCP_ROOT_PATH . 'public/partials/bdpcp-public-display.php');
		}
	}

	public function bdpcp_woocommerce_order_item_name_handle($product_name, $item)
	{

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

			$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');
			$setting_price_details = $order->get_meta('_bdcp_price_details');

			$product_name .= '<div style="font-size: 14px; line-height: normal;">';
			$product_name .= '<div>Date: ' . gmdate('d-m-Y', strtotime($booking_date)) . '</div>';
			foreach ($booking_times as $booking_time) {
				$product_name .= '<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];
					$product_name .= '<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>';
				}
			}
			$product_name .= '</div>';
			return $product_name;
		}
		return $product_name;
	}

	public function bookingdaddy_display($atts)
	{
		$atts = shortcode_atts(
			array(
				'product_id' => 0
			),
			$atts,
			'bookingdaddy-pro'
		);

		include_once(BDPCP_ROOT_PATH . 'public/partials/bdpcp-public-display.php');
	}
}
