<?php
/**
 * MindWbConcierge Product Catalog Handlers
 *
 * @package MindWebConcierge
 */

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


add_action( 'wp_ajax_mindweco_fetch_product_catalog', 'mindweco_fetch_product_catalog' );

function mindweco_fetch_product_catalog() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	if ( ! class_exists( 'WooCommerce' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'WooCommerce is not active.', 'mind-web-concierge' ) ) );
		return;
	}

	$products = wc_get_products( array(
		'limit'  => -1,
		'status' => 'publish',
		'return' => 'objects',
	) );

	global $wpdb;
	$table = $wpdb->prefix . 'mindweco_indexed_products';

	$col = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM `' . $table . '` LIKE %s', 'item_id' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	$product_data = array();
	foreach ( $products as $product ) {
		$indexed_row = $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM `{$table}` WHERE product_id = %d LIMIT 1", $product->get_id() )
		);

		$is_indexed = ! empty( $indexed_row );
		$item_id    = $indexed_row ? $indexed_row->item_id : null;

		$product_data[] = array(
			'id'                => $product->get_id(),
			'name'              => $product->get_name(),
			'sku'               => $product->get_sku(),
			'price'             => $product->get_price(),
			'regular_price'     => $product->get_regular_price(),
			'sale_price'        => $product->get_sale_price(),
			'stock'             => $product->get_stock_quantity(),
			'description'       => $product->get_description(),
			'short_description' => $product->get_short_description(),
			'categories'        => wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'names' ) ),
			'tags'              => wp_get_post_terms( $product->get_id(), 'product_tag', array( 'fields' => 'names' ) ),
			'image'             => wp_get_attachment_url( $product->get_image_id() ),
			'permalink'         => $product->get_permalink(),
			'indexed'           => $is_indexed,
			'item_id'           => $item_id,
		);
	}

	$total_products = count( $product_data );
	$total_indexed  = intval( $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	wp_send_json_success( array(
		'products' => $product_data,
		'totals'   => array(
			'total_products' => $total_products,
			'total_indexed'  => $total_indexed,
		),
	) );
}

add_action( 'wp_ajax_mindweco_index_all_products', 'mindweco_index_all_products' );

