<?php
/**
 * This file handles all front end action callbacks.
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Includes\Front;

use DDWCPointsAndRewards\Helper\Rule\DDWCPR_Rule_Helper;
use DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper;
use DDWCPointsAndRewards\Helper\Log\DDWCPR_Log_Helper;
use DDWCPointsAndRewards\Helper\Reward\DDWCPR_Reward_Helper;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Front_Functions' ) ) {    
	/**
	 * Front functions class
	 */
	class DDWCPR_Front_Functions {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Rule Helper Variable
		 *
		 * @var object
		 */
		protected $rule_helper;

		/**
		 * Construct
		 * 
		 * @param array $ddwcpr_configuration
		 */
		public function __construct( $ddwcpr_configuration ) {
			$this->ddwcpr_configuration = $ddwcpr_configuration;
			$this->rule_helper          = new DDWCPR_Rule_Helper( $ddwcpr_configuration );
		}

		/**
		 * Add woocommerce menu function
		 *
		 * @param array $items
		 * @return array
		 */
		public function ddwcpr_add_woocommerce_menu( $items ) {
			$customer_logout_endpoint = get_option( 'woocommerce_logout_endpoint' );

			// Remove the logout menu item.
			if ( ! empty( $items[ $customer_logout_endpoint ] ) ) {
				$logout = $items[ $customer_logout_endpoint ];
				unset( $items[ $customer_logout_endpoint ] );
			}

			// Insert your custom endpoint.
			$items[ $this->ddwcpr_configuration['my_account_endpoint'] ] = $this->ddwcpr_configuration['my_account_endpoint_title'];

			// Insert back the logout item.
			if ( ! empty( $logout ) ) {
				$items[ $customer_logout_endpoint ] = $logout;
			}

			return $items;
		}

		/**
		 * Add Query Vars function
		 *
		 * @param array $vars
		 * @return array
		 */
		public function ddwcpr_add_query_vars( $vars ) {
			$vars[] = $this->ddwcpr_configuration['my_account_endpoint'];
			return $vars;
		}

		/**
		 * Add my account endpoint content function
		 *
		 * @return void
		 */
		public function ddwcpr_add_my_account_endpoint_content() {
			echo do_shortcode( $this->ddwcpr_configuration['points_dashboard_shortcode'] );
		}

		/**
		 * Change Endpoint Title function
		 *
		 * @param string $title
		 * @return string
		 */
		public function ddwcpr_change_endpoint_title( $title ) {
			global $wp_query;

			// New page title.
			if ( is_main_query() && in_the_loop() && is_account_page() ) {
				if ( isset( $wp_query->query_vars[ $this->ddwcpr_configuration['my_account_endpoint'] ] ) ) {
					$title = $this->ddwcpr_configuration['my_account_endpoint_title'];
				}
			}

			return $title;
		}

		/**
		 * Remove Sidebar from custom menu page function
		 *
		 * @param array $sidebars_widgets
		 * @return array
		 */
		public function ddwcpr_remove_sidebar_from_custom_menu_page( $sidebars_widgets ) {
			global $wp_query;

			if ( isset( $wp_query->query_vars[ $this->ddwcpr_configuration['my_account_endpoint'] ] ) && empty( $this->ddwcpr_configuration['enable_widgets_my_account_endpoint'] ) && is_account_page() ) {
				return [ false ];
			}

			return $sidebars_widgets;
		}

		/**
		 * Points Dashboard shortcode content function
		 * 
		 * @return string
		 */
		public function ddwcpr_get_points_dashboard_shortcode_content( $shortcode_args = [] ) {
			$this->ddwcpr_enqueue_front_scripts();
			ob_start();
			require DDWCPR_PLUGIN_FILE . 'templates/shortcodes/points-dashboard.php';
			return ob_get_clean();
		}

		/**
		 * Get available points value shortcode content function
		 * 
		 * @return string
		 */
		public function ddwcpr_get_available_points_value_shortcode_content() {
			$point_helper            = new DDWCPR_Point_Helper( $ddwcpr_configuration );
			$available_redeem_points = $point_helper->ddwcpr_get_user_available_points( get_current_user_id() );
			return $available_redeem_points;
		}

		/**
		 * Front scripts enqueue function
		 *
		 * @return void
		 */
		public function ddwcpr_front_scripts() {
			wp_register_style( 'ddwcpr-front-style', DDWCPR_PLUGIN_URL . 'assets/css/front.css', [], filemtime( DDWCPR_PLUGIN_FILE . 'assets/css/front.css' ) );
			wp_register_script( 'ddwcpr-front-script', DDWCPR_PLUGIN_URL . 'assets/js/front.js', ['jquery'], filemtime( DDWCPR_PLUGIN_FILE . 'assets/js/front.js' ) );

			wp_localize_script(
				'ddwcpr-front-script',
				'ddwcprFrontObject',
				[
					'ajax' => [
						'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
						'ajaxNonce' => wp_create_nonce( 'ddwcpr-nonce' ),
					],
					'i18n' => [
						'copied' => esc_html__( 'Copied', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					],
					'ddwcpr_configuration' => $this->ddwcpr_configuration,
				]
			);

			global $wp_query;

			if ( is_account_page() && isset( $wp_query->query_vars[ $this->ddwcpr_configuration['my_account_endpoint'] ] ) ) {
				wp_enqueue_style( 'ddwcpr-front-style' );
				wp_enqueue_script( 'ddwcpr-front-script' );
			}
		}

		/**
		 * Enqueue front scripts function
		 *
		 * @return void
		 */
		public function ddwcpr_enqueue_front_scripts() {
			wp_enqueue_style( 'ddwcpr-front-style' );
			wp_enqueue_script( 'ddwcpr-front-script' );

			$custom_css = "
				:root {
					--ddwcpr-details-icon-color                   : " . esc_html( $this->ddwcpr_configuration['details_icon_color'] ) . ";
					--ddwcpr-details-icon-wrapper-background-color: " . esc_html( $this->ddwcpr_configuration['details_icon_wrapper_background_color'] ) . ";
					--ddwcpr-card-background-color                : " . esc_html( $this->ddwcpr_configuration['details_card_background_color'] ) . ";
					--ddwcpr-border-color                         : " . esc_html( $this->ddwcpr_configuration['details_card_border_color'] ) . ";
					--ddwcpr-card-text-color                      : " . esc_html( $this->ddwcpr_configuration['details_card_text_color'] ) . ";
					--ddwcpr-card-points-value-color              : " . esc_html( $this->ddwcpr_configuration['details_card_value_color'] ) . ";
					--ddwcpr-primary-color                        : " . esc_html( $this->ddwcpr_configuration['details_card_value_color'] ) . ";
					--ddwcpr-progress-bar-background-color        : " . esc_html( $this->ddwcpr_configuration['layout_level_progress_bar_background_color'] ) . ";
					--ddwcpr-progress-bar-color                   : " . esc_html( $this->ddwcpr_configuration['layout_level_progress_bar_color'] ) . ";
					--ddwcpr-table-header-text-color              : " . esc_html( $this->ddwcpr_configuration['layout_table_header_text_color'] ) . ";
					--ddwcpr-table-header-background-color        : " . esc_html( $this->ddwcpr_configuration['layout_table_header_background_color'] ) . ";
					--ddwcpr-rule-icons-wrapper-background-color  : " . esc_html( $this->ddwcpr_configuration['layout_rule_icons_wrapper_background_color'] ) . ";
				}
			";

			wp_enqueue_style( 'ddwcpr-front-inline-style', true );
			wp_add_inline_style( 'ddwcpr-front-inline-style', $custom_css );
		}

		/**
		 * Display earning points message function
		 *
		 * @return void
		 */
		public function ddwcpr_display_earning_points_message() {
			$points = $this->rule_helper->ddwcpr_calculate_earning_points_by_product_id( get_the_ID() );

			if ( $points <= 0 ) {
				return; 
			}

			$this->ddwcpr_enqueue_front_scripts();

			if ( is_product() ) {
				$message = $this->ddwcpr_configuration['points_message']['product_page']['message'];
			}

			$this->rule_helper->ddwcpr_get_display_points_earning_message( $points, $message, 'product' );
		}

		/**
		 * Display earning points message on products loop function
		 *
		 * @return void
		 */
		public function ddwcpr_display_earning_points_message_product_loop() {
			$points = $this->rule_helper->ddwcpr_calculate_earning_points_by_product_id( get_the_ID() );

			if ( $points <= 0 ) {
				return; 
			}

			$this->ddwcpr_enqueue_front_scripts();

			$message = $this->ddwcpr_configuration['points_message']['shop_page']['message'];

			$this->rule_helper->ddwcpr_get_display_points_earning_message( $points, $message, 'shop' );
		}

		/**
		 * Display earning points message on cart or checkout function
		 *
		 * @return void
		 */
		public function ddwcpr_display_earning_points_message_on_cart_or_checkout() {
			$points = $this->rule_helper->ddwcpr_calculate_cart_earning_points();

			if ( $points <= 0 ) {
				return; 
			}

			$this->ddwcpr_enqueue_front_scripts();

			if ( is_cart() ) {
				$message = $this->ddwcpr_configuration['points_message']['cart_page']['points_earning']['message'];
			} elseif ( is_checkout() ) {
				$message = $this->ddwcpr_configuration['points_message']['checkout_page']['points_earning']['message'];
			}

			$this->rule_helper->ddwcpr_get_display_points_earning_message( $points, $message );
		}

		/**
		 * Display redeeming points message on cart or checkout function
		 *
		 * @return void
		 */
		public function ddwcpr_display_redeeming_points_message_on_cart_or_checkout() {
			$this->ddwcpr_enqueue_front_scripts();

			if ( is_cart() ) {
				$message = $this->ddwcpr_configuration['points_message']['cart_page']['points_redeeming']['message'];
			} elseif ( is_checkout() ) {
				$message = $this->ddwcpr_configuration['points_message']['checkout_page']['points_redeeming']['message'];
			}

			$this->rule_helper->ddwcpr_get_display_points_redeeming_message( $message );
		}

		/**
		 * Display earning points message on order page function
		 *
		 * @return void
		 */
		public function ddwcpr_display_earning_points_message_on_view_order_page( $order_id ) {
			$order = wc_get_order( $order_id );

			$points = $this->rule_helper->ddwcpr_calculate_order_earning_points( $order );

			if ( $points <= 0 ) {
				return; 
			}

			$this->ddwcpr_enqueue_front_scripts();

			$message = $this->ddwcpr_configuration['points_message']['view_order_page']['message'];

			$this->rule_helper->ddwcpr_get_display_points_earning_message( $points, $message );
		}

		/**
		 * Handle WP loaded function
		 *
		 * @return void
		 */
		public function ddwcpr_handle_wp_loaded() {
			if ( ! empty( $_POST['ddwcpr_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ddwcpr_nonce'] ) ), 'ddwcpr_nonce_action' ) ) {
				if ( ! empty( $_POST['ddwcpr_redeem_button_submit'] ) ) {
					$reward_helper = new DDWCPR_Reward_Helper( $this->ddwcpr_configuration );
					$reward_helper->ddwcpr_create_coupon_reward();
				}

				if ( ! empty( $_POST['ddwcpr_apply_reward_points_submit'] ) ) {
					$coupon_code = ! empty( $_POST['ddwcpr_coupon_code'] ) ? sanitize_text_field( wp_unslash( $_POST['ddwcpr_coupon_code'] ) ) : '';
					$reward_helper = new DDWCPR_Reward_Helper( $this->ddwcpr_configuration );
					$reward_helper->ddwcpr_apply_reward_points_to_cart( $coupon_code );
				}

				if ( ! empty( $_POST['ddwcpr_global_points_conversion_submit'] ) ) {
					$reward_helper = new DDWCPR_Reward_Helper( $this->ddwcpr_configuration );
					$result = $reward_helper->ddwcpr_global_points_conversion_to_coupon();

					if ( is_wp_error( $result ) ) {
						wc_add_notice( $result->get_error_message(), 'error' );
						wp_safe_redirect( add_query_arg( null, null ) );
						exit;
					}
				}
			}
		}
	}
}
