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

namespace DDWCPointsAndRewards\Includes\Admin;

use DDWCPointsAndRewards\Templates\Admin;
use DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper;

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

if ( ! class_exists( 'DDWCPR_Admin_Functions' ) ) {
	/**
	 * Admin Functions Class
	 */
	class DDWCPR_Admin_Functions {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

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

		/**
		 * Change the admin footer text function.
		 *
		 * @param  string $footer_text text to be rendered in the footer.
		 * @return string
		 */
		public function ddwcpr_set_admin_footer_text( $footer_text ) {
			if ( ! current_user_can( 'manage_woocommerce' ) || ! function_exists( 'wc_get_screen_ids' ) ) {
				return $footer_text;
			}
			$current_screen = get_current_screen();
			$wc_pages       = wc_get_screen_ids();

			// Set only WC pages.
			$wc_pages = array_diff( $wc_pages, [ 'profile', 'user-edit' ] );

			/**
			 * Check to make sure we're on a plugin page.
			 * 
			 * @since 1.0.0
			 */
			if ( isset( $current_screen->base ) && 'devdiggers-plugins_page_ddwcpr-dashboard' === $current_screen->base ) {
				// Change the footer text.
				$footer_text = sprintf(
					/* translators: %s for a tag */
					esc_html__( 'If you really like our plugin, please leave us a %s rating, we\'ll really appreciate it.', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href="//devdiggers.com/plugin/woocommerce-points-and-rewards" target="_blank" title="' . esc_attr__( 'Review', 'loyaltyx-points-and-rewards-for-woocommerce' ) . '" aria-label="' . esc_attr__( 'Review', 'loyaltyx-points-and-rewards-for-woocommerce' ) . '"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 32" height="10"><path d="M16 26.534L6.111 32 8 20.422l-8-8.2 11.056-1.688L16 0l4.944 10.534L32 12.223l-8 8.2L25.889 32zm40 0L46.111 32 48 20.422l-8-8.2 11.056-1.688L56 0l4.944 10.534L72 12.223l-8 8.2L65.889 32zm40 0L86.111 32 88 20.422l-8-8.2 11.056-1.688L96 0l4.944 10.534L112 12.223l-8 8.2L105.889 32zm40 0L126.111 32 128 20.422l-8-8.2 11.056-1.688L136 0l4.944 10.534L152 12.223l-8 8.2L145.889 32zm40 0L166.111 32 168 20.422l-8-8.2 11.056-1.688L176 0l4.944 10.534L192 12.223l-8 8.2L185.889 32z" fill="#F5A623" fill-rule="evenodd"/></svg></a>'
				);
			}

			return $footer_text;
		}

		/**
		 * Sanitize boolean value
		 *
		 * @param mixed $value
		 * @return int
		 */
		private function sanitize_boolean( $value ) {
			return wp_validate_boolean( $value ) ? 1 : 0;
		}

		/**
		 * Sanitize array of strings
		 *
		 * @param mixed $value
		 * @return array
		 */
		private function sanitize_array_strings( $value ) {
			if ( ! is_array( $value ) ) {
				return [];
			}
			return array_map( 'sanitize_text_field', $value );
		}

		/**
		 * Sanitize array recursively
		 *
		 * @param mixed $value
		 * @return mixed
		 */
		private function sanitize_array_recursive( $value ) {
			if ( is_array( $value ) ) {
				return array_map( [ $this, 'sanitize_array_recursive' ], $value );
			} elseif ( is_string( $value ) ) {
				return sanitize_text_field( $value );
			} else {
				return $value;
			}
		}

		/**
		 * Sanitize hex color
		 *
		 * @param string $value
		 * @return string
		 */
		private function sanitize_hex_color( $value ) {
			if ( empty( $value ) ) {
				return '';
			}
			$value = sanitize_hex_color( $value );
			return $value ? $value : '';
		}

		/**
		 * Register settings function
		 *
		 * @return void
		 */
		public function ddwcpr_register_settings() {
			// General configuration fields
			register_setting( 'ddwcpr-general-configuration-fields', '_ddwcpr_enabled', [ 'sanitize_callback' => [ $this, 'sanitize_boolean' ] ] );
			register_setting( 'ddwcpr-general-configuration-fields', '_ddwcpr_award_order_status', [ 'sanitize_callback' => [ $this, 'sanitize_array_strings' ] ] );
			register_setting( 'ddwcpr-general-configuration-fields', '_ddwcpr_revoke_order_status', [ 'sanitize_callback' => [ $this, 'sanitize_array_strings' ] ] );

			// Display messages configuration fields
			register_setting( 'ddwcpr-display-messages-configuration-fields', '_ddwcpr_show_messages_to_guest_users', [ 'sanitize_callback' => [ $this, 'sanitize_boolean' ] ] );
			register_setting( 'ddwcpr-display-messages-configuration-fields', '_ddwcpr_points_singlular_label', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-display-messages-configuration-fields', '_ddwcpr_points_plural_label', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-display-messages-configuration-fields', '_ddwcpr_points_message_styling', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-display-messages-configuration-fields', '_ddwcpr_points_message', [ 'sanitize_callback' => [ $this, 'sanitize_array_recursive' ] ] );

			// Points earning configuration fields
			register_setting( 'ddwcpr-points-earning-configuration-fields', '_ddwcpr_points_earning_per_amount', [ 'sanitize_callback' => 'intval' ] );
			register_setting( 'ddwcpr-points-earning-configuration-fields', '_ddwcpr_points_earning_value', [ 'sanitize_callback' => 'intval' ] );

			// Points redeeming configuration fields
			register_setting( 'ddwcpr-points-redeeming-configuration-fields', '_ddwcpr_points_redeeming_amount', [ 'sanitize_callback' => 'intval' ] );
			register_setting( 'ddwcpr-points-redeeming-configuration-fields', '_ddwcpr_points_redeeming_value', [ 'sanitize_callback' => 'intval' ] );

			// Layout configuration fields
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icons_enabled', [ 'sanitize_callback' => [ $this, 'sanitize_boolean' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icons_wrapper_enabled', [ 'sanitize_callback' => [ $this, 'sanitize_boolean' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_rule_icons_wrapper_enabled', [ 'sanitize_callback' => [ $this, 'sanitize_boolean' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_size', [ 'sanitize_callback' => 'intval' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_total_earned_points', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_available_points', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_redeemed_points', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_coupon_reward', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_referrals', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_icon_wrapper_background_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_card_background_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_card_border_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_card_text_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_details_card_value_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_layout_level_progress_bar_background_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_layout_level_progress_bar_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_layout_table_header_text_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_layout_table_header_background_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );
			register_setting( 'ddwcpr-layout-configuration-fields', '_ddwcpr_layout_rule_icons_wrapper_background_color', [ 'sanitize_callback' => [ $this, 'sanitize_hex_color' ] ] );

			// Emails configuration fields
			register_setting( 'ddwcpr-emails-configuration-fields', '_ddwcpr_points_reason', [ 'sanitize_callback' => [ $this, 'sanitize_array_recursive' ] ] );
			register_setting( 'ddwcpr-emails-configuration-fields', '_ddwcpr_email_settings', [ 'sanitize_callback' => [ $this, 'sanitize_array_recursive' ] ] );

			// Shortcodes configuration fields
			register_setting( 'ddwcpr-shortcodes-configuration-fields', '_ddwcpr_points_dashboard_shortcode', [ 'sanitize_callback' => 'sanitize_text_field' ] );
			register_setting( 'ddwcpr-shortcodes-configuration-fields', '_ddwcpr_available_points_value_shortcode', [ 'sanitize_callback' => 'sanitize_text_field' ] );
		}

		/**
		 * Add custom fields in user data form function
		 *
		 * @param object $user
		 * @return void
		 */
		public function ddwcpr_add_custom_fields_in_user_data_form( $user ) {
			?>
			<h3><?php esc_html_e( 'Birthday Information', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h3>
			<table class="form-table">
				<tr>
					<th><label for="ddwcpr-birthday"><?php esc_html_e( 'Birthday', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label></th>
					<td>
						<input type="date" name="_ddwcpr_birthday" id="ddwcpr-birthday" value="<?php echo esc_attr( get_user_meta( $user->ID, '_ddwcpr_birthday', true ) ); ?>" class="regular-text" />
						<p class="description"><?php esc_html_e( "Enter the user's birthday. This field can only be edited by the admin.", 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
					</td>
				</tr>
			</table>
			<?php
		}

		/**
		 * Save custom fields in user data function
		 *
		 * @param int $user_id
		 * @return void
		 */
		public function ddwcpr_save_custom_fields_in_user_data( $user_id ) {
			// Check if the current user can edit the user.
			if ( ! current_user_can( 'edit_user', $user_id ) ) {
				return;
			}

			// Save the birthday field value.
			if ( ! empty( $_POST['_ddwcpr_birthday'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				update_user_meta( $user_id, '_ddwcpr_birthday', sanitize_text_field( wp_unslash( $_POST['_ddwcpr_birthday'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			}
		}

		/**
		 * Handle order refund creation
		 *
		 * @param int $refund_id Refund id.
		 * @return void
		 */
		public function ddwcpr_handle_refund_created( $refund_id ) {
			$refund = wc_get_order( $refund_id );

			if ( ! $refund ) {
				return;
			}

			$order = wc_get_order( $refund->get_parent_id() );

			if ( ! $order ) {
				return;
			}

			if ( $order->has_status( 'refunded' ) ) {
				return;
			}

			if ( ! $order->get_meta( '_ddwcpr_earned_points', true ) ) {
				return;
			}

			$revoked_points = 0;

			foreach ( $refund->get_items() as $item_id => $item ) {
				$refunded_qty = absint( $item->get_quantity() );

				// Get the original item ID and points
				$original_item_id = $item->get_meta( '_refunded_item_id', true );
				$earned_points    = wc_get_order_item_meta( $original_item_id, '_ddwcpr_earned_points' );

				// Calculate points to revoke based on refunded quantity
				if ( $earned_points && $refunded_qty > 0 ) {
					$points_per_item      = $earned_points / $order->get_item( $original_item_id )->get_quantity();
					$item_revoked_points  = $points_per_item * $refunded_qty;
					$revoked_points      += $item_revoked_points;

					// Add meta to the refund item for tracking revoked points
					wc_add_order_item_meta( $item_id, '_ddwcpr_revoked_points', $item_revoked_points );
				}
			}

			// Get refunded shipping items
			$refunded_shipping_items = $refund->get_items( 'shipping' );

			foreach ( $refunded_shipping_items as $item_id => $item ) {
				// Check if points were earned for shipping in the original order
				$original_item_id       = $item->get_meta( '_refunded_item_id', true );
				$earned_shipping_points = wc_get_order_item_meta( $original_item_id, '_ddwcpr_earned_points', true );


				if ( $earned_shipping_points > 0 ) {
					$revoked_points += $earned_shipping_points;

					// Optionally: Add refunded points to the refund item meta
					wc_add_order_item_meta( $item_id, '_revoked_shipping_points', $earned_shipping_points );
				}
			}

			if ( $revoked_points > 0 ) {
				$point_helper = new DDWCPR_Point_Helper( $this->ddwcpr_configuration );

				// Deduct the points from the customer's balance
				$data = [
					'points'     => -$revoked_points,
					'user_id'    => $order->get_customer_id(),
					'related_id' => $order->get_id(),
					'event'      => 'order_refunded',
				];

				$point_helper->ddwcpr_deduct_user_points( $data );

				/* translators: %1$d: revoked points and %2$s: points label */
				$order->add_order_note( sprintf( esc_html__( 'Refunded items resulted in revocation of %1$d %2$s.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $revoked_points, ddwcpr_get_points_label( $revoked_points ) ) );

				$old_revoked_points = $order->get_meta( '_ddwcpr_revoked_points', true );

				$order->update_meta_data( '_ddwcpr_revoked_points', ! empty( $old_revoked_points ) ? $old_revoked_points + $revoked_points : $revoked_points );
				$order->save();
			}
		}

		/**
		 * Allow SVG in TinyMCE editor
		 *
		 * @param array $init TinyMCE init settings.
		 * @return array
		 */
		public function ddwcpr_allow_svg_in_tinymce( $init ) {
			// Add SVG and its children to valid elements
			$custom_svg = 'svg[*],path[*],circle[*],rect[*],polygon[*],polyline[*],ellipse[*],line[*],g[*],defs[*],linearGradient[*],stop[*],use[*],symbol[*],text[*],tspan[*]';
			if ( isset( $init['extended_valid_elements'] ) ) {
				$init['extended_valid_elements'] .= ',' . $custom_svg;
			} else {
				$init['extended_valid_elements'] = $custom_svg;
			}
			return $init;
		}

		/**
		 * Display Pro Upgrade Admin Notice
		 *
		 * @return void
		 */
		public function ddwcpr_show_pro_upgrade_notice() {
			if ( ! current_user_can( 'manage_woocommerce' ) ) {
				return;
			}

			// Only show on LoyaltyX specific pages.
			$upgrade_url = '//devdiggers.com/plugin/woocommerce-points-and-rewards/?utm_source=admin_notice&utm_medium=upgrade_button&utm_campaign=plugin_upgrade';
			
			$message = sprintf(
				/* translators: %1$s: opening strong tag, %2$s: closing strong tag, %3$s: opening anchor tag, %4$s: closing anchor tag */
				esc_html__( 'Want to take your loyalty program to the next level? %1$sUpgrade to LoyaltyX Pro%2$s now to unlock advanced features like Referral Program, Points Expiration, Gamification Tiers, and more! %3$sGet Pro Version &gt;%4$s', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'<strong>',
				'</strong>',
				'<a href="' . esc_url( $upgrade_url ) . '" target="_blank" style="margin-left: 10px; font-weight: bold; text-decoration: none; color: #0256ff;">',
				'</a>'
			);

			if ( function_exists( 'ddfw_print_notification' ) ) {
				ddfw_print_notification( $message, 'info', true );
			}
		}
	}
}