function mindweco_index_all_products() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	global $wpdb;

	$options       = get_option( 'mindweco_plugin_options', array() );
	$base_url      = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
	$chunk_size    = intval( get_option( 'mindweco_chunk_size' ) ) ?: 1000;
	$chunk_overlap = intval( get_option( 'mindweco_chunk_overlap' ) ) ?: 200;
	$header_levels = get_option( 'mindweco_header_levels', 'h1,h2,h3' );

	if ( empty( $header_levels ) ) {
		$header_levels = 'h1,h2,h3';
	}

	$category = get_option( 'mindweco_plugin_category', null );
	if ( ! $category || empty( $category['id'] ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Category not set. Please login first.', 'mind-web-concierge' ) ) );
		return;
	}

	$category_id   = intval( $category['id'] );
	$category_name = sanitize_text_field( $category['name'] );

	if ( empty( $base_url ) || empty( $token ) || ! $category_id ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Missing required configuration: Base URL, Token, or Category ID.', 'mind-web-concierge' ) ) );
		return;
	}

	$fresh_token = mindweco_plugin_refresh_token();
	if ( $fresh_token ) {
		$token = $fresh_token;
	}

	$all_product_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT ID FROM `{$wpdb->prefix}posts` WHERE post_type = %s AND post_status = %s",
			'product',
			'publish'
		)
	);

	$results = array();
	$table   = $wpdb->prefix . 'mindweco_indexed_products';

	foreach ( $all_product_ids as $product_id ) {
		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			continue;
		}

		$existing = $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM `{$table}` WHERE product_id = %d LIMIT 1", $product_id )
		);

		if ( $existing ) {
			$results[] = array(
				'id'          => $existing->id,
				'product_id'  => $product_id,
				'post_id'     => $product_id,
				'category_id' => $category_id,
				'status'      => 'already_indexed',
				'url'         => $product->get_permalink(),
				'title'       => $product->get_name(),
				'category'    => $category_name,
				'item_id'     => isset( $existing->item_id ) ? $existing->item_id : null,
			);
			continue;
		}

		$wp_json_array = mindweco_build_product_payload( $product );

		$meta = array(
			'categories' => wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'names' ) ),
			'tags'       => wp_get_post_terms( $product->get_id(), 'product_tag', array( 'fields' => 'names' ) ),
		);

		$api_response = mindweco_plugin_api_index_products(
			$base_url,
			$token,
			$category_id,
			$chunk_size,
			$chunk_overlap,
			$wp_json_array,
			$meta,
			''
		);

		if ( isset( $api_response['error'] ) ) {
			$results[] = array(
				'id'            => null,
				'product_id'    => $product->get_id(),
				'post_id'       => $product->get_id(),
				'category_id'   => $category_id,
				'status'        => 'failed',
				'url'           => get_permalink( $product->get_id() ),
				'title'         => $product->get_name(),
				'category'      => $category_name,
				'error_message' => $api_response['error'],
			);
			continue;
		}

		$new_item_id = isset( $api_response['item_id'] ) ? $api_response['item_id'] : null;
		if ( empty( $new_item_id ) ) {
			$results[] = array(
				'id'            => null,
				'product_id'    => $product->get_id(),
				'post_id'       => $product->get_id(),
				'category_id'   => $category_id,
				'status'        => 'failed',
				'url'           => get_permalink( $product->get_id() ),
				'title'         => $product->get_name(),
				'category'      => $category_name,
				'error_message' => esc_html__( 'No item ID returned from API.', 'mind-web-concierge' ),
			);
			continue;
		}

		$upserted = $wpdb->query(
			$wpdb->prepare(
				"INSERT INTO `{$wpdb->prefix}mindweco_indexed_products`
					(product_id, post_id, item_id, category_id, created_at)
				VALUES (%d, %d, %s, %d, %s)
				ON DUPLICATE KEY UPDATE
					item_id     = VALUES(item_id),
					category_id = VALUES(category_id),
					created_at  = VALUES(created_at)",
				$product->get_id(),
				$product->get_id(),
				$new_item_id,
				$category_id,
				current_time( 'mysql' )
			)
		);

		if ( false === $upserted ) {
			$results[] = array(
				'post_id'     => $product->get_id(),
				'item_id'     => $new_item_id,
				'category_id' => $category_id,
				'status'      => 'failed',
				'error'       => esc_html__( 'Database upsert failed.', 'mind-web-concierge' ),
				'url'         => get_permalink( $product->get_id() ),
				'title'       => $product->get_name(),
				'category'    => $category_name,
			);
			continue;
		}

		$author_id   = get_post_field( 'post_author', $product->get_id() );
		$author_data = get_userdata( $author_id );
		$author_name = $author_data ? $author_data->display_name : esc_html__( 'Unknown', 'mind-web-concierge' );

		$results[] = array(
			'id'          => $wpdb->insert_id ? $wpdb->insert_id : null,
			'product_id'  => $product->get_id(),
			'post_id'     => $product->get_id(),
			'category_id' => $category_id,
			'status'      => 'success',
			'item_id'     => $new_item_id,
			'url'         => get_permalink( $product->get_id() ),
			'title'       => $product->get_name(),
			'category'    => $category_name,
			'image'       => wp_get_attachment_url( $product->get_image_id() ) ?: '',
			'price'       => $product->get_price(),
			'post_status' => $product->get_status(),
			'author'      => $author_name,
		);
	}

	wp_send_json_success( $results );
}

add_action( 'rest_api_init', 'mindweco_register_rest_routes' );

function mindweco_register_rest_routes() {
	register_rest_route(
		'mindweb/v1',
		'/products',
		array(
			'methods'             => 'GET',
			'callback'            => 'mindweco_rest_get_all_products',
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
		)
	);
}

