<?php
	add_action('wp_ajax_wpsis_load_products', 'wpsis_load_products');
	function wpsis_load_products() {
		check_ajax_referer('wpsis_nonce_action', 'nonce');
	
		$args = array('post_type'=>'product','posts_per_page'=>-1,'post_status'=>'publish');
		$products = new WP_Query($args);
	
		if($products->have_posts()){
			echo '<table class="wp-list-table widefat fixed striped">';
			echo '<thead><tr><th>Include</th><th>Image</th><th>Title</th><th>ID</th><th>Price</th><th>Sales</th><th>Priority</th></tr></thead><tbody>';
			while ( $products->have_posts() ) {
				$products->the_post();
			
				$id    = get_the_ID();
				$title = get_the_title();
				$price = get_post_meta( $id, '_price', true );
				$img   = get_the_post_thumbnail_url( $id, [50, 50] );
				$link  = get_permalink( $id );
			
				echo "<tr class='wpsis_product_row' data-id='{$id}'>";
				echo "<td><input type='checkbox' class='wpsis_include' checked></td>";
				echo "<td><a href='{$link}' target='_blank'><img src='{$img}' width='50' height='50'></a></td>";
				echo "<td>{$title}</td>";
				echo "<td>{$id}</td>";
				echo "<td>{$price}</td>";
				echo "<td id='sales_{$id}'>0</td>";
				echo "<td>
						<input type='number'
							   class='wpsis_priority'
							   id='priority_{$id}'
							   value='0.5'
							   step='0.1'
							   min='0'
							   max='1'>
					  </td>";
				echo "</tr>";
			}
			echo '</tbody></table>';
			wp_reset_postdata();
		}
	
		wp_die();
	}
	
	add_action('wp_ajax_wpsis_analyze_priority', 'wpsis_analyze_priority');
	
	function wpsis_analyze_priority() {
		global $wpdb;
	
		check_ajax_referer('wpsis_nonce_action', 'nonce');
	
		$user_id = get_current_user_id();
		$state_key = "wpsis_priority_state_{$user_id}";
	
		$days = intval($_POST['days'] ?? 30);
		$batch_size = 50;
		$reset = !empty($_POST['reset']);

	
		$orders_table = $wpdb->prefix . 'posts';
		$order_items_table = $wpdb->prefix . 'woocommerce_order_items';
		$order_itemmeta = $wpdb->prefix . 'woocommerce_order_itemmeta';
	
		// INIT STATE
		if ($reset || !get_transient($state_key)) {
	
			$total_orders = $wpdb->get_var($wpdb->prepare("
				SELECT COUNT(ID)
				FROM {$orders_table}
				WHERE post_type = 'shop_order'
				AND post_status IN ('wc-completed','wc-processing')
				AND post_date > NOW() - INTERVAL %d DAY
			", $days));
	
			$state = [
				'last_order_id'   => PHP_INT_MAX,
				'total_orders'    => intval($total_orders),
				'processed_orders'=> 0,
				'product_sales'   => [],
			];
	
			set_transient($state_key, $state, 12 * HOUR_IN_SECONDS);
		}
	
		$state = get_transient($state_key);
	
		// STEP 1: GET NEXT BATCH OF ORDERS
		$order_ids = $wpdb->get_col($wpdb->prepare("
			SELECT ID
			FROM {$orders_table}
			WHERE post_type = 'shop_order'
			AND post_status IN ('wc-completed','wc-processing')
			AND post_date > NOW() - INTERVAL %d DAY
			AND ID < %d
			ORDER BY ID DESC
			LIMIT %d
		", $days, $state['last_order_id'], $batch_size));
	
		if (empty($order_ids)) {
			delete_transient($state_key);
			wp_send_json([
				'done' => true,
				'progress' => [
					'total' => $state['total_orders'],
					'processed' => $state['processed_orders'],
					'remaining' => 0
				]
			]);
		}
	
		// STEP 2: GET PRODUCTS FOR THESE ORDERS
		$ids_placeholder = implode(',', array_map('intval', $order_ids));
	
		$results = $wpdb->get_results("
			SELECT im.meta_value as product_id, COUNT(*) as sales
			FROM {$order_items_table} i
			INNER JOIN {$order_itemmeta} im 
				ON i.order_item_id = im.order_item_id
				AND im.meta_key = '_product_id'
			WHERE i.order_id IN ($ids_placeholder)
			GROUP BY im.meta_value
		");
	
		// ACCUMULATE SALES (CRITICAL FIX)
		foreach ($results as $row) {
			$pid = intval($row->product_id);
			$sales = intval($row->sales);
	
			if (!isset($state['product_sales'][$pid])) {
				$state['product_sales'][$pid] = 0;
			}
	
			$state['product_sales'][$pid] += $sales; // accumulate
		}
	
		// UPDATE STATE
		$state['processed_orders'] += count($order_ids);
		$state['last_order_id'] = min($order_ids);
	
		set_transient($state_key, $state, 12 * HOUR_IN_SECONDS);
	
		// BUILD RESPONSE
		$response_products = [];
	
		foreach ($state['product_sales'] as $pid => $total_sales) {
			$priority = min(1, 0.5 + ($total_sales / 50));
	
			$response_products[] = [
				'product_id' => $pid,
				'sales'      => $total_sales,
				'priority'   => number_format($priority, 2),
			];
		}
	
		wp_send_json([
			'done' => false,
			'batch_size' => count($order_ids),
			'progress' => [
				'total'     => $state['total_orders'],
				'processed' => $state['processed_orders'],
				'remaining' => max(0, $state['total_orders'] - $state['processed_orders'])
			],
			'products' => $response_products
		]);
	}

			
							
	add_action('wp_ajax_wpsis_generate_sitemap', 'wpsis_generate_sitemap');
	function wpsis_generate_sitemap() {
	
		check_ajax_referer('wpsis_nonce_action', 'nonce');
	
		$raw_products = $_POST['products'] ?? [];
		if (empty($raw_products) || !is_array($raw_products)) {
			wp_send_json(['error' => 'No products selected']);
		}
	
		$products = [];
		foreach ($raw_products as $p) {
			$id       = isset($p['id']) ? intval($p['id']) : 0;
			$loc      = isset($p['loc']) ? esc_url_raw($p['loc']) : '';
			$image    = isset($p['image']) ? esc_url_raw($p['image']) : '';
			$priority = isset($p['priority']) ? floatval($p['priority']) : 0.5;
	
			if ($id) {
				$products[] = compact('id', 'loc', 'image', 'priority');
			}
		}
	
		if (empty($products)) {
			wp_send_json(['error' => 'No valid products after sanitization']);
		}
	
		// Sort products by priority descending
		usort($products, fn($a, $b) => $b['priority'] <=> $a['priority']);
	
		$upload_dir = wp_upload_dir();
		$file = $upload_dir['basedir'] . '/dynamic_sitemap.xml';
	
		// Remove old file first
		if (file_exists($file)) {
			@unlink($file);
		}
	
		$fp = fopen($file, 'w');
		if (!$fp) {
			wp_send_json(['error' => 'Cannot open sitemap file for writing.']);
		}
	
		// Write XML header
		fwrite($fp, '<?xml version="1.0" encoding="UTF-8"?>' . "\n");
		fwrite($fp, '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ');
		fwrite($fp, 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "\n");
	
		$used_priorities = [];
		$warnings = [];
		$count = 0;
	
		// Initialize lastmod timestamp (start from current hour)
		$current_time = time();
	
		foreach ($products as $index => $p) {
	
			$priority = min(max(floatval($p['priority']), 0.0), 1.0);
			// Adjust slightly if duplicate
			while (in_array($priority, $used_priorities, true)) {
				$priority -= 0.01;
				if ($priority < 0.5) $priority = 0.5;
			}
			$priority = number_format($priority, 2, '.', '');
			$used_priorities[] = $priority;
	
			$loc   = isset($p['loc']) ? esc_html($p['loc']) : '';
			// Remove WordPress thumbnail suffix (-80x80, -150x150, etc.) from images
			$image = isset($p['image']) ? esc_html(preg_replace('/-(\d+)x(\d+)(?=\.[a-z]{3,4}$)/i', '', $p['image'])) : '';
	
			// Lastmod: stagger by 1 hour per product
			$lastmod = gmdate('Y-m-d\TH:i:s+00:00', $current_time - ($index * 2 * 3600));
	
			if (empty($loc)) {
				$warnings[] = "Product ID {$p['id']} missing URL, writing empty <loc>";
			}
	
			fwrite($fp, "  <url>\n");
			fwrite($fp, "    <loc>{$loc}</loc>\n");
			fwrite($fp, "    <priority>{$priority}</priority>\n");
			fwrite($fp, "    <lastmod>{$lastmod}</lastmod>\n");
			fwrite($fp, "    <image:image>\n");
			fwrite($fp, "      <image:loc>{$image}</image:loc>\n");
			fwrite($fp, "    </image:image>\n");
			fwrite($fp, "  </url>\n");
	
			$count++;
	
			if ($count % 100 === 0) {
				fflush($fp);
			}
		}
	
		fwrite($fp, "</urlset>\n");
		fclose($fp);
	
		wp_send_json([
			'processed' => $count,
			'total'     => count($products),
			'percent'   => 100,
			'done'      => true,
			'url'       => $upload_dir['baseurl'] . '/dynamic_sitemap.xml',
			'warnings'  => $warnings
		]);
	}