<?php

if ( ! defined( 'ABSPATH' ) ) { exit; }

class AIEO_DMM_Product_Picker {

	
	const ACTION_SEARCH     = 'aieo_dmm_product_search';
	const ACTION_VARIATIONS = 'aieo_dmm_product_variations';

	
	public static function register_ajax() {
		add_action( 'wp_ajax_' . self::ACTION_SEARCH,     array( __CLASS__, 'ajax_search' ) );
		add_action( 'wp_ajax_' . self::ACTION_VARIATIONS, array( __CLASS__, 'ajax_variations' ) );
	}

	
	public static function enqueue_assets() {
		$rel  = 'assets/js/dmm-product-picker.js';
		$path = defined( 'AIEO_DIR' ) ? AIEO_DIR . $rel : '';
		$ver  = ( $path && file_exists( $path ) ) ? (string) filemtime( $path ) : ( defined( 'AIEO_VERSION' ) ? AIEO_VERSION : '1.0' );
		wp_enqueue_script(
			'aieo-dmm-product-picker',
			( defined( 'AIEO_URI' ) ? AIEO_URI : '' ) . $rel,
			array( 'aieo-dmm' ),
			$ver,
			true
		);
	}

	
	
	

	
	public static function render_field( array $args ) {
		$name = isset( $args['name'] ) ? (string) $args['name'] : '';
		if ( $name === '' ) { return ''; }

		$mode  = ( isset( $args['mode'] ) && $args['mode'] === 'exclude' ) ? 'exclude' : 'include';
		$field = isset( $args['field'] ) && $args['field'] !== '' ? (string) $args['field'] : $name;
		$label = isset( $args['label'] ) ? (string) $args['label'] : '';
		$help  = isset( $args['help'] ) ? (string) $args['help'] : '';
		$btn   = isset( $args['button'] ) ? (string) $args['button'] : __( '+ Browse / choose products', 'ai-eshop-optimizer' );
		$empty = isset( $args['empty_text'] ) && $args['empty_text'] !== ''
			? (string) $args['empty_text']
			: ( $mode === 'exclude'
				? __( 'No products excluded.', 'ai-eshop-optimizer' )
				: __( 'No products picked — all products qualify.', 'ai-eshop-optimizer' ) );

		$selected = array();
		if ( isset( $args['selected'] ) && is_array( $args['selected'] ) ) {
			$selected = array_values( array_filter( array_map( 'absint', $args['selected'] ) ) );
		}
		$pairs = $selected ? self::hydrate_ids( $selected ) : array();

		$opts = '';
		foreach ( $pairs as $p ) {
			$opts .= '<option value="' . esc_attr( (string) $p['id'] ) . '" selected'
				. ' data-text="' . esc_attr( (string) $p['text'] ) . '"'
				. ' data-type="' . esc_attr( (string) $p['type'] ) . '"'
				. ' data-status="' . esc_attr( (string) $p['status'] ) . '"'
				. ( ! empty( $p['parent_id'] ) ? ' data-parent="' . esc_attr( (string) $p['parent_id'] ) . '"' : '' )
				. '>' . esc_html( (string) $p['text'] ) . '</option>';
		}

		ob_start();
		?>
		<div class="aieo-prodpick-rule">
			<?php if ( $label !== '' ) : ?>
				<label class="aieo-prodpick-label"><?php echo esc_html( $label ); ?></label>
			<?php endif; ?>
			<div class="aieo-prodpick" data-field="<?php echo esc_attr( $field ); ?>" data-mode="<?php echo esc_attr( $mode ); ?>">
				<select name="<?php echo esc_attr( $name ); ?>[]" multiple hidden class="aieo-prodpick-store"><?php
					echo $opts; 
				?></select>
				<div class="aieo-prodpick-chips" data-empty="<?php echo esc_attr( $empty ); ?>"></div>
				<button type="button" class="button aieo-prodpick-open"><?php echo esc_html( $btn ); ?></button>
			</div>
			<?php if ( $help !== '' ) : ?>
				<span class="description"><?php echo esc_html( $help ); ?></span>
			<?php endif; ?>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	
	
	

	
	public static function collect_ids( $field ) {
		$raw = isset( $_POST[ $field ] ) ? wp_unslash( $_POST[ $field ] ) : array(); 
		if ( ! is_array( $raw ) ) { $raw = array( $raw ); }
		$ids = array_map( 'absint', $raw );
		$ids = array_filter( $ids );
		return array_values( array_unique( $ids ) );
	}

	
	public static function roll_up_to_parents( array $ids ) {
		$out = array();
		foreach ( $ids as $id ) {
			$id = (int) $id;
			if ( $id <= 0 ) { continue; }
			if ( get_post_type( $id ) === 'product_variation' ) {
				$parent = (int) wp_get_post_parent_id( $id );
				if ( $parent > 0 ) { $id = $parent; }
			}
			$out[ $id ] = $id;
		}
		return array_values( $out );
	}

	
	
	

	
	public static function ajax_search() {
		AIEO_DMM::verify_ajax_request();
		$q = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '';
		wp_send_json( array( 'results' => self::search_products_raw( $q, 30 ) ) );
	}

	
	public static function ajax_variations() {
		AIEO_DMM::verify_ajax_request();
		$parent_id = isset( $_GET['parent_id'] ) ? absint( wp_unslash( $_GET['parent_id'] ) ) : 0;
		wp_send_json( array( 'results' => self::get_variations( $parent_id ) ) );
	}

	
	
	

	
	public static function get_variations( $parent_id ) {
		$parent_id = (int) $parent_id;
		$out = array();
		if ( $parent_id && function_exists( 'wc_get_product' ) ) {
			$parent = wc_get_product( $parent_id );
			if ( $parent && $parent->is_type( 'variable' ) ) {
				foreach ( $parent->get_children() as $vid ) {
					$v = wc_get_product( $vid );
					if ( ! $v ) { continue; }
					$out[] = array(
						'id'     => (int) $vid,
						'text'   => self::variation_label( $v ),
						'status' => $v->get_status(),
					);
				}
			}
		}
		return $out;
	}

	
	public static function variation_label( $v ) {
		$attrs = function_exists( 'wc_get_formatted_variation' ) ? (string) wc_get_formatted_variation( $v, true ) : '';
		$label = $attrs !== '' ? $attrs : ( '#' . (int) $v->get_id() );
		if ( $v->get_sku() ) { $label .= ' [' . $v->get_sku() . ']'; }
		return $label;
	}

	
	public static function hydrate_ids( array $list ) {
		$out = array();
		foreach ( $list as $entry ) {
			$pid = (int) $entry;
			if ( $pid <= 0 ) { continue; }

			$post = get_post( $pid );
			if ( ! $post || ( $post->post_type !== 'product' && $post->post_type !== 'product_variation' ) ) {
				$out[] = array( 'id' => $pid, 'text' => '#' . $pid, 'type' => 'missing', 'status' => 'missing' );
				continue;
			}

			if ( $post->post_type === 'product_variation' ) {
				$parent_id = (int) $post->post_parent;
				$v     = function_exists( 'wc_get_product' ) ? wc_get_product( $pid ) : null;
				$label = $v ? self::variation_label( $v ) : ( '#' . $pid );
				$pname = $parent_id ? (string) get_the_title( $parent_id ) : '';
				$text  = ( $pname !== '' ? $pname : ( '#' . $parent_id ) ) . ' — ' . $label;
				$status = $parent_id ? (string) get_post_status( $parent_id ) : $post->post_status;
				$out[] = array( 'id' => $pid, 'text' => $text, 'type' => 'variation', 'status' => $status, 'parent_id' => $parent_id );
				continue;
			}

			$p     = function_exists( 'wc_get_product' ) ? wc_get_product( $pid ) : null;
			$is_var = $p && $p->is_type( 'variable' );
			$title = (string) get_the_title( $pid );
			$sku   = $p ? (string) $p->get_sku() : '';
			$text  = ( $title !== '' ? $title : ( '#' . $pid ) ) . ( $sku !== '' ? ' [' . $sku . ']' : '' );
			$out[] = array(
				'id'     => $pid,
				'text'   => $text,
				'type'   => $is_var ? 'variable' : 'simple',
				'status' => $post->post_status,
			);
		}
		return $out;
	}

	
	public static function search_products_raw( $q, $limit = 30 ) {
		if ( ! function_exists( 'wc_get_product' ) ) { return array(); }
		global $wpdb;
		$limit = max( 1, (int) $limit );
		$q     = trim( (string) $q );

		if ( $q === '' ) {
			$ids = $wpdb->get_col( $wpdb->prepare(
				"SELECT p.ID FROM {$wpdb->posts} p
				 WHERE p.post_type = 'product' AND p.post_status IN ('publish','draft','private')
				 GROUP BY p.ID
				 ORDER BY (p.post_status='publish') DESC, p.post_title ASC
				 LIMIT %d",
				$limit
			) );
		} else {
			$like = '%' . $wpdb->esc_like( $q ) . '%';
			$brand_tt = $wpdb->get_col( $wpdb->prepare(
				"SELECT tt.term_taxonomy_id
				 FROM {$wpdb->term_taxonomy} tt
				 INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
				 WHERE tt.taxonomy = 'product_brand' AND t.name LIKE %s
				 LIMIT 20",
				$like
			) );
			$brand_sql = '';
			$params    = array( $like, $like );
			if ( ! empty( $brand_tt ) ) {
				$ph        = implode( ',', array_fill( 0, count( $brand_tt ), '%d' ) );
				$brand_sql = " OR p.ID IN (SELECT tr.object_id FROM {$wpdb->term_relationships} tr WHERE tr.term_taxonomy_id IN ($ph)) ";
				$params    = array_merge( $params, array_map( 'intval', $brand_tt ) );
			}
			$params[] = $limit;
			$ids = $wpdb->get_col( $wpdb->prepare(
				"SELECT p.ID
				 FROM {$wpdb->posts} p
				 LEFT JOIN {$wpdb->postmeta} sku ON sku.post_id = p.ID AND sku.meta_key = '_sku'
				 WHERE p.post_type = 'product' AND p.post_status IN ('publish','draft','private')
				   AND ( p.post_title LIKE %s OR sku.meta_value LIKE %s {$brand_sql} )
				 GROUP BY p.ID
				 ORDER BY (p.post_status='publish') DESC, p.post_title ASC
				 LIMIT %d",
				$params
			) );
		}

		$results = array();
		foreach ( (array) $ids as $pid ) {
			$p = wc_get_product( (int) $pid );
			if ( ! $p ) { continue; }
			$is_variable = $p->is_type( 'variable' );
			$results[] = array(
				'id'           => (int) $pid,
				'text'         => $p->get_name() . ( $p->get_sku() ? ' [' . $p->get_sku() . ']' : '' ),
				'name'         => $p->get_name(),
				'type'         => $is_variable ? 'variable' : 'simple',
				'status'       => $p->get_status(),
				'n_variations' => $is_variable ? count( $p->get_children() ) : 0,
			);
		}
		return $results;
	}
}