/**
 * REST API callback: returns all published WooCommerce products.
 *
 * @return WP_REST_Response
 */
function mindweco_rest_get_all_products() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return new WP_REST_Response( array( 'error' => esc_html__( 'WooCommerce not active.', 'mind-web-concierge' ) ), 400 );
	}

	$products = wc_get_products( array( 'limit' => -1, 'status' => 'publish' ) );
	$data     = array();

	foreach ( $products as $product ) {
		$data[] = mindweco_build_product_payload( $product );
	}

	return new WP_REST_Response( array(
		'success'  => true,
		'total'    => count( $data ),
		'products' => $data,
	), 200 );
}

add_action( 'wp_ajax_mindweco_get_stats_product_catalog', 'mindweco_get_stats_product_catalog' );

function mindweco_get_stats_product_catalog() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );
	if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
        return;
    }

	global $wpdb;

	$posts_table   = $wpdb->prefix . 'posts';
	$indexed_table = $wpdb->prefix . 'mindweco_indexed_products';

	$total_products = intval( $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM `{$posts_table}` WHERE post_type = %s AND post_status = %s",
			'product',
			'publish'
		)
	) );

	$indexed_products = intval( $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM `{$indexed_table}` i
			INNER JOIN `{$posts_table}` p ON i.post_id = p.ID
			WHERE p.post_type = %s AND p.post_status = %s",
			'product',
			'publish'
		)
	) );

	$pending  = max( 0, $total_products - $indexed_products );
	$progress = $total_products > 0 ? round( ( $indexed_products / $total_products ) * 100, 2 ) : 0;

	wp_send_json_success( array(
		'total'    => $total_products,
		'indexed'  => $indexed_products,
		'to_index' => $pending,
		'progress' => $progress,
	) );
}

add_action( 'wp_ajax_mindweco_refresh_access_token_products', 'mindweco_handle_refresh_token_products' );

function mindweco_handle_refresh_token_products() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	$new_token = mindweco_plugin_refresh_token();

	if ( $new_token ) {
		wp_send_json_success( array(
			'message' => esc_html__( 'Token refreshed successfully.', 'mind-web-concierge' ),
			'token'   => $new_token,
		) );
	} else {
		wp_send_json_error( array( 'message' => esc_html__( 'Failed to refresh token. Please check your credentials.', 'mind-web-concierge' ) ) );
	}
}

add_action( 'wp_ajax_mindweco_get_indexed_table_products', 'mindweco_get_indexed_table_products' );

