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

namespace DDWCPointsAndRewards\Includes\Admin;

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

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

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

		/**
		 * AJAX handler for batch manual adjustment
		 *
		 * @return void
		 */
		public function ddwcpr_batch_manual_adjustment() {
			try {
				check_ajax_referer( 'ddwcpr-nonce', 'nonce' );

				// Handle both array and JSON string formats
				$user_ids = ! empty( $_POST['user_ids'] ) && is_string( $_POST['user_ids'] ) 
					? json_decode( wp_unslash( $_POST['user_ids'] ), true )
					: [];

				if ( ! is_array( $user_ids ) ) {
					wp_send_json_error( [ 'error' => 'Invalid user_ids format.' ] );
				}

				$user_ids        = array_map( 'intval', $user_ids );
				$points          = floatval( $_POST['points'] ?? 0 );
				$action_type     = sanitize_text_field( wp_unslash( $_POST['action_type'] ?? '' ) );
				$expiration_date = sanitize_text_field( wp_unslash( $_POST['expiration_date'] ?? '' ) );
				$description     = sanitize_text_field( wp_unslash( $_POST['description'] ?? '' ) );

				if ( empty( $user_ids ) || empty( $action_type ) || $points <= 0 ) {
					wp_send_json_error( [ 'error' => esc_html__( 'Invalid parameters.', 'loyaltyx-points-and-rewards-for-woocommerce' ) ] );
				}

				global $ddwcpr_configuration;
				$point_helper = new \DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper( $ddwcpr_configuration );
				$results      = [];

				// Process each user in the batch
				foreach ( $user_ids as $user_id ) {
					$user_data           = get_userdata( $user_id );
					$user_points_balance = $point_helper->ddwcpr_get_user_available_points( $user_id );

					$result = [
						'user_id'          => $user_id,
						'action_type'      => $action_type,
						'points_requested' => $points,
						'points_balance'   => $user_points_balance,
						'user_login'       => $user_data ? $user_data->user_login : 'Unknown',
						'display_name'     => $user_data ? $user_data->display_name : 'Unknown',
					];

					try {
						if ( 'add' === $action_type ) {
							$data = [
								'points'          => $points,
								'user_id'         => $user_id,
								'description'     => $description,
								'expiration_date' => $expiration_date,
								'event'           => 'manual_adjustment',
							];
							$point_helper->ddwcpr_add_user_points( $data );
							$result['status']  = 'success';
							/* translators: %s: added points */
							$result['message'] = sprintf( esc_html__( '%s point(s) added successfully', 'loyaltyx-points-and-rewards-for-woocommerce' ), $points );
						} elseif ( 'deduct' === $action_type ) {
							if ( $user_points_balance >= $points ) {
								$point_helper->ddwcpr_deduct_user_points( [
									'points'      => -$points,
									'user_id'     => $user_id,
									'description' => $description,
									'event'       => 'manual_adjustment',
								] );
								$result['status'] = 'success';
								/* translators: %s: deducted points */
								$result['message'] = sprintf( esc_html__( '%s point(s) deducted successfully', 'loyaltyx-points-and-rewards-for-woocommerce' ), $points );
							} else {
								$result['status'] = 'error';
								$result['message'] = esc_html__( 'Insufficient points to deduct', 'loyaltyx-points-and-rewards-for-woocommerce' );
							}
						} else {
							$result['status'] = 'error';
							$result['message'] = esc_html__( 'Invalid action type', 'loyaltyx-points-and-rewards-for-woocommerce' );
						}
					} catch ( \Exception $e ) {
						$result['status'] = 'error';
						$result['message'] = esc_html__( 'Error processing user: ', 'loyaltyx-points-and-rewards-for-woocommerce' ) . $e->getMessage();
					}

					$results[] = $result;
				}

				wp_send_json_success( [ 'results' => $results ] );
			} catch ( \Exception $e ) {
				wp_send_json_error( [ 'error' => 'Internal error: ' . $e->getMessage() ] );
			}
		}

		/**
		 * AJAX handler to get all users for select all functionality
		 *
		 * @return void
		 */
		public function ddwcpr_get_all_users() {
			check_ajax_referer( 'ddwcpr-nonce', 'nonce' );

			global $wpdb;
			$users = $wpdb->get_results( 
				"SELECT ID, user_login, user_email, display_name FROM {$wpdb->users} ORDER BY display_name ASC",
				ARRAY_A
			);

			wp_send_json_success( [ 'users' => $users ] );
		}
	}
}
