<?php
/**
 * Import Users with Points
 *
 * @package WooCommerce Points and Rewards
 */

namespace DDWCPointsAndRewards\Includes;

use DevDiggers\Framework\Includes\DDFW_SVG;
use DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper;

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

if ( ! class_exists( 'DDWCPR_Import_Wizard' ) ) {
	/**
	 * Import class
	 */
	class DDWCPR_Import_Wizard {
		/**
		 * Constructor
		 */
		public function __construct() {
			$this->enqueue_scripts();
			add_action( 'wp_ajax_ddwcpr_batch_import_points', [ $this, 'ajax_batch_import_points' ] );
		}

		/**
		 * Recursively sanitize array data
		 *
		 * @param mixed $data Data to sanitize
		 * @return mixed Sanitized data
		 */
		private static function sanitize_recursive( $data ) {
			if ( is_array( $data ) ) {
				return array_map( [ self::class, 'sanitize_recursive' ], $data );
			} elseif ( is_string( $data ) ) {
				return sanitize_text_field( $data );
			} else {
				return $data;
			}
		}

		/**
		 * AJAX handler for batch import points
		 *
		 * @return void
		 */
		public static function ajax_batch_import_points() {
			check_ajax_referer( 'ddwcpr-nonce', 'nonce' );

			$rows               = isset( $_POST['rows'] ) ? self::sanitize_recursive( json_decode( wp_unslash( $_POST['rows'] ), true ) ) : '';
			$mapping            = isset( $_POST['mapping'] ) ? self::sanitize_recursive( json_decode( wp_unslash( $_POST['mapping'] ), true ) ) : '';
			$action             = isset( $_POST['action_type'] ) ? sanitize_text_field( wp_unslash( $_POST['action_type'] ) ) : 'add';
			$manual_description = isset( $_POST['manual_description'] ) ? sanitize_text_field( wp_unslash( $_POST['manual_description'] ) ) : '';
			$start_index        = isset( $_POST['start_index'] ) ? intval( wp_unslash( $_POST['start_index'] ) ) : 0;

			if ( empty( $rows ) || ! is_array( $rows ) ) {
				wp_send_json_error( [ 'error' => esc_html__( 'No data.', 'loyaltyx-points-and-rewards-for-woocommerce' ) ] );
			}

			global $ddwcpr_configuration;
			$point_helper = new DDWCPR_Point_Helper( $ddwcpr_configuration );
			$results = [];

			foreach ( $rows as $i => $row ) {
				$absolute_row_index = $start_index + $i;

				// Map fields
				$id       = isset( $mapping['id'] ) && $mapping['id'] ? ( $row[ $mapping['id'] ] ?? '' ) : '';
				$username = isset( $mapping['username'] ) && $mapping['username'] ? ( $row[ $mapping['username'] ] ?? '' ) : '';
				$email    = isset( $mapping['email'] ) && $mapping['email'] ? ( $row[ $mapping['email'] ] ?? '' ) : '';
				$points   = isset( $mapping['points'] ) && $mapping['points'] ? ( $row[ $mapping['points'] ] ?? '' ) : '';

				// Get description
				$desc = isset( $mapping['description'] ) && $mapping['description'] ? ( $row[ $mapping['description'] ] ?? '' ) : ( $manual_description ?: '' );

				// User lookup: id > username > email
				$user_id = 0;
				if ( $id && is_numeric( $id ) ) {
					$user_id = intval( $id );
				} elseif ( $username ) {
					$user_obj = get_user_by( 'login', $username );
					$user_id  = $user_obj ? $user_obj->ID : 0;
				} elseif ( $email && is_email( $email ) ) {
					$user_obj = get_user_by( 'email', $email );
					$user_id  = $user_obj ? $user_obj->ID : 0;
				}

				if ( ! $user_id ) {
					$results[] = [
						'row'         => $i,
						'absoluteRow' => $absolute_row_index,
						'status'      => 'error',
						'message'     => esc_html__( 'User not found', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					];
					continue;
				}

				// Validate points
				$points = floatval( $points );
				if ( ! is_numeric( $points ) ) {
					$results[] = [
						'row'         => $i,
						'absoluteRow' => $absolute_row_index,
						'status'      => 'error',
						'message'     => esc_html__( 'Invalid points value', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					];
					continue;
				}

				// Process points action
				$current_points = $point_helper->ddwcpr_get_user_available_points( $user_id );
				$data = [
					'user_id'     => $user_id,
					'points'      => $points,
					'description' => $desc,
					'event'       => 'import'
				];

				switch ( $action ) {
					case 'add':
						$data['points'] = abs( $points );
						$point_helper->ddwcpr_add_user_points( $data );
						$message = esc_html__( 'Points added', 'loyaltyx-points-and-rewards-for-woocommerce' );
						break;
					case 'subtract':
						$data['points'] = -abs( $points );
						$point_helper->ddwcpr_deduct_user_points( $data );
						$message = esc_html__( 'Points subtracted', 'loyaltyx-points-and-rewards-for-woocommerce' );
						break;
					case 'override':
						$diff = $points - $current_points;
						if ( $diff > 0 ) {
							$data['points'] = $diff;
							$point_helper->ddwcpr_add_user_points( $data );
							$message = esc_html__( 'Points overridden (added)', 'loyaltyx-points-and-rewards-for-woocommerce' );
						} elseif ( $diff < 0 ) {
							$data['points'] = $diff;
							$point_helper->ddwcpr_deduct_user_points( $data );
							$message = esc_html__( 'Points overridden (subtracted)', 'loyaltyx-points-and-rewards-for-woocommerce' );
						} else {
							$message = esc_html__( 'Points already match', 'loyaltyx-points-and-rewards-for-woocommerce' );
						}
						break;
					default:
						$results[] = [
							'row'         => $i,
							'absoluteRow' => $absolute_row_index,
							'status'      => 'error',
							'message'     => esc_html__( 'Unknown action', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						];
						continue 2;
				}

				$results[] = [
					'row'         => $i,
					'absoluteRow' => $absolute_row_index,
					'status'      => 'success',
					'message'     => $message,
				];
			}
			wp_send_json_success( [ 'results' => $results ] );
		}

		/**
		 * Enqueue scripts and styles
		 */
		public function enqueue_scripts() {
			wp_enqueue_style( 'ddwcpr-import-style' );
			wp_enqueue_script( 'ddwcpr-import-script' );
		}

		/**
		 * Render import page
		 */
		public function render() {
			?>
			<div class="ddwcpr-wizard">
				<!-- Generic Progress Bar Template -->
				<script type="text/html" id="tmpl-ddwcpr-progress-bar">
					<div class="ddwcpr-progress-wrap">
						<div class="ddwcpr-progress-bar-bg">
							<div class="ddwcpr-progress-bar" style="width:{{ data.percent }}%" data-percent="{{ data.percent }}"></div>
						</div>
						<div class="ddwcpr-progress-label">
							<span>{{ data.message || 'Processing...' }}</span>
							<span class="ddwcpr-progress-text">{{ data.processed }}/{{ data.total }}</span>
						</div>
					</div>
				</script>

				<!-- Error State Template -->
				<script type="text/html" id="tmpl-ddwcpr-wizard-error">
					<div class="ddwcpr-wizard-error">
						<span class="ddwcpr-wizard-error-icon">⚠</span>
						<h3><?php esc_html_e( 'Import Error', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h3>
						<p>{{ data.message }}</p>
						<button class="button button-secondary ddwcpr-wizard-retry"><?php esc_html_e( 'Try Again', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
					</div>
				</script>

				<!-- File Info Template -->
				<script type="text/html" id="tmpl-ddwcpr-file-info">
					<span class="ddwcpr-file-icon">📄</span>
					<span class="ddwcpr-file-name">{{ data.fileName }}</span>
					<span class="ddwcpr-file-size">({{ data.fileSize }})</span>
				</script>


				<!-- Imported/Not Imported Dropdown Template -->
				<script type="text/html" id="tmpl-ddwcpr-import-summary-list">
					<# if ( data.items && data.items.length ) { #>
						<ul>
						<# _.each( data.items, function( item ) { #>
							<li>
								<span class="ddwcpr-row-number"><?php esc_html_e( 'Row', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?> {{ item.displayRow || ( item.row + 1 ) }}:</span>
								<span class="ddwcpr-row-message">{{ item.message }}</span>
								<# if ( item.user_id ) { #>
									<span class="ddwcpr-row-user-id">(<?php esc_html_e( 'User ID', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>: {{ item.user_id }})</span>
								<# } #>
							</li>
						<# }); #>
						</ul>
					<# } else { #>
						<em>{{ data.emptyText }}</em>
					<# } #>
				</script>

				<!-- Import Summary Card Template -->
				<script type="text/html" id="tmpl-ddwcpr-wizard-summary-card">
					<div class="ddwcpr-wizard-summary-card">
						<div class="ddwcpr-wizard-summary-header">
							<span class="ddwcpr-wizard-summary-success">
								<svg width="24" height="24" fill="none"><circle cx="12" cy="12" r="12" fill="#22C55E"/><path d="M7 13l3 3 7-7" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
							</span>
							<span class="ddwcpr-wizard-summary-title"><?php esc_html_e( 'Import CSV Summary', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
						</div>
						<div class="ddwcpr-wizard-summary-details">
							<div class="ddwcpr-wizard-summary-rows">
								{{ data.totalRows }} <?php esc_html_e( 'rows', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?> • {{ data.totalCols }} <?php esc_html_e( 'columns', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
							</div>
							<div class="ddwcpr-wizard-summary-table">
								<div class="ddwcpr-wizard-summary-row">
									<span class="ddwcpr-wizard-summary-label ddwcpr-success">✔ <?php esc_html_e( 'Total rows in file', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
									<span class="ddwcpr-wizard-summary-value ddwcpr-wizard-summary-total-rows">{{ data.totalRows }}</span>
								</div>
								<div class="ddwcpr-wizard-summary-row">
									<span class="ddwcpr-wizard-summary-label ddwcpr-warning">⚠ <?php esc_html_e( 'Duplicated rows in file', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
									<span class="ddwcpr-wizard-summary-value ddwcpr-wizard-summary-duplicate-rows">{{ data.duplicateRows }}</span>
								</div>
								<div class="ddwcpr-wizard-summary-row ddwcpr-import-summary-row-indent ddwcpr-import-summary-toggle" data-toggle="imported">
									<span class="ddwcpr-wizard-summary-label">↳ <?php esc_html_e( 'Imported to the system', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?> <span class="ddwcpr-import-summary-caret">▼</span></span>
									<span class="ddwcpr-wizard-summary-value ddwcpr-wizard-summary-imported">{{ data.imported }}</span>
								</div>
								<div class="ddwcpr-import-summary-dropdown ddwcpr-imported-list ddfw-hide">{{{ data.importedListHTML }}}</div>
								<div class="ddwcpr-wizard-summary-row ddwcpr-import-summary-row-indent ddwcpr-import-summary-toggle" data-toggle="notimported">
									<span class="ddwcpr-wizard-summary-label">↳ <?php esc_html_e( 'Not Imported', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?> <span class="ddwcpr-import-summary-caret">▼</span></span>
									<span class="ddwcpr-wizard-summary-value ddwcpr-wizard-summary-notimported">{{ data.notImported }}</span>
								</div>
								<div class="ddwcpr-import-summary-dropdown ddwcpr-notimported-list ddfw-hide">{{{ data.notImportedListHTML }}}</div>
							</div>
							<div class="ddwcpr-wizard-summary-total">
								<span><?php esc_html_e( 'Total rows imported', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
								<span class="ddwcpr-wizard-summary-total-value ddwcpr-wizard-summary-imported">{{ data.imported }}</span>
							</div>
							<div class="ddwcpr-step-actions-final ddwcpr-step-actions">
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . sanitize_text_field( wp_unslash( $_GET['page'] ) ) . '&menu=' . sanitize_text_field( wp_unslash( $_GET['menu'] ) ) ) ); ?>" class="button button-primary"><?php esc_html_e( 'Done', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></a>
							</div>
						</div>
					</div>
				</script>

				<div class="ddwcpr-steps">
					<div class="ddwcpr-step active" data-step="1">
						<span class="ddwcpr-step-index">1</span>
						<span class="ddwcpr-step-label"><?php esc_html_e( 'Select File', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
					</div>
					<div class="ddwcpr-step" data-step="2">
						<span class="ddwcpr-step-index">2</span>
						<span class="ddwcpr-step-label"><?php esc_html_e( 'Mapping', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
					</div>
					<div class="ddwcpr-step" data-step="3">
						<span class="ddwcpr-step-index">3</span>
						<span class="ddwcpr-step-label"><?php esc_html_e( 'Data Import', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></span>
					</div>
				</div>

				<form id="ddwcpr-import-form" method="post" enctype="multipart/form-data">
					<div class="ddwcpr-step-content" data-step="1">
						<h2><?php esc_html_e( 'Upload a CSV file', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h2>
						<p class="ddwcpr-step-description"><?php esc_html_e( 'Make sure file includes user ID, email, and points data', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
						<div class="ddwcpr-dropzone" id="ddwcpr-dropzone">
							<input type="file" name="import_file" id="ddwcpr-import-file" accept=".csv" required hidden />
							<div class="ddwcpr-dropzone-inner">
								<div class="ddwcpr-dropzone-icon">
									<?php
									DDFW_SVG::get_svg_icon(
										'cloud-upload',
										false,
										[
											'size'         => '60',
											'fill'         => '#9ca3af',
											'stroke_color' => '#9ca3af',
											'stroke_width' => '0',
										]
									);
									?>
								</div>
								<p><?php esc_html_e( 'Drop a file or click to browse', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
								<small><?php esc_html_e( 'CSV files of any size are supported with batch processing', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></small>
							</div>
						</div>
						<div class="ddwcpr-import-file-info ddfw-hide"></div>
						<div class="ddwcpr-sample-file-link">
							<a href="<?php echo esc_url( DDWCPR_PLUGIN_URL . 'assets/sample/user-points.csv' ); ?>" class="ddwcpr-sample-link">
								<?php esc_html_e( 'Download a sample CSV file', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
							</a>
						</div>
						<div class="ddwcpr-step-actions">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . sanitize_text_field( wp_unslash( $_GET['page'] ) ) . '&menu=' . sanitize_text_field( wp_unslash( $_GET['menu'] ) ) ) ); ?>" class="button button-secondary"><?php esc_html_e( 'Cancel', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></a>
							<button type="button" class="button button-primary ddwcpr-next-step" data-next="2" disabled><?php esc_html_e( 'Continue', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
						</div>
					</div>

					<div class="ddwcpr-step-content ddfw-hide" data-step="2">
						<h2><?php esc_html_e( 'CSV Fields Mapping', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h2>
						<p class="ddwcpr-step-description"><?php esc_html_e( 'Map columns from imported CSV to the default fields required for points. Not required columns could be skipped.', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>

						<div class="ddwcpr-mapping-notice">
							<div class="ddwcpr-notice-content">
								<strong><?php esc_html_e( 'User Identification:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong>
								<?php esc_html_e( 'You need to map at least one of ID, Username, or Email to identify users. Points field is required.', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
							</div>
						</div>
						<div class="ddfw-table-wrapper">
							<table class="ddwcpr-mapping ddfw-table" id="ddwcpr-mapping-table">
								<thead>
									<tr>
											<th><?php esc_html_e( 'Fields', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></th>
											<th><?php esc_html_e( 'CSV Column', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></th>
											<th><?php esc_html_e( 'CSV Example Data', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></th>
									</tr>
								</thead>
								<tbody>
									<?php
									$mapping_fields = [
										[
											'key'      => 'id',
											'label'    => esc_html__( 'ID', 'loyaltyx-points-and-rewards-for-woocommerce' ),
											'required' => false,
											'group'    => 'user_identifier',
										],
										[
											'key'      => 'username',
											'label'    => esc_html__( 'Username', 'loyaltyx-points-and-rewards-for-woocommerce' ),
											'required' => false,
											'group'    => 'user_identifier',
										],
										[
											'key'      => 'email',
											'label'    => esc_html__( 'Email', 'loyaltyx-points-and-rewards-for-woocommerce' ),
											'required' => false,
											'group'    => 'user_identifier',
										],
										[
											'key'      => 'points',
											'label'    => esc_html__( 'Points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
											'required' => true,
										],
										[
											'key'      => 'description',
											'label'    => esc_html__( 'Description', 'loyaltyx-points-and-rewards-for-woocommerce' ),
											'required' => false,
										],
									];
									foreach ( $mapping_fields as $field ) {
										?>
										<tr>
											<td>
												<?php echo esc_html( $field['label'] ); ?>
												<?php
												if ( $field['required'] ) {
													?>
													&nbsp;<abbr class="required" title="<?php esc_attr_e( 'required', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>">*</abbr>
													<?php
												} elseif ( isset( $field['group'] ) && 'user_identifier' ===$field['group'] ) {
													?>
													&nbsp;<abbr class="required" title="<?php esc_attr_e( 'at least one required', 'loyaltyx-points-and-rewards-for-woocommerce' ) ?>">*</abbr>
													<?php
												}
												?>
											</td>
											<td>
												<select name="map[<?php echo esc_attr( $field['key'] ); ?>]" class="ddwcpr-map-select" data-field="<?php echo esc_attr( $field['key'] ); ?>" data-default="<?php echo esc_attr( $field['key'] ); ?>">
													<option value=""><?php esc_html_e( 'Select column', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></option>
												</select>
											</td>
											<td class="ddwcpr-example-data"></td>
										</tr>
										<?php
									}
									?>
								</tbody>
							</table>
						</div>

						<div class="ddwcpr-import-action-row">
							<label><?php esc_html_e( 'Points Action', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>:</label>
							<div class="ddwcpr-action-card-group">
								<?php
								$action_cards = [
									[
										'value' => 'add',
										'icon'  => '+',
										'title' => esc_html__( 'Add to existing points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
									],
									[
										'value' => 'subtract',
										'icon'  => '−',
										'title' => esc_html__( 'Subtract from existing points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
									],
									[
										'value' => 'override',
										'icon'  => '=',
										'title' => esc_html__( 'Override points (set to value)', 'loyaltyx-points-and-rewards-for-woocommerce' ),
									],
								];

								foreach ( $action_cards as $card ) {
									$checked = isset( $card['value'] ) && $card['value'] ? ' checked' : '';
									?>
									<label class="ddwcpr-action-card">
										<input type="radio" name="ddwcpr_import_action" value="<?php echo esc_attr( $card['value'] ); ?>"<?php echo esc_attr( $checked ); ?> />
										<div class="ddwcpr-action-card-content">
											<div class="ddwcpr-action-card-icon"><?php echo esc_html( $card['icon'] ); ?></div>
											<div class="ddwcpr-action-card-title"><?php echo esc_html( $card['title'] ); ?></div>
										</div>
									</label>
									<?php
								}
								?>
							</div>
						</div>

						<div class="ddwcpr-import-action-row">
							<label for="ddwcpr-manual-description"><?php esc_html_e( 'Manual Description (if not in CSV):', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label>
							<textarea id="ddwcpr-manual-description" name="ddwcpr_manual_description" class="ddwcpr-description-textarea regular-text ddfw-full-width" rows="3" placeholder="<?php esc_attr_e( 'Enter description for all rows if not mapped', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>"></textarea>
						</div>

						<div class="ddwcpr-step-actions">
							<button type="button" class="button button-secondary ddwcpr-prev-step" data-prev="1"><?php esc_html_e( 'Back', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
							<button type="submit" class="button button-primary"><?php esc_html_e( 'Import Points', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
						</div>
					</div>

					<div class="ddwcpr-step-content ddwcpr-step-content-final ddfw-hide" data-step="3">
						<h2><?php esc_html_e( 'Import Points', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h2>
						<p class="ddwcpr-step-description"><?php esc_html_e( 'Processing your import...', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
						<div class="ddwcpr-wizard-summary-wrap">
							<div class="ddwcpr-wizard-summary">
								<!-- Progress bar and results will be rendered using templates -->
							</div>
						</div>
					</div>
				</form>
			</div>
			<?php
		}
	}
}