function mindweco_get_indexed_table_products() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	global $wpdb;

	$table_name = $wpdb->prefix . 'mindweco_indexed_products';

	$results = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT i.id AS index_id, i.item_id, i.post_id, i.category_id,
				p.post_title, p.post_name, p.post_status, p.post_author,
				u.display_name AS author_name
			FROM `{$table_name}` i
			LEFT JOIN `{$wpdb->prefix}posts` p ON i.post_id = p.ID
			LEFT JOIN `{$wpdb->prefix}users` u ON p.post_author = u.ID
			WHERE p.post_type = %s
			ORDER BY i.id ASC",
			'product'
		)
	);

	$html = '';

	if ( $results ) {
		foreach ( $results as $r ) {
			$product       = wc_get_product( $r->post_id );
			$regular_price = 0;
			$sale_price    = 0;

			if ( $product ) {
				if ( $product->is_type( 'variable' ) ) {
					$variation_prices = $product->get_variation_prices( true );
					$regular_price    = ! empty( $variation_prices['regular_price'] ) ? min( $variation_prices['regular_price'] ) : 0;
					$sale_price       = ! empty( $variation_prices['sale_price'] ) ? min( $variation_prices['sale_price'] ) : 0;
				} else {
					$regular_price = floatval( $product->get_regular_price() );
					$sale_price    = floatval( $product->get_sale_price() );
				}
			}

			$image_url = $product ? wp_get_attachment_url( $product->get_image_id() ) : '';
			$img_html  = $image_url
				? '<img src="' . esc_url( $image_url ) . '" style="width:40px;height:40px;object-fit:cover;border-radius:4px;" />'
				: '<span style="color:#999;font-size:11px;">' . esc_html__( 'No image', 'mind-web-concierge' ) . '</span>';

			$html .= '<tr>';
			$html .= '<td>' . esc_html( $r->index_id ) . '</td>';
			$html .= '<td>' . esc_html( $r->item_id ) . '</td>';
			$html .= '<td>' . esc_html( $r->post_id ) . '</td>';
			$html .= '<td>' . esc_html( $r->category_id ) . '</td>';
			$html .= '<td>' . $img_html . '</td>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			$html .= '<td>' . esc_html( $r->post_title ) . '</td>';
			$html .= '<td>' . wc_price( $regular_price ) . '</td>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wc_price() returns sanitized HTML.
			$html .= '<td>' . wc_price( $sale_price ) . '</td>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wc_price() returns sanitized HTML.
			$html .= '<td>' . esc_html( $r->author_name ) . '</td>';
			$html .= '<td>';
			$html .= '<button class="button button-small button-link-delete unindex-product p-1"';
			$html .= ' data-item-id="' . esc_attr( $r->item_id ) . '"';
			$html .= ' data-category-id="' . esc_attr( $r->category_id ) . '">';
			$html .= '<span class="dashicons dashicons-trash"></span> ' . esc_html__( 'UnIndex', 'mind-web-concierge' );
			$html .= '</button>';
			$html .= '</td>';
			$html .= '</tr>';
		}
	}

	wp_send_json_success( $html );
}

add_action( 'wp_ajax_mindweco_delete_indexed_products', 'mindweco_delete_indexed_products' );

function mindweco_delete_indexed_products() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	global $wpdb;

	$item_id     = isset( $_POST['item_id'] ) ? sanitize_text_field( wp_unslash( $_POST['item_id'] ) ) : '';
	$category_id = isset( $_POST['category_id'] ) ? intval( $_POST['category_id'] ) : 0;

	if ( ! $item_id || ! $category_id ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid item_id or category_id.', 'mind-web-concierge' ) ) );
		return;
	}

	$table = $wpdb->prefix . 'mindweco_indexed_products';

	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

	if ( empty( $base_url ) || empty( $token ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Missing Base URL or Access Token.', 'mind-web-concierge' ) ) );
		return;
	}

	$fresh_token = mindweco_plugin_refresh_token();
	if ( $fresh_token ) {
		$token = $fresh_token;
	}


	$api_response = mindweco_plugin_api_delete_indexed_items( $base_url, $token, $category_id, $item_id );

	if ( isset( $api_response['http_code'] ) && 401 === (int) $api_response['http_code'] ) {
		$new_token = mindweco_plugin_refresh_token();
		if ( $new_token ) {
			$api_response = mindweco_plugin_api_delete_indexed_items( $base_url, $new_token, $category_id, $item_id );
		}
	}

	$count_before = intval( $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	$deleted = $wpdb->delete(
		$table,
		array( 'item_id' => $item_id, 'category_id' => $category_id ),
		array( '%s', '%d' )
	);

	$count_after = intval( $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	if ( false === $deleted ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Database delete failed.', 'mind-web-concierge' ) ) );
		return;
	}

	wp_send_json_success( array(
		'message'      => $deleted > 0
			? esc_html__( 'Item unindexed successfully.', 'mind-web-concierge' )
			: esc_html__( 'Item removed from API but was not in local database.', 'mind-web-concierge' ),
		'deleted_rows' => $deleted,
		'count_before' => $count_before,
		'count_after'  => $count_after,
	) );
}

add_action( 'wp_ajax_mindweco_unindex_all_products', 'mindweco_unindex_all_products' );

function mindweco_unindex_all_products() {
	check_ajax_referer( 'mindweco_product_catalog_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
		return;
	}

	global $wpdb;

	$table    = $wpdb->prefix . 'mindweco_indexed_products';
	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
	
	$all_items = $wpdb->get_results( "SELECT item_id, category_id FROM `{$table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	if ( $base_url && $token ) {
		$fresh_token = mindweco_plugin_refresh_token();
		if ( $fresh_token ) {
			$token = $fresh_token;
		}

		foreach ( $all_items as $item ) {
			mindweco_plugin_api_delete_indexed_items( $base_url, $token, $item->category_id, $item->item_id );
		}
	}

	$deleted = $wpdb->query( "TRUNCATE TABLE `{$table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	if ( false !== $deleted ) {
		wp_send_json_success( array( 'message' => esc_html__( 'All indexed products have been deleted.', 'mind-web-concierge' ) ) );
	} else {
		wp_send_json_error( array( 'message' => esc_html__( 'Failed to delete products.', 'mind-web-concierge' ) ) );
	}
}

add_action( 'save_post_product', 'mindweco_handle_product_save', 10, 3 );
/**
 * Indexes a product when it is saved/published.
 *
 * @param int     $post_id Post ID.
 * @param WP_Post $post    Post object.
 * @param bool    $update  Whether this is an update.
 */
function mindweco_handle_product_save( $post_id, $post, $update ) {
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( wp_is_post_revision( $post_id ) ) {
		return;
	}
	if ( 'product' !== $post->post_type ) {
		return;
	}
	if ( 'publish' !== $post->post_status ) {
		return;
	}

	global $wpdb;

	$options     = get_option( 'mindweco_plugin_options', array() );
	$base_url    = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
	$category    = get_option( 'mindweco_plugin_category', array() );
	$category_id = isset( $category['id'] ) ? intval( $category['id'] ) : null;

	if ( ! $base_url || ! $token || ! $category_id ) {
		return;
	}

	$product = wc_get_product( $post_id );
	if ( ! $product ) {
		return;
	}

	$table    = $wpdb->prefix . 'mindweco_indexed_products';
	$existing = $wpdb->get_row(
		$wpdb->prepare( "SELECT * FROM `{$table}` WHERE product_id = %d LIMIT 1", $post_id )
	);

	$wp_json_array = mindweco_build_product_payload( $product );
	$meta = array(
		'categories' => wp_get_post_terms( $post_id, 'product_cat', array( 'fields' => 'names' ) ),
		'tags'       => wp_get_post_terms( $post_id, 'product_tag', array( 'fields' => 'names' ) ),
	);

	$chunk_size    = intval( get_option( 'mindweco_chunk_size' ) ) ?: 1000;
	$chunk_overlap = intval( get_option( 'mindweco_chunk_overlap' ) ) ?: 200;

	$fresh_token = mindweco_plugin_refresh_token();
	if ( $fresh_token ) {
		$token = $fresh_token;
	}

	$api_response = mindweco_plugin_api_index_products(
		$base_url, $token, $category_id,
		$chunk_size, $chunk_overlap,
		$wp_json_array, $meta, ''
	);

	if ( isset( $api_response['error'] ) ) {
		return;
	}

	$new_item_id = isset( $api_response['item_id'] ) ? $api_response['item_id'] : null;
	if ( empty( $new_item_id ) ) {
		return;
	}

	if ( $existing ) {
		$wpdb->update(
			$table,
			array( 'item_id' => $new_item_id, 'category_id' => $category_id, 'created_at' => current_time( 'mysql' ) ),
			array( 'id' => $existing->id ),
			array( '%s', '%d', '%s' ),
			array( '%d' )
		);
	} else {
		$wpdb->insert(
			$table,
			array(
				'product_id'  => $post_id,
				'post_id'     => $post_id,
				'item_id'     => $new_item_id,
				'category_id' => $category_id,
				'created_at'  => current_time( 'mysql' ),
			),
			array( '%d', '%d', '%s', '%d', '%s' )
		);
	}
}

add_action( 'woocommerce_update_product', 'mindweco_handle_product_update', 10, 1 );
/**
 * Re-indexes a product when it is updated.
 *
 * @param int $product_id Product ID.
 */
function mindweco_handle_product_update( $product_id ) {
	$product = wc_get_product( $product_id );
	if ( ! $product || 'publish' !== $product->get_status() ) {
		return;
	}

	global $wpdb;

	$options     = get_option( 'mindweco_plugin_options', array() );
	$base_url    = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
	$category    = get_option( 'mindweco_plugin_category', array() );
	$category_id = isset( $category['id'] ) ? intval( $category['id'] ) : null;

	if ( ! $base_url || ! $token || ! $category_id ) {
		return;
	}

	$table    = $wpdb->prefix . 'mindweco_indexed_products';
	$existing = $wpdb->get_row(
		$wpdb->prepare( "SELECT * FROM `{$table}` WHERE product_id = %d LIMIT 1", $product_id )
	);

	if ( ! $existing || empty( $existing->item_id ) ) {
		return;
	}

	$wp_json_array = mindweco_build_product_payload( $product );
	$meta = array(
		'categories' => wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'names' ) ),
		'tags'       => wp_get_post_terms( $product_id, 'product_tag', array( 'fields' => 'names' ) ),
	);

	$chunk_size    = intval( get_option( 'mindweco_chunk_size' ) ) ?: 1000;
	$chunk_overlap = intval( get_option( 'mindweco_chunk_overlap' ) ) ?: 200;

	$fresh_token = mindweco_plugin_refresh_token();
	if ( $fresh_token ) {
		$token = $fresh_token;
	}

	$api_response = mindweco_plugin_api_index_products(
		$base_url, $token, $category_id,
		$chunk_size, $chunk_overlap,
		$wp_json_array, $meta, $existing->item_id
	);

	if ( isset( $api_response['error'] ) ) {
		return;
	}

	$wpdb->update(
		$table,
		array( 'created_at' => current_time( 'mysql' ) ),
		array( 'id' => $existing->id ),
		array( '%s' ),
		array( '%d' )
	);
}

add_action( 'woocommerce_delete_product', 'mindweco_handle_product_delete', 10, 1 );
add_action( 'woocommerce_trash_product', 'mindweco_handle_product_delete', 10, 1 );
/**
 * Removes a product from the index when deleted or trashed.
 *
 * @param int $product_id Product ID.
 */
function mindweco_handle_product_delete( $product_id ) {
	global $wpdb;

	$indexed_product = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT item_id, category_id FROM `{$wpdb->prefix}mindweco_indexed_products` WHERE post_id = %d LIMIT 1",
			$product_id
		)
	);

	if ( ! $indexed_product ) {
		return;
	}

	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

	if ( $base_url && $token && $indexed_product->item_id && $indexed_product->category_id ) {
		$fresh_token = mindweco_plugin_refresh_token();
		if ( $fresh_token ) {
			$token = $fresh_token;
		}

		$api_response = mindweco_plugin_api_delete_indexed_items(
			$base_url, $token,
			$indexed_product->category_id,
			$indexed_product->item_id
		);

		if ( isset( $api_response['http_code'] ) && 401 === (int) $api_response['http_code'] ) {
			$new_token = mindweco_plugin_refresh_token();
			if ( $new_token ) {
				mindweco_plugin_api_delete_indexed_items(
					$base_url, $new_token,
					$indexed_product->category_id,
					$indexed_product->item_id
				);
			}
		}
	}

	$deleted = $wpdb->delete(
		$wpdb->prefix . 'mindweco_indexed_products',
		array( 'post_id' => $product_id ),
		array( '%d' )
	);

	if ( $deleted ) {
		wp_cache_delete( 'mindweco_has_items_' . get_current_blog_id(), 'mindweco' );
	}
}


add_action( 'transition_post_status', 'mindweco_handle_product_status_transition', 10, 3 );
/**
 * Removes a product from the index when it is unpublished.
 *
 * @param string  $new_status New post status.
 * @param string  $old_status Old post status.
 * @param WP_Post $post       Post object.
 */
function mindweco_handle_product_status_transition( $new_status, $old_status, $post ) {
	if ( 'product' !== $post->post_type ) {
		return;
	}
	if ( 'publish' !== $old_status || 'publish' === $new_status ) {
		return;
	}

	global $wpdb;

	$table           = $wpdb->prefix . 'mindweco_indexed_products';
	$indexed_product = $wpdb->get_row(
		$wpdb->prepare( "SELECT * FROM `{$table}` WHERE product_id = %d LIMIT 1", $post->ID )
	);

	if ( ! $indexed_product || empty( $indexed_product->item_id ) ) {
		return;
	}

	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

	if ( $base_url && $token ) {
		$fresh_token = mindweco_plugin_refresh_token();
		if ( $fresh_token ) {
			$token = $fresh_token;
		}

		mindweco_plugin_api_delete_indexed_items(
			$base_url, $token,
			$indexed_product->category_id,
			$indexed_product->item_id
		);
	}

	$wpdb->delete( $table, array( 'product_id' => $post->ID ), array( '%d' ) );
	wp_cache_delete( 'mindweco_has_items_' . get_current_blog_id(), 'mindweco' );
}


/**
 * Builds the product data array sent to the indexing API.
 * Extracted to avoid duplicating the same 30+ lines in every hook.
 *
 * @param WC_Product $product WooCommerce product object.
 * @return array
 */
function mindweco_build_product_payload( $product ) {
	$categories_full = array();
	foreach ( $product->get_category_ids() as $cat_id ) {
		$term = get_term( $cat_id );
		if ( $term ) {
			$categories_full[] = array( 'id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug );
		}
	}

	$tags_full = array();
	foreach ( $product->get_tag_ids() as $tag_id ) {
		$term = get_term( $tag_id );
		if ( $term ) {
			$tags_full[] = array( 'id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug );
		}
	}

	$gallery = array();
	foreach ( $product->get_gallery_image_ids() as $img_id ) {
		$gallery[] = wp_get_attachment_url( $img_id );
	}

	$attributes = array();
	foreach ( $product->get_attributes() as $attribute ) {
		$attributes[] = array(
			'name'      => $attribute->get_name(),
			'visible'   => $attribute->get_visible(),
			'variation' => $attribute->get_variation(),
			'options'   => $attribute->get_options(),
		);
	}

	$variations = array();
	if ( $product->is_type( 'variable' ) ) {
		foreach ( $product->get_children() as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			if ( ! $variation ) {
				continue;
			}
			$variations[] = array(
				'id'         => $variation->get_id(),
				'price'      => $variation->get_price(),
				'sku'        => $variation->get_sku(),
				'stock'      => $variation->get_stock_quantity(),
				'attributes' => $variation->get_attributes(),
			);
		}
	}

	return array(
		'id'                => $product->get_id(),
		'name'              => $product->get_name(),
		'slug'              => $product->get_slug(),
		'status'            => $product->get_status(),
		'type'              => $product->get_type(),
		'price'             => $product->get_price(),
		'regular_price'     => $product->get_regular_price(),
		'sale_price'        => $product->get_sale_price(),
		'sku'               => $product->get_sku(),
		'stock_quantity'    => $product->get_stock_quantity(),
		'stock_status'      => $product->get_stock_status(),
		'manage_stock'      => $product->get_manage_stock(),
		'description'       => $product->get_description(),
		'short_description' => $product->get_short_description(),
		'categories'        => $categories_full,
		'tags'              => $tags_full,
		'featured_image'    => wp_get_attachment_url( $product->get_image_id() ),
		'gallery_images'    => $gallery,
		'attributes'        => $attributes,
		'variations'        => $variations,
		'date_created'      => $product->get_date_created() ? $product->get_date_created()->date( 'c' ) : null,
		'date_modified'     => $product->get_date_modified() ? $product->get_date_modified()->date( 'c' ) : null,
		'permalink'         => $product->get_permalink(),
	);
}
