class-studiou-wc-product-cat-manage-manipulator.php 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. <?php
  2. /**
  3. * Category Manipulator class
  4. *
  5. * Handles manipulation operations for product categories
  6. *
  7. * @since 1.0.0
  8. * @package Studiou_WC_Product_Cat_Manage
  9. * @subpackage Studiou_WC_Product_Cat_Manage/includes
  10. */
  11. // If this file is called directly, abort.
  12. if (!defined('WPINC')) {
  13. die;
  14. }
  15. class Studiou_WC_Product_Cat_Manage_Manipulator {
  16. /**
  17. * Database handler
  18. *
  19. * @var Studiou_WC_Product_Cat_Manage_DB
  20. */
  21. private $db;
  22. /**
  23. * Constructor
  24. *
  25. * @param Studiou_WC_Product_Cat_Manage_DB $db Database handler
  26. */
  27. public function __construct($db) {
  28. $this->db = $db;
  29. // Register AJAX handlers
  30. add_action('wp_ajax_studiou_wcpcm_move_products', array($this, 'handle_move_products_ajax'));
  31. add_action('wp_ajax_studiou_wcpcm_batch_description', array($this, 'handle_batch_description_ajax'));
  32. add_action('wp_ajax_studiou_wcpcm_delete_products', array($this, 'handle_delete_products_ajax'));
  33. add_action('wp_ajax_studiou_wcpcm_delete_products_batch', array($this, 'handle_delete_products_batch_ajax'));
  34. add_action('wp_ajax_studiou_wcpcm_clear_media', array($this, 'handle_clear_media_ajax'));
  35. add_action('wp_ajax_studiou_wcpcm_clear_media_batch', array($this, 'handle_clear_media_batch_ajax'));
  36. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media', array($this, 'handle_remove_unassigned_media_ajax'));
  37. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media_batch', array($this, 'handle_remove_unassigned_media_batch_ajax'));
  38. add_action('wp_ajax_studiou_wcpcm_upvp_get_attributes', array($this, 'handle_upvp_get_attributes_ajax'));
  39. add_action('wp_ajax_studiou_wcpcm_upvp_get_attribute_values', array($this, 'handle_upvp_get_attribute_values_ajax'));
  40. add_action('wp_ajax_studiou_wcpcm_upvp_count', array($this, 'handle_upvp_count_ajax'));
  41. add_action('wp_ajax_studiou_wcpcm_upvp_apply', array($this, 'handle_upvp_apply_ajax'));
  42. // Add a test AJAX handler to verify AJAX is working
  43. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  44. // Debug: Log that the handler is being registered
  45. if (defined('WP_DEBUG') && WP_DEBUG) {
  46. error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
  47. }
  48. }
  49. /**
  50. * Handle AJAX batch description request
  51. */
  52. public function handle_batch_description_ajax() {
  53. // Clean all output buffers and prevent any output
  54. while (ob_get_level()) {
  55. ob_end_clean();
  56. }
  57. // Start a new output buffer to catch any unwanted output
  58. ob_start();
  59. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  60. $original_error_reporting = error_reporting();
  61. error_reporting(0);
  62. // Enable error logging only
  63. if (defined('WP_DEBUG') && WP_DEBUG) {
  64. error_log('STUDIOU WC: Batch description AJAX handler called');
  65. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  66. }
  67. try {
  68. // Check nonce
  69. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  70. wp_send_json_error(array(
  71. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  72. ));
  73. }
  74. // Check permissions
  75. if (!current_user_can('manage_woocommerce')) {
  76. wp_send_json_error(array(
  77. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  78. ));
  79. }
  80. // Validate input
  81. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  82. wp_send_json_error(array(
  83. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  84. ));
  85. }
  86. $selected_categories = array_map('intval', $_POST['selected_categories']);
  87. $description = sanitize_textarea_field($_POST['description']);
  88. // Debug logging
  89. if (defined('WP_DEBUG') && WP_DEBUG) {
  90. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  91. error_log('STUDIOU WC: Description: ' . $description);
  92. }
  93. // Validate categories
  94. if (empty($selected_categories)) {
  95. wp_send_json_error(array(
  96. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  97. ));
  98. }
  99. // Execute batch description operation
  100. $result = $this->update_categories_description($selected_categories, $description);
  101. // Debug logging
  102. if (defined('WP_DEBUG') && WP_DEBUG) {
  103. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  104. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  105. }
  106. // Clean any output that might have been generated
  107. ob_clean();
  108. // Return success response
  109. wp_send_json_success(array(
  110. 'message' => $result['message'],
  111. 'updated_count' => $result['updated_count'],
  112. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  113. ));
  114. } catch (Exception $e) {
  115. // Debug logging
  116. if (defined('WP_DEBUG') && WP_DEBUG) {
  117. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  118. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  119. }
  120. // Clean any output that might have been generated
  121. ob_clean();
  122. wp_send_json_error(array(
  123. 'message' => sprintf(
  124. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  125. $e->getMessage()
  126. )
  127. ));
  128. } finally {
  129. // Restore original error reporting
  130. error_reporting($original_error_reporting);
  131. // End the output buffer
  132. ob_end_clean();
  133. }
  134. }
  135. /**
  136. * Handle AJAX move products request
  137. */
  138. public function handle_move_products_ajax() {
  139. // Clean all output buffers and prevent any output
  140. while (ob_get_level()) {
  141. ob_end_clean();
  142. }
  143. // Start a new output buffer to catch any unwanted output
  144. ob_start();
  145. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  146. $original_error_reporting = error_reporting();
  147. error_reporting(0);
  148. // Enable error logging only
  149. if (defined('WP_DEBUG') && WP_DEBUG) {
  150. error_log('STUDIOU WC: AJAX handler called');
  151. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  152. }
  153. try {
  154. // Check nonce
  155. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  156. wp_send_json_error(array(
  157. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  158. ));
  159. }
  160. // Check permissions
  161. if (!current_user_can('manage_woocommerce')) {
  162. wp_send_json_error(array(
  163. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  164. ));
  165. }
  166. // Validate input
  167. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  168. wp_send_json_error(array(
  169. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  170. ));
  171. }
  172. $source_category_id = intval($_POST['source_category']);
  173. $target_category_id = intval($_POST['target_category']);
  174. // Debug logging
  175. if (defined('WP_DEBUG') && WP_DEBUG) {
  176. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  177. }
  178. // Validate categories
  179. if ($source_category_id === $target_category_id) {
  180. wp_send_json_error(array(
  181. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  182. ));
  183. }
  184. if ($source_category_id <= 0 || $target_category_id <= 0) {
  185. wp_send_json_error(array(
  186. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  187. ));
  188. }
  189. // Execute move operation
  190. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  191. // Debug logging
  192. if (defined('WP_DEBUG') && WP_DEBUG) {
  193. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  194. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  195. }
  196. // Clean any output that might have been generated
  197. ob_clean();
  198. // Return success response
  199. wp_send_json_success(array(
  200. 'message' => $result['message'],
  201. 'moved_count' => $result['moved_count'],
  202. 'source_count' => $result['source_count'],
  203. 'target_count' => $result['target_count'],
  204. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  205. ));
  206. } catch (Exception $e) {
  207. // Debug logging
  208. if (defined('WP_DEBUG') && WP_DEBUG) {
  209. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  210. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  211. }
  212. // Clean any output that might have been generated
  213. ob_clean();
  214. wp_send_json_error(array(
  215. 'message' => sprintf(
  216. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  217. $e->getMessage()
  218. )
  219. ));
  220. } finally {
  221. // Restore original error reporting
  222. error_reporting($original_error_reporting);
  223. // End the output buffer
  224. ob_end_clean();
  225. }
  226. }
  227. /**
  228. * Move all products from source category to target category
  229. *
  230. * @param int $source_category_id Source category ID
  231. * @param int $target_category_id Target category ID
  232. * @return array Result with counts and message
  233. * @throws Exception On error
  234. */
  235. public function move_products_between_categories($source_category_id, $target_category_id) {
  236. // Get source and target category terms
  237. $source_category = get_term($source_category_id, 'product_cat');
  238. $target_category = get_term($target_category_id, 'product_cat');
  239. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  240. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  241. }
  242. // Get initial count of products in source category using direct DB query
  243. $initial_source_count = $this->get_category_product_count($source_category_id);
  244. // Check if source category has any products
  245. if ($initial_source_count === 0) {
  246. $message = sprintf(
  247. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  248. $source_category->name
  249. );
  250. return array(
  251. 'moved_count' => 0,
  252. 'source_count' => 0,
  253. 'target_count' => $this->get_category_product_count($target_category_id),
  254. 'message' => $message
  255. );
  256. }
  257. // Get all products in source category using direct DB query
  258. $products = $this->get_products_in_category($source_category_id);
  259. $moved_count = 0;
  260. $failed_count = 0;
  261. if (defined('WP_DEBUG') && WP_DEBUG) {
  262. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  263. }
  264. // Move each product
  265. foreach ($products as $product_id) {
  266. // Get current categories for the product
  267. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  268. if (is_wp_error($current_categories)) {
  269. $failed_count++;
  270. if (defined('WP_DEBUG') && WP_DEBUG) {
  271. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  272. }
  273. continue;
  274. }
  275. // Remove source category and add target category
  276. $new_categories = array_diff($current_categories, array($source_category_id));
  277. $new_categories[] = $target_category_id;
  278. // Update product categories
  279. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  280. if (!is_wp_error($result)) {
  281. $moved_count++;
  282. if (defined('WP_DEBUG') && WP_DEBUG) {
  283. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  284. }
  285. } else {
  286. $failed_count++;
  287. if (defined('WP_DEBUG') && WP_DEBUG) {
  288. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  289. }
  290. }
  291. }
  292. // Get updated counts using direct DB query
  293. $source_count = $this->get_category_product_count($source_category_id);
  294. $target_count = $this->get_category_product_count($target_category_id);
  295. // Generate detailed result message
  296. if ($moved_count === 0 && count($products) > 0) {
  297. $message = sprintf(
  298. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  299. $source_category->name,
  300. $target_category->name,
  301. count($products)
  302. );
  303. } else {
  304. $message = sprintf(
  305. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  306. $moved_count,
  307. $source_category->name,
  308. $target_category->name,
  309. $source_count,
  310. $target_count
  311. );
  312. if ($failed_count > 0) {
  313. $message .= ' ' . sprintf(
  314. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  315. $failed_count
  316. );
  317. }
  318. }
  319. return array(
  320. 'moved_count' => $moved_count,
  321. 'source_count' => $source_count,
  322. 'target_count' => $target_count,
  323. 'failed_count' => $failed_count,
  324. 'message' => $message
  325. );
  326. }
  327. /**
  328. * Get product count for a category
  329. *
  330. * @param int $category_id Category ID
  331. * @return int Product count
  332. */
  333. private function get_category_product_count($category_id) {
  334. global $wpdb;
  335. // Use direct database query for more accurate counting
  336. $sql = "
  337. SELECT COUNT(DISTINCT p.ID)
  338. FROM {$wpdb->posts} p
  339. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  340. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  341. WHERE tt.term_id = %d
  342. AND tt.taxonomy = 'product_cat'
  343. AND p.post_type = 'product'
  344. AND p.post_status IN ('publish', 'private', 'draft')
  345. ";
  346. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  347. if (defined('WP_DEBUG') && WP_DEBUG) {
  348. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  349. }
  350. return intval($count);
  351. }
  352. /**
  353. * Get all products in a category
  354. *
  355. * @param int $category_id Category ID
  356. * @return array Array of product IDs
  357. */
  358. private function get_products_in_category($category_id) {
  359. global $wpdb;
  360. // Use direct database query to get products
  361. $sql = "
  362. SELECT DISTINCT p.ID
  363. FROM {$wpdb->posts} p
  364. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  365. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  366. WHERE tt.term_id = %d
  367. AND tt.taxonomy = 'product_cat'
  368. AND p.post_type = 'product'
  369. AND p.post_status IN ('publish', 'private', 'draft')
  370. ";
  371. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  372. if (defined('WP_DEBUG') && WP_DEBUG) {
  373. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  374. if (!empty($products)) {
  375. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  376. }
  377. }
  378. return $products ? array_map('intval', $products) : array();
  379. }
  380. /**
  381. * Update descriptions for multiple categories
  382. *
  383. * @param array $category_ids Array of category IDs
  384. * @param string $description New description for categories
  385. * @return array Result with counts and message
  386. * @throws Exception On error
  387. */
  388. public function update_categories_description($category_ids, $description) {
  389. $updated_count = 0;
  390. $failed_count = 0;
  391. $category_names = array();
  392. // Debug logging
  393. if (defined('WP_DEBUG') && WP_DEBUG) {
  394. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  395. }
  396. // Update each category
  397. foreach ($category_ids as $category_id) {
  398. // Get category term
  399. $category = get_term($category_id, 'product_cat');
  400. if (is_wp_error($category) || !$category) {
  401. $failed_count++;
  402. if (defined('WP_DEBUG') && WP_DEBUG) {
  403. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  404. }
  405. continue;
  406. }
  407. // Update category description
  408. $result = wp_update_term($category_id, 'product_cat', array(
  409. 'description' => $description
  410. ));
  411. if (!is_wp_error($result)) {
  412. $updated_count++;
  413. $category_names[] = $category->name;
  414. if (defined('WP_DEBUG') && WP_DEBUG) {
  415. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  416. }
  417. } else {
  418. $failed_count++;
  419. if (defined('WP_DEBUG') && WP_DEBUG) {
  420. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  421. }
  422. }
  423. }
  424. // Generate result message
  425. if ($updated_count === 0) {
  426. $message = sprintf(
  427. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  428. $failed_count
  429. );
  430. } else {
  431. $message = sprintf(
  432. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  433. $updated_count,
  434. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  435. );
  436. if ($failed_count > 0) {
  437. $message .= ' ' . sprintf(
  438. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  439. $failed_count
  440. );
  441. }
  442. }
  443. return array(
  444. 'updated_count' => $updated_count,
  445. 'failed_count' => $failed_count,
  446. 'message' => $message
  447. );
  448. }
  449. /**
  450. * Get all categories with product counts for select lists
  451. *
  452. * @return array Array of categories with ID, name, and product count
  453. */
  454. public function get_categories_with_counts() {
  455. $args = array(
  456. 'taxonomy' => 'product_cat',
  457. 'orderby' => 'name',
  458. 'hide_empty' => false,
  459. );
  460. $categories = get_terms($args);
  461. $categories_with_counts = array();
  462. if (!is_wp_error($categories)) {
  463. foreach ($categories as $category) {
  464. $product_count = $this->get_category_product_count($category->term_id);
  465. $categories_with_counts[] = array(
  466. 'id' => $category->term_id,
  467. 'name' => $category->name,
  468. 'count' => $product_count,
  469. 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
  470. );
  471. }
  472. }
  473. return $categories_with_counts;
  474. }
  475. /**
  476. * Handle AJAX delete products request (initial request to get product IDs)
  477. */
  478. public function handle_delete_products_ajax() {
  479. // Clean all output buffers and prevent any output
  480. while (ob_get_level()) {
  481. ob_end_clean();
  482. }
  483. // Start a new output buffer to catch any unwanted output
  484. ob_start();
  485. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  486. $original_error_reporting = error_reporting();
  487. error_reporting(0);
  488. // Enable error logging only
  489. if (defined('WP_DEBUG') && WP_DEBUG) {
  490. error_log('STUDIOU WC: Delete products AJAX handler called');
  491. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  492. }
  493. try {
  494. // Check nonce
  495. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  496. wp_send_json_error(array(
  497. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  498. ));
  499. }
  500. // Check permissions
  501. if (!current_user_can('manage_woocommerce')) {
  502. wp_send_json_error(array(
  503. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  504. ));
  505. }
  506. // Validate input
  507. if (!isset($_POST['delete_categories'])) {
  508. wp_send_json_error(array(
  509. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  510. ));
  511. }
  512. $category_ids = array_map('intval', $_POST['delete_categories']);
  513. // Debug logging
  514. if (defined('WP_DEBUG') && WP_DEBUG) {
  515. error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
  516. }
  517. // Validate categories
  518. if (empty($category_ids)) {
  519. wp_send_json_error(array(
  520. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  521. ));
  522. }
  523. // Get all products from selected categories
  524. $product_ids = $this->get_products_from_categories($category_ids);
  525. // Debug logging
  526. if (defined('WP_DEBUG') && WP_DEBUG) {
  527. error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
  528. }
  529. // Clean any output that might have been generated
  530. ob_clean();
  531. // Return product IDs for batch processing
  532. wp_send_json_success(array(
  533. 'product_ids' => $product_ids,
  534. 'total_count' => count($product_ids),
  535. 'message' => sprintf(
  536. __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
  537. count($product_ids)
  538. )
  539. ));
  540. } catch (Exception $e) {
  541. // Debug logging
  542. if (defined('WP_DEBUG') && WP_DEBUG) {
  543. error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
  544. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  545. }
  546. // Clean any output that might have been generated
  547. ob_clean();
  548. wp_send_json_error(array(
  549. 'message' => sprintf(
  550. __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
  551. $e->getMessage()
  552. )
  553. ));
  554. } finally {
  555. // Restore original error reporting
  556. error_reporting($original_error_reporting);
  557. // End the output buffer
  558. ob_end_clean();
  559. }
  560. }
  561. /**
  562. * Handle AJAX delete products batch request (processes products in batches)
  563. */
  564. public function handle_delete_products_batch_ajax() {
  565. // Clean all output buffers and prevent any output
  566. while (ob_get_level()) {
  567. ob_end_clean();
  568. }
  569. // Start a new output buffer to catch any unwanted output
  570. ob_start();
  571. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  572. $original_error_reporting = error_reporting();
  573. error_reporting(0);
  574. // Enable error logging only
  575. if (defined('WP_DEBUG') && WP_DEBUG) {
  576. error_log('STUDIOU WC: Delete products batch AJAX handler called');
  577. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  578. }
  579. try {
  580. // Check nonce
  581. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  582. wp_send_json_error(array(
  583. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  584. ));
  585. }
  586. // Check permissions
  587. if (!current_user_can('manage_woocommerce')) {
  588. wp_send_json_error(array(
  589. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  590. ));
  591. }
  592. // Validate input
  593. if (!isset($_POST['product_ids'])) {
  594. wp_send_json_error(array(
  595. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  596. ));
  597. }
  598. $product_ids = array_map('intval', $_POST['product_ids']);
  599. // Debug logging
  600. if (defined('WP_DEBUG') && WP_DEBUG) {
  601. error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
  602. }
  603. // Delete products in this batch
  604. $result = $this->delete_products_batch($product_ids);
  605. // Debug logging
  606. if (defined('WP_DEBUG') && WP_DEBUG) {
  607. error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  608. }
  609. // Clean any output that might have been generated
  610. ob_clean();
  611. // Return success response
  612. wp_send_json_success(array(
  613. 'deleted_count' => $result['deleted_count'],
  614. 'failed_count' => $result['failed_count'],
  615. 'failed_products' => $result['failed_products']
  616. ));
  617. } catch (Exception $e) {
  618. // Debug logging
  619. if (defined('WP_DEBUG') && WP_DEBUG) {
  620. error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
  621. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  622. }
  623. // Clean any output that might have been generated
  624. ob_clean();
  625. wp_send_json_error(array(
  626. 'message' => sprintf(
  627. __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
  628. $e->getMessage()
  629. )
  630. ));
  631. } finally {
  632. // Restore original error reporting
  633. error_reporting($original_error_reporting);
  634. // End the output buffer
  635. ob_end_clean();
  636. }
  637. }
  638. /**
  639. * Get all products from multiple categories
  640. *
  641. * @param array $category_ids Array of category IDs
  642. * @return array Array of unique product IDs (including parent products with variants)
  643. */
  644. private function get_products_from_categories($category_ids) {
  645. global $wpdb;
  646. if (empty($category_ids)) {
  647. return array();
  648. }
  649. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  650. // Get all products from selected categories (both simple and parent products)
  651. $sql = "
  652. SELECT DISTINCT p.ID
  653. FROM {$wpdb->posts} p
  654. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  655. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  656. WHERE tt.term_id IN ($placeholders)
  657. AND tt.taxonomy = 'product_cat'
  658. AND p.post_type = 'product'
  659. AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
  660. ";
  661. $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
  662. if (defined('WP_DEBUG') && WP_DEBUG) {
  663. error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
  664. }
  665. return $products ? array_map('intval', $products) : array();
  666. }
  667. /**
  668. * Delete a batch of products and their variants
  669. *
  670. * @param array $product_ids Array of product IDs to delete
  671. * @return array Result with counts
  672. */
  673. private function delete_products_batch($product_ids) {
  674. $deleted_count = 0;
  675. $failed_count = 0;
  676. $failed_products = array();
  677. foreach ($product_ids as $product_id) {
  678. try {
  679. // Get the product object
  680. $product = wc_get_product($product_id);
  681. if (!$product) {
  682. $failed_count++;
  683. $failed_products[] = $product_id;
  684. if (defined('WP_DEBUG') && WP_DEBUG) {
  685. error_log('STUDIOU WC: Product ' . $product_id . ' not found');
  686. }
  687. continue;
  688. }
  689. // If it's a variable product, delete all variations first
  690. if ($product->is_type('variable')) {
  691. $variations = $product->get_children();
  692. if (defined('WP_DEBUG') && WP_DEBUG) {
  693. error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
  694. }
  695. foreach ($variations as $variation_id) {
  696. $variation = wc_get_product($variation_id);
  697. if ($variation) {
  698. $variation->delete(true); // true = force delete permanently
  699. }
  700. }
  701. }
  702. // Delete the product permanently
  703. $result = $product->delete(true); // true = force delete permanently
  704. if ($result) {
  705. $deleted_count++;
  706. if (defined('WP_DEBUG') && WP_DEBUG) {
  707. error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
  708. }
  709. } else {
  710. $failed_count++;
  711. $failed_products[] = $product_id;
  712. if (defined('WP_DEBUG') && WP_DEBUG) {
  713. error_log('STUDIOU WC: Failed to delete product ' . $product_id);
  714. }
  715. }
  716. } catch (Exception $e) {
  717. $failed_count++;
  718. $failed_products[] = $product_id;
  719. if (defined('WP_DEBUG') && WP_DEBUG) {
  720. error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
  721. }
  722. }
  723. }
  724. return array(
  725. 'deleted_count' => $deleted_count,
  726. 'failed_count' => $failed_count,
  727. 'failed_products' => $failed_products
  728. );
  729. }
  730. /**
  731. * Get all media categories with file counts for select lists
  732. *
  733. * @return array Array of media categories with ID, name, and file count
  734. */
  735. public function get_media_categories_with_counts() {
  736. $taxonomy = $this->get_media_category_taxonomy();
  737. if (!$taxonomy) {
  738. return array();
  739. }
  740. $args = array(
  741. 'taxonomy' => $taxonomy,
  742. 'orderby' => 'name',
  743. 'hide_empty' => false,
  744. );
  745. $categories = get_terms($args);
  746. $categories_with_counts = array();
  747. if (!is_wp_error($categories)) {
  748. foreach ($categories as $category) {
  749. $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
  750. $categories_with_counts[] = array(
  751. 'id' => $category->term_id,
  752. 'name' => $category->name,
  753. 'count' => $file_count,
  754. 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
  755. );
  756. }
  757. }
  758. return $categories_with_counts;
  759. }
  760. /**
  761. * Get the media category taxonomy name
  762. *
  763. * Checks for common media category taxonomies used by popular plugins
  764. *
  765. * @return string|false Taxonomy name or false if none found
  766. */
  767. private function get_media_category_taxonomy() {
  768. $possible_taxonomies = array(
  769. 'media_category',
  770. 'attachment_category',
  771. 'media-category',
  772. );
  773. foreach ($possible_taxonomies as $taxonomy) {
  774. if (taxonomy_exists($taxonomy)) {
  775. error_log('STUDIOU WC MEDIA: Detected media taxonomy: ' . $taxonomy);
  776. return $taxonomy;
  777. }
  778. }
  779. // Try to find any taxonomy registered for attachments
  780. $attachment_taxonomies = get_object_taxonomies('attachment', 'names');
  781. if (!empty($attachment_taxonomies)) {
  782. // Filter out built-in taxonomies
  783. $custom_taxonomies = array_filter($attachment_taxonomies, function($tax) {
  784. return !in_array($tax, array('post_tag', 'category', 'post_format'));
  785. });
  786. if (!empty($custom_taxonomies)) {
  787. $found = reset($custom_taxonomies);
  788. error_log('STUDIOU WC MEDIA: Auto-detected attachment taxonomy: ' . $found);
  789. return $found;
  790. }
  791. }
  792. error_log('STUDIOU WC MEDIA: No media category taxonomy found. Registered attachment taxonomies: ' . implode(', ', $attachment_taxonomies ?? array()));
  793. return false;
  794. }
  795. /**
  796. * Get file count for a media category
  797. *
  798. * @param int $category_id Category term ID
  799. * @param string $taxonomy Taxonomy name
  800. * @return int File count
  801. */
  802. private function get_media_category_file_count($category_id, $taxonomy) {
  803. global $wpdb;
  804. $sql = "
  805. SELECT COUNT(DISTINCT p.ID)
  806. FROM {$wpdb->posts} p
  807. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  808. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  809. WHERE tt.term_id = %d
  810. AND tt.taxonomy = %s
  811. AND p.post_type = 'attachment'
  812. ";
  813. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
  814. return intval($count);
  815. }
  816. /**
  817. * Get all media IDs from multiple media categories
  818. *
  819. * @param array $category_ids Array of category term IDs
  820. * @return array Array of unique attachment IDs
  821. */
  822. private function get_media_from_categories($category_ids) {
  823. global $wpdb;
  824. $taxonomy = $this->get_media_category_taxonomy();
  825. error_log('STUDIOU WC MEDIA: get_media_from_categories called - taxonomy: ' . ($taxonomy ?: 'false') . ', category_ids: ' . implode(', ', $category_ids));
  826. if (!$taxonomy || empty($category_ids)) {
  827. error_log('STUDIOU WC MEDIA: No taxonomy or empty category_ids, returning empty');
  828. return array();
  829. }
  830. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  831. $sql = "
  832. SELECT DISTINCT p.ID
  833. FROM {$wpdb->posts} p
  834. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  835. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  836. WHERE tt.term_id IN ($placeholders)
  837. AND tt.taxonomy = %s
  838. AND p.post_type = 'attachment'
  839. ";
  840. $params = array_merge($category_ids, array($taxonomy));
  841. $media = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  842. error_log('STUDIOU WC MEDIA: Query found ' . ($media ? count($media) : 0) . ' media files');
  843. return $media ? array_map('intval', $media) : array();
  844. }
  845. /**
  846. * Delete a batch of media files permanently
  847. *
  848. * @param array $media_ids Array of attachment IDs to delete
  849. * @return array Result with counts
  850. */
  851. private function delete_media_batch($media_ids) {
  852. global $wpdb;
  853. $deleted_count = 0;
  854. $failed_count = 0;
  855. $failed_media = array();
  856. $affected_term_ids = array();
  857. $taxonomy = $this->get_media_category_taxonomy();
  858. // Ensure required file functions are loaded
  859. if (!function_exists('wp_delete_attachment')) {
  860. require_once ABSPATH . 'wp-admin/includes/post.php';
  861. }
  862. if (!function_exists('wp_delete_file')) {
  863. require_once ABSPATH . 'wp-includes/functions.php';
  864. }
  865. error_log('STUDIOU WC MEDIA: delete_media_batch called with ' . count($media_ids) . ' media IDs');
  866. foreach ($media_ids as $media_id) {
  867. try {
  868. $attachment = get_post($media_id);
  869. if (!$attachment || $attachment->post_type !== 'attachment') {
  870. $failed_count++;
  871. $failed_media[] = $media_id;
  872. error_log('STUDIOU WC MEDIA: Media file ' . $media_id . ' not found or not an attachment');
  873. continue;
  874. }
  875. // Collect affected term IDs before deletion for count update
  876. if ($taxonomy) {
  877. $terms = wp_get_object_terms($media_id, $taxonomy, array('fields' => 'ids'));
  878. if (!is_wp_error($terms)) {
  879. $affected_term_ids = array_merge($affected_term_ids, $terms);
  880. }
  881. }
  882. // Get file paths BEFORE deletion
  883. $file = get_attached_file($media_id);
  884. $meta = wp_get_attachment_metadata($media_id);
  885. $upload_dir = wp_get_upload_dir();
  886. error_log('STUDIOU WC MEDIA: Deleting media ID ' . $media_id . ', file: ' . ($file ?: 'none'));
  887. // Attempt standard WordPress deletion
  888. wp_delete_attachment($media_id, true);
  889. // Verify the post was actually deleted
  890. $still_exists = $wpdb->get_var($wpdb->prepare(
  891. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  892. $media_id
  893. ));
  894. if ($still_exists) {
  895. error_log('STUDIOU WC MEDIA: wp_delete_attachment did not delete post ' . $media_id . ', forcing manual deletion');
  896. // Force manual deletion: remove term relationships
  897. $all_taxonomies = get_object_taxonomies('attachment');
  898. if (!empty($all_taxonomies)) {
  899. wp_delete_object_term_relationships($media_id, $all_taxonomies);
  900. }
  901. // Remove all post meta
  902. $wpdb->delete($wpdb->postmeta, array('post_id' => $media_id));
  903. // Remove the post itself
  904. $wpdb->delete($wpdb->posts, array('ID' => $media_id));
  905. // Clean cache
  906. clean_post_cache($media_id);
  907. }
  908. // Delete physical files from disk
  909. if ($file && file_exists($file)) {
  910. @unlink($file);
  911. error_log('STUDIOU WC MEDIA: Deleted main file: ' . $file);
  912. }
  913. // Delete thumbnail/intermediate sizes
  914. if (!empty($meta['sizes']) && !empty($upload_dir['basedir'])) {
  915. $file_dir = !empty($file) ? trailingslashit(dirname($file)) : '';
  916. foreach ($meta['sizes'] as $size => $sizeinfo) {
  917. if (!empty($sizeinfo['file'])) {
  918. $intermediate_file = $file_dir . $sizeinfo['file'];
  919. if (file_exists($intermediate_file)) {
  920. @unlink($intermediate_file);
  921. }
  922. }
  923. }
  924. }
  925. // Final verification
  926. $final_check = $wpdb->get_var($wpdb->prepare(
  927. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  928. $media_id
  929. ));
  930. if (!$final_check) {
  931. $deleted_count++;
  932. error_log('STUDIOU WC MEDIA: Successfully deleted media file ' . $media_id);
  933. } else {
  934. $failed_count++;
  935. $failed_media[] = $media_id;
  936. error_log('STUDIOU WC MEDIA: FAILED to delete media file ' . $media_id . ' even after manual cleanup');
  937. }
  938. } catch (Exception $e) {
  939. $failed_count++;
  940. $failed_media[] = $media_id;
  941. error_log('STUDIOU WC MEDIA: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
  942. }
  943. }
  944. // Force update term counts for affected categories
  945. if ($taxonomy && !empty($affected_term_ids)) {
  946. $affected_term_ids = array_unique($affected_term_ids);
  947. wp_update_term_count_now($affected_term_ids, $taxonomy);
  948. error_log('STUDIOU WC MEDIA: Updated term counts for term IDs: ' . implode(', ', $affected_term_ids));
  949. }
  950. error_log('STUDIOU WC MEDIA: Batch result - deleted: ' . $deleted_count . ', failed: ' . $failed_count);
  951. return array(
  952. 'deleted_count' => $deleted_count,
  953. 'failed_count' => $failed_count,
  954. 'failed_media' => $failed_media
  955. );
  956. }
  957. /**
  958. * Handle AJAX clear media request (initial request to get media IDs)
  959. */
  960. public function handle_clear_media_ajax() {
  961. while (ob_get_level()) {
  962. ob_end_clean();
  963. }
  964. ob_start();
  965. $original_error_reporting = error_reporting();
  966. error_reporting(0);
  967. error_log('STUDIOU WC MEDIA: Clear media AJAX handler called');
  968. error_log('STUDIOU WC MEDIA: POST data: ' . print_r($_POST, true));
  969. try {
  970. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  971. error_log('STUDIOU WC MEDIA: Nonce verification failed');
  972. wp_send_json_error(array(
  973. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  974. ));
  975. return;
  976. }
  977. if (!current_user_can('manage_woocommerce')) {
  978. error_log('STUDIOU WC MEDIA: Permission check failed');
  979. wp_send_json_error(array(
  980. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  981. ));
  982. return;
  983. }
  984. if (!isset($_POST['media_categories'])) {
  985. error_log('STUDIOU WC MEDIA: media_categories not in POST data');
  986. wp_send_json_error(array(
  987. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  988. ));
  989. return;
  990. }
  991. $category_ids = array_map('intval', $_POST['media_categories']);
  992. if (empty($category_ids)) {
  993. error_log('STUDIOU WC MEDIA: Empty category_ids after intval mapping');
  994. wp_send_json_error(array(
  995. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  996. ));
  997. return;
  998. }
  999. $media_ids = $this->get_media_from_categories($category_ids);
  1000. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' media files to delete from categories: ' . implode(', ', $category_ids));
  1001. ob_clean();
  1002. wp_send_json_success(array(
  1003. 'media_ids' => $media_ids,
  1004. 'total_count' => count($media_ids),
  1005. 'message' => sprintf(
  1006. __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
  1007. count($media_ids)
  1008. )
  1009. ));
  1010. } catch (Exception $e) {
  1011. error_log('STUDIOU WC MEDIA: Clear media operation failed - ' . $e->getMessage());
  1012. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1013. ob_clean();
  1014. wp_send_json_error(array(
  1015. 'message' => sprintf(
  1016. __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
  1017. $e->getMessage()
  1018. )
  1019. ));
  1020. } finally {
  1021. error_reporting($original_error_reporting);
  1022. ob_end_clean();
  1023. }
  1024. }
  1025. /**
  1026. * Handle AJAX clear media batch request (processes media in batches)
  1027. */
  1028. public function handle_clear_media_batch_ajax() {
  1029. while (ob_get_level()) {
  1030. ob_end_clean();
  1031. }
  1032. ob_start();
  1033. $original_error_reporting = error_reporting();
  1034. error_reporting(0);
  1035. error_log('STUDIOU WC MEDIA: Clear media batch AJAX handler called');
  1036. try {
  1037. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1038. error_log('STUDIOU WC MEDIA: Batch nonce verification failed');
  1039. wp_send_json_error(array(
  1040. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  1041. ));
  1042. return;
  1043. }
  1044. if (!current_user_can('manage_woocommerce')) {
  1045. error_log('STUDIOU WC MEDIA: Batch permission check failed');
  1046. wp_send_json_error(array(
  1047. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  1048. ));
  1049. return;
  1050. }
  1051. if (!isset($_POST['media_ids'])) {
  1052. error_log('STUDIOU WC MEDIA: media_ids not in POST data');
  1053. wp_send_json_error(array(
  1054. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  1055. ));
  1056. return;
  1057. }
  1058. $media_ids = array_map('intval', $_POST['media_ids']);
  1059. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' media files for deletion');
  1060. $result = $this->delete_media_batch($media_ids);
  1061. error_log('STUDIOU WC MEDIA: Batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1062. ob_clean();
  1063. wp_send_json_success(array(
  1064. 'deleted_count' => $result['deleted_count'],
  1065. 'failed_count' => $result['failed_count'],
  1066. 'failed_media' => $result['failed_media']
  1067. ));
  1068. } catch (Exception $e) {
  1069. error_log('STUDIOU WC MEDIA: Clear media batch operation failed - ' . $e->getMessage());
  1070. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1071. ob_clean();
  1072. wp_send_json_error(array(
  1073. 'message' => sprintf(
  1074. __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
  1075. $e->getMessage()
  1076. )
  1077. ));
  1078. } finally {
  1079. error_reporting($original_error_reporting);
  1080. ob_end_clean();
  1081. }
  1082. }
  1083. /**
  1084. * Get count of unassigned unused media files
  1085. *
  1086. * @return int Count of media files not in any category and not referenced
  1087. */
  1088. public function get_unassigned_unused_media_count() {
  1089. $ids = $this->get_unassigned_unused_media_ids();
  1090. return count($ids);
  1091. }
  1092. /**
  1093. * Get IDs of media files that are not assigned to any media category
  1094. * and not used as featured image, product gallery image, or attached to any post.
  1095. *
  1096. * @return array Array of attachment IDs
  1097. */
  1098. public function get_unassigned_unused_media_ids() {
  1099. global $wpdb;
  1100. $taxonomy = $this->get_media_category_taxonomy();
  1101. // Base query: all attachments not used as featured image and not attached to a post
  1102. $sql = "
  1103. SELECT a.ID
  1104. FROM {$wpdb->posts} a
  1105. LEFT JOIN {$wpdb->postmeta} pm_thumb
  1106. ON a.ID = CAST(pm_thumb.meta_value AS UNSIGNED)
  1107. AND pm_thumb.meta_key = '_thumbnail_id'
  1108. WHERE a.post_type = 'attachment'
  1109. AND a.post_parent = 0
  1110. AND pm_thumb.meta_id IS NULL
  1111. ";
  1112. // If media category taxonomy exists, also exclude categorized media
  1113. if ($taxonomy) {
  1114. $sql .= $wpdb->prepare("
  1115. AND a.ID NOT IN (
  1116. SELECT tr.object_id
  1117. FROM {$wpdb->term_relationships} tr
  1118. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1119. WHERE tt.taxonomy = %s
  1120. )
  1121. ", $taxonomy);
  1122. }
  1123. $media_ids = $wpdb->get_col($sql);
  1124. if (empty($media_ids)) {
  1125. return array();
  1126. }
  1127. $media_ids = array_map('intval', $media_ids);
  1128. // Filter out media used in WooCommerce product galleries (_product_image_gallery)
  1129. $gallery_meta = $wpdb->get_col(
  1130. "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value != ''"
  1131. );
  1132. if (!empty($gallery_meta)) {
  1133. $gallery_ids = array();
  1134. foreach ($gallery_meta as $gallery_value) {
  1135. $ids = array_map('intval', array_filter(explode(',', $gallery_value)));
  1136. $gallery_ids = array_merge($gallery_ids, $ids);
  1137. }
  1138. $gallery_ids = array_unique($gallery_ids);
  1139. if (!empty($gallery_ids)) {
  1140. $media_ids = array_diff($media_ids, $gallery_ids);
  1141. }
  1142. }
  1143. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files');
  1144. return array_values($media_ids);
  1145. }
  1146. /**
  1147. * Handle AJAX remove unassigned media request (get IDs)
  1148. */
  1149. public function handle_remove_unassigned_media_ajax() {
  1150. while (ob_get_level()) {
  1151. ob_end_clean();
  1152. }
  1153. ob_start();
  1154. $original_error_reporting = error_reporting();
  1155. error_reporting(0);
  1156. error_log('STUDIOU WC MEDIA: Remove unassigned media AJAX handler called');
  1157. try {
  1158. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1159. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1160. return;
  1161. }
  1162. if (!current_user_can('manage_woocommerce')) {
  1163. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1164. return;
  1165. }
  1166. $media_ids = $this->get_unassigned_unused_media_ids();
  1167. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files to delete');
  1168. ob_clean();
  1169. wp_send_json_success(array(
  1170. 'media_ids' => $media_ids,
  1171. 'total_count' => count($media_ids),
  1172. 'message' => sprintf(
  1173. __('Found %d unused uncategorized media files to delete', 'studiou-wc-product-cat-manage'),
  1174. count($media_ids)
  1175. )
  1176. ));
  1177. } catch (Exception $e) {
  1178. error_log('STUDIOU WC MEDIA: Remove unassigned media failed - ' . $e->getMessage());
  1179. ob_clean();
  1180. wp_send_json_error(array(
  1181. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1182. ));
  1183. } finally {
  1184. error_reporting($original_error_reporting);
  1185. ob_end_clean();
  1186. }
  1187. }
  1188. /**
  1189. * Handle AJAX remove unassigned media batch request
  1190. */
  1191. public function handle_remove_unassigned_media_batch_ajax() {
  1192. while (ob_get_level()) {
  1193. ob_end_clean();
  1194. }
  1195. ob_start();
  1196. $original_error_reporting = error_reporting();
  1197. error_reporting(0);
  1198. error_log('STUDIOU WC MEDIA: Remove unassigned media batch AJAX handler called');
  1199. try {
  1200. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1201. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1202. return;
  1203. }
  1204. if (!current_user_can('manage_woocommerce')) {
  1205. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1206. return;
  1207. }
  1208. if (!isset($_POST['media_ids'])) {
  1209. wp_send_json_error(array('message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')));
  1210. return;
  1211. }
  1212. $media_ids = array_map('intval', $_POST['media_ids']);
  1213. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' unassigned media for deletion');
  1214. $result = $this->delete_media_batch($media_ids);
  1215. error_log('STUDIOU WC MEDIA: Unassigned batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1216. ob_clean();
  1217. wp_send_json_success(array(
  1218. 'deleted_count' => $result['deleted_count'],
  1219. 'failed_count' => $result['failed_count'],
  1220. 'failed_media' => $result['failed_media']
  1221. ));
  1222. } catch (Exception $e) {
  1223. error_log('STUDIOU WC MEDIA: Unassigned media batch failed - ' . $e->getMessage());
  1224. ob_clean();
  1225. wp_send_json_error(array(
  1226. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1227. ));
  1228. } finally {
  1229. error_reporting($original_error_reporting);
  1230. ob_end_clean();
  1231. }
  1232. }
  1233. // ========================================================================
  1234. // Update Product Variant Prices (UPVP) — v1.5.3
  1235. // Bulk-update regular_price on product_variation records by category +
  1236. // attribute filter. Touches only product records; never order items, carts,
  1237. // or historical order data.
  1238. // ========================================================================
  1239. /**
  1240. * Get list of attribute "heads" usable for variations.
  1241. *
  1242. * Source 1: every wc_get_attribute_taxonomies() entry (global attributes)
  1243. * — key = 'pa_<slug>', is_taxonomy = true.
  1244. * Source 2: distinct meta_key starting with 'attribute_' on product_variation
  1245. * rows that are NOT global taxonomies (custom product-level
  1246. * attributes flagged for variations) — key = '<slug>',
  1247. * is_taxonomy = false.
  1248. *
  1249. * @return array [ ['key' => string, 'label' => string, 'is_taxonomy' => bool], ... ]
  1250. */
  1251. public function get_variation_attribute_heads() {
  1252. global $wpdb;
  1253. $heads = array();
  1254. $seen = array();
  1255. // Source 1: global taxonomies.
  1256. $taxonomies = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : array();
  1257. if (!empty($taxonomies)) {
  1258. foreach ($taxonomies as $tax) {
  1259. $key = 'pa_' . $tax->attribute_name;
  1260. if (isset($seen[$key])) {
  1261. continue;
  1262. }
  1263. $seen[$key] = true;
  1264. $heads[] = array(
  1265. 'key' => $key,
  1266. 'label' => !empty($tax->attribute_label) ? $tax->attribute_label : $tax->attribute_name,
  1267. 'is_taxonomy' => true,
  1268. );
  1269. }
  1270. }
  1271. // Source 2: existing variation postmeta (attribute_*).
  1272. $sql = "
  1273. SELECT DISTINCT pm.meta_key
  1274. FROM {$wpdb->postmeta} pm
  1275. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1276. WHERE v.post_type = 'product_variation'
  1277. AND v.post_status IN ('publish','private')
  1278. AND pm.meta_key LIKE %s
  1279. ";
  1280. $rows = $wpdb->get_col($wpdb->prepare($sql, $wpdb->esc_like('attribute_') . '%'));
  1281. if (!empty($rows)) {
  1282. foreach ($rows as $meta_key) {
  1283. $slug = substr($meta_key, strlen('attribute_'));
  1284. if ($slug === '' || isset($seen[$slug])) {
  1285. continue;
  1286. }
  1287. $seen[$slug] = true;
  1288. $heads[] = array(
  1289. 'key' => $slug,
  1290. 'label' => wc_attribute_label($slug),
  1291. 'is_taxonomy' => (strpos($slug, 'pa_') === 0) || taxonomy_exists($slug),
  1292. );
  1293. }
  1294. }
  1295. // Source 3: variable parent products' _product_attributes postmeta.
  1296. // Catches attributes flagged "Used for variations" on the product's
  1297. // Attributes tab, even when (a) the attribute is a custom non-global
  1298. // entry, or (b) no variations have been generated yet.
  1299. $sql_parents = "
  1300. SELECT pm.meta_value
  1301. FROM {$wpdb->postmeta} pm
  1302. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1303. WHERE p.post_type = 'product'
  1304. AND p.post_status IN ('publish','private','draft')
  1305. AND pm.meta_key = '_product_attributes'
  1306. ";
  1307. $serialized_rows = $wpdb->get_col($sql_parents);
  1308. if (!empty($serialized_rows)) {
  1309. foreach ($serialized_rows as $serialized) {
  1310. $attrs = maybe_unserialize($serialized);
  1311. if (!is_array($attrs)) {
  1312. continue;
  1313. }
  1314. foreach ($attrs as $attr_key => $attr_data) {
  1315. if (!is_array($attr_data) || empty($attr_data['is_variation'])) {
  1316. continue;
  1317. }
  1318. $is_taxonomy = !empty($attr_data['is_taxonomy']);
  1319. $name = isset($attr_data['name']) ? $attr_data['name'] : $attr_key;
  1320. $key = $is_taxonomy ? $name : sanitize_title($name);
  1321. if ($key === '' || isset($seen[$key])) {
  1322. continue;
  1323. }
  1324. $seen[$key] = true;
  1325. $heads[] = array(
  1326. 'key' => $key,
  1327. 'label' => $is_taxonomy ? wc_attribute_label($key) : $name,
  1328. 'is_taxonomy' => $is_taxonomy,
  1329. );
  1330. }
  1331. }
  1332. }
  1333. // Sort alphabetically by label.
  1334. usort($heads, function($a, $b) {
  1335. return strcasecmp($a['label'], $b['label']);
  1336. });
  1337. return $heads;
  1338. }
  1339. /**
  1340. * Get distinct values for the given attribute key, scoped to existing
  1341. * variations (and optionally to a set of parent product categories).
  1342. *
  1343. * For taxonomy attributes (pa_*) the meta_value is the term slug; we
  1344. * resolve labels via get_term_by('slug', ..., $taxonomy).
  1345. *
  1346. * @param string $attribute_key E.g. 'pa_color' or 'size'.
  1347. * @param int[] $category_ids Optional list of parent product_cat term IDs.
  1348. * @return array [ ['value' => string, 'label' => string], ... ]
  1349. */
  1350. public function get_variation_attribute_values($attribute_key, $category_ids = array()) {
  1351. global $wpdb;
  1352. $attribute_key = sanitize_text_field($attribute_key);
  1353. if ($attribute_key === '') {
  1354. return array();
  1355. }
  1356. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1357. $params = array($meta_key);
  1358. $cat_join = '';
  1359. $cat_where = '';
  1360. if (!empty($category_ids)) {
  1361. $cat_ids = array_map('intval', $category_ids);
  1362. $cat_ids = array_filter($cat_ids, function($v) { return $v > 0; });
  1363. if (!empty($cat_ids)) {
  1364. $placeholders = implode(',', array_fill(0, count($cat_ids), '%d'));
  1365. $cat_join = "
  1366. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1367. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1368. ";
  1369. $cat_where = "
  1370. AND tt.taxonomy = 'product_cat'
  1371. AND tt.term_id IN ($placeholders)
  1372. ";
  1373. $params = array_merge($params, $cat_ids);
  1374. }
  1375. }
  1376. $sql = "
  1377. SELECT DISTINCT pm.meta_value
  1378. FROM {$wpdb->postmeta} pm
  1379. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1380. AND v.post_type = 'product_variation'
  1381. AND v.post_status IN ('publish','private')
  1382. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1383. AND p.post_type = 'product'
  1384. $cat_join
  1385. WHERE pm.meta_key = %s
  1386. AND pm.meta_value <> ''
  1387. $cat_where
  1388. ";
  1389. $values = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1390. $is_taxonomy = (strpos($attribute_key, 'pa_') === 0) || taxonomy_exists($attribute_key);
  1391. // Fallback: if SQL returned no values but the attribute exists on a
  1392. // variable parent's _product_attributes (e.g. variations not generated
  1393. // yet, or custom attribute), parse pipe-separated values from there.
  1394. if (empty($values)) {
  1395. $sanitized_key = $is_taxonomy
  1396. ? (strpos($attribute_key, 'pa_') === 0 ? $attribute_key : 'pa_' . $attribute_key)
  1397. : sanitize_title($attribute_key);
  1398. $sql_parents = "
  1399. SELECT pm.meta_value
  1400. FROM {$wpdb->postmeta} pm
  1401. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1402. WHERE p.post_type = 'product'
  1403. AND p.post_status IN ('publish','private','draft')
  1404. AND pm.meta_key = '_product_attributes'
  1405. ";
  1406. $rows = $wpdb->get_col($sql_parents);
  1407. $values = array();
  1408. if (!empty($rows)) {
  1409. foreach ($rows as $serialized) {
  1410. $attrs = maybe_unserialize($serialized);
  1411. if (!is_array($attrs) || !isset($attrs[$sanitized_key])) {
  1412. continue;
  1413. }
  1414. $entry = $attrs[$sanitized_key];
  1415. if (empty($entry['is_variation'])) {
  1416. continue;
  1417. }
  1418. if ($is_taxonomy) {
  1419. // Taxonomy custom values are stored as term IDs in 'value'.
  1420. $term_ids = !empty($entry['value']) ? wp_parse_id_list($entry['value']) : array();
  1421. if (empty($term_ids)) {
  1422. // Or the parent uses all terms — pull them from the taxonomy.
  1423. $tax_name = $sanitized_key;
  1424. $terms = get_terms(array('taxonomy' => $tax_name, 'hide_empty' => false));
  1425. if (!is_wp_error($terms)) {
  1426. foreach ($terms as $t) {
  1427. $values[] = $t->slug;
  1428. }
  1429. }
  1430. } else {
  1431. foreach ($term_ids as $tid) {
  1432. $term = get_term($tid, $sanitized_key);
  1433. if ($term && !is_wp_error($term)) {
  1434. $values[] = $term->slug;
  1435. }
  1436. }
  1437. }
  1438. } else {
  1439. $raw = isset($entry['value']) ? (string) $entry['value'] : '';
  1440. if ($raw !== '') {
  1441. $parts = array_map('trim', explode('|', $raw));
  1442. foreach ($parts as $p) {
  1443. if ($p !== '') {
  1444. $values[] = $p;
  1445. }
  1446. }
  1447. }
  1448. }
  1449. }
  1450. $values = array_values(array_unique($values));
  1451. }
  1452. }
  1453. if (empty($values)) {
  1454. return array();
  1455. }
  1456. $result = array();
  1457. foreach ($values as $value) {
  1458. $label = $value;
  1459. if ($is_taxonomy) {
  1460. $tax = (strpos($attribute_key, 'pa_') === 0) ? $attribute_key : 'pa_' . $attribute_key;
  1461. $term = get_term_by('slug', $value, $tax);
  1462. if ($term && !is_wp_error($term)) {
  1463. $label = $term->name;
  1464. }
  1465. }
  1466. $result[] = array(
  1467. 'value' => $value,
  1468. 'label' => $label,
  1469. );
  1470. }
  1471. usort($result, function($a, $b) {
  1472. return strcasecmp($a['label'], $b['label']);
  1473. });
  1474. return $result;
  1475. }
  1476. /**
  1477. * Find variations matching the filter.
  1478. *
  1479. * @param int[] $category_ids
  1480. * @param string $attribute_key
  1481. * @param string $attribute_value
  1482. * @return array ['count' => int, 'ids' => int[], 'sample' => array[]]
  1483. */
  1484. public function find_matching_variations($category_ids, $attribute_key, $attribute_value) {
  1485. global $wpdb;
  1486. $category_ids = array_filter(array_map('intval', (array) $category_ids), function($v) { return $v > 0; });
  1487. $attribute_key = sanitize_text_field($attribute_key);
  1488. $attribute_value = sanitize_text_field($attribute_value);
  1489. if (empty($category_ids) || $attribute_key === '' || $attribute_value === '') {
  1490. return array('count' => 0, 'ids' => array(), 'sample' => array());
  1491. }
  1492. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1493. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  1494. $sql = "
  1495. SELECT DISTINCT v.ID
  1496. FROM {$wpdb->posts} v
  1497. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1498. INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = v.ID
  1499. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1500. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1501. WHERE v.post_type = 'product_variation'
  1502. AND v.post_status IN ('publish','private')
  1503. AND p.post_type = 'product'
  1504. AND tt.taxonomy = 'product_cat'
  1505. AND tt.term_id IN ($placeholders)
  1506. AND pm.meta_key = %s
  1507. AND pm.meta_value = %s
  1508. ";
  1509. $params = array_merge($category_ids, array($meta_key, $attribute_value));
  1510. $ids = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1511. $ids = $ids ? array_map('intval', $ids) : array();
  1512. // Build a sample (up to 20).
  1513. $sample = array();
  1514. $slice = array_slice($ids, 0, 20);
  1515. foreach ($slice as $id) {
  1516. $variation = wc_get_product($id);
  1517. if (!$variation) {
  1518. continue;
  1519. }
  1520. $parent_id = $variation->get_parent_id();
  1521. $parent_name = '';
  1522. if ($parent_id) {
  1523. $parent = wc_get_product($parent_id);
  1524. if ($parent) {
  1525. $parent_name = $parent->get_name();
  1526. }
  1527. }
  1528. $sample[] = array(
  1529. 'id' => $id,
  1530. 'sku' => $variation->get_sku(),
  1531. 'name' => $variation->get_name(),
  1532. 'parent_name' => $parent_name,
  1533. 'current_price' => $variation->get_regular_price(),
  1534. );
  1535. }
  1536. return array(
  1537. 'count' => count($ids),
  1538. 'ids' => $ids,
  1539. 'sample' => $sample,
  1540. );
  1541. }
  1542. /**
  1543. * Apply new regular price to a list of variation IDs.
  1544. *
  1545. * @param int[] $variation_ids
  1546. * @param string $new_price
  1547. * @return array ['updated','failed','failed_ids','message']
  1548. */
  1549. public function apply_variant_price($variation_ids, $new_price) {
  1550. $variation_ids = array_filter(array_map('intval', (array) $variation_ids), function($v) { return $v > 0; });
  1551. // Validate price.
  1552. if (!is_numeric($new_price) || (float) $new_price < 0) {
  1553. return array(
  1554. 'updated' => 0,
  1555. 'failed' => 0,
  1556. 'failed_ids' => array(),
  1557. 'message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage'),
  1558. 'error' => true,
  1559. );
  1560. }
  1561. $formatted = wc_format_decimal($new_price);
  1562. $updated = 0;
  1563. $failed = 0;
  1564. $failed_ids = array();
  1565. $parent_ids = array();
  1566. foreach ($variation_ids as $id) {
  1567. try {
  1568. $variation = wc_get_product($id);
  1569. if (!$variation || !$variation->is_type('variation')) {
  1570. $failed++;
  1571. $failed_ids[] = $id;
  1572. error_log('STUDIOU WC UPVP: Variation ' . $id . ' not found or not a variation');
  1573. continue;
  1574. }
  1575. $variation->set_regular_price($formatted);
  1576. $variation->save();
  1577. $updated++;
  1578. $parent_id = $variation->get_parent_id();
  1579. if ($parent_id) {
  1580. $parent_ids[$parent_id] = true;
  1581. }
  1582. } catch (Exception $e) {
  1583. $failed++;
  1584. $failed_ids[] = $id;
  1585. error_log('STUDIOU WC UPVP: Exception updating variation ' . $id . ' - ' . $e->getMessage());
  1586. }
  1587. }
  1588. // Re-sync parent variable products so price-range cache reflects the new prices.
  1589. if (!empty($parent_ids) && class_exists('WC_Product_Variable')) {
  1590. foreach (array_keys($parent_ids) as $parent_id) {
  1591. try {
  1592. WC_Product_Variable::sync($parent_id);
  1593. if (function_exists('wc_delete_product_transients')) {
  1594. wc_delete_product_transients($parent_id);
  1595. }
  1596. } catch (Exception $e) {
  1597. error_log('STUDIOU WC UPVP: Failed to sync parent ' . $parent_id . ' - ' . $e->getMessage());
  1598. }
  1599. }
  1600. }
  1601. $message = sprintf(
  1602. __('Successfully updated %d variations.', 'studiou-wc-product-cat-manage'),
  1603. $updated
  1604. );
  1605. if ($failed > 0) {
  1606. $message .= ' ' . sprintf(
  1607. __('Failed to update %d variations.', 'studiou-wc-product-cat-manage'),
  1608. $failed
  1609. );
  1610. }
  1611. return array(
  1612. 'updated' => $updated,
  1613. 'failed' => $failed,
  1614. 'failed_ids' => $failed_ids,
  1615. 'message' => $message,
  1616. );
  1617. }
  1618. /**
  1619. * Common AJAX preflight: nonce + capability + output buffer setup.
  1620. * Returns false on failure (after sending JSON error), true on success.
  1621. */
  1622. private function upvp_preflight() {
  1623. while (ob_get_level()) {
  1624. ob_end_clean();
  1625. }
  1626. ob_start();
  1627. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1628. ob_clean();
  1629. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1630. return false;
  1631. }
  1632. if (!current_user_can('manage_woocommerce')) {
  1633. ob_clean();
  1634. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1635. return false;
  1636. }
  1637. return true;
  1638. }
  1639. /**
  1640. * AJAX: list variation attribute heads.
  1641. */
  1642. public function handle_upvp_get_attributes_ajax() {
  1643. if (!$this->upvp_preflight()) return;
  1644. $original_error_reporting = error_reporting();
  1645. error_reporting(0);
  1646. try {
  1647. $heads = $this->get_variation_attribute_heads();
  1648. ob_clean();
  1649. wp_send_json_success(array('attributes' => $heads));
  1650. } catch (Exception $e) {
  1651. error_log('STUDIOU WC UPVP: get_attributes failed - ' . $e->getMessage());
  1652. ob_clean();
  1653. wp_send_json_error(array('message' => $e->getMessage()));
  1654. } finally {
  1655. error_reporting($original_error_reporting);
  1656. ob_end_clean();
  1657. }
  1658. }
  1659. /**
  1660. * AJAX: list values for the chosen attribute (scoped to selected categories).
  1661. */
  1662. public function handle_upvp_get_attribute_values_ajax() {
  1663. if (!$this->upvp_preflight()) return;
  1664. $original_error_reporting = error_reporting();
  1665. error_reporting(0);
  1666. try {
  1667. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1668. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1669. if ($attribute_key === '') {
  1670. ob_clean();
  1671. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1672. return;
  1673. }
  1674. $values = $this->get_variation_attribute_values($attribute_key, $category_ids);
  1675. ob_clean();
  1676. wp_send_json_success(array('values' => $values));
  1677. } catch (Exception $e) {
  1678. error_log('STUDIOU WC UPVP: get_attribute_values failed - ' . $e->getMessage());
  1679. ob_clean();
  1680. wp_send_json_error(array('message' => $e->getMessage()));
  1681. } finally {
  1682. error_reporting($original_error_reporting);
  1683. ob_end_clean();
  1684. }
  1685. }
  1686. /**
  1687. * AJAX: count + sample of variations matching the current filter.
  1688. */
  1689. public function handle_upvp_count_ajax() {
  1690. if (!$this->upvp_preflight()) return;
  1691. $original_error_reporting = error_reporting();
  1692. error_reporting(0);
  1693. try {
  1694. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1695. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1696. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  1697. if (empty($category_ids)) {
  1698. ob_clean();
  1699. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  1700. return;
  1701. }
  1702. if ($attribute_key === '') {
  1703. ob_clean();
  1704. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1705. return;
  1706. }
  1707. if ($attribute_value === '') {
  1708. ob_clean();
  1709. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  1710. return;
  1711. }
  1712. $result = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  1713. ob_clean();
  1714. wp_send_json_success(array(
  1715. 'count' => $result['count'],
  1716. 'sample' => $result['sample'],
  1717. ));
  1718. } catch (Exception $e) {
  1719. error_log('STUDIOU WC UPVP: count failed - ' . $e->getMessage());
  1720. ob_clean();
  1721. wp_send_json_error(array('message' => $e->getMessage()));
  1722. } finally {
  1723. error_reporting($original_error_reporting);
  1724. ob_end_clean();
  1725. }
  1726. }
  1727. /**
  1728. * AJAX: apply new regular price to all matching variations.
  1729. */
  1730. public function handle_upvp_apply_ajax() {
  1731. if (!$this->upvp_preflight()) return;
  1732. $original_error_reporting = error_reporting();
  1733. error_reporting(0);
  1734. try {
  1735. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1736. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1737. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  1738. $new_price = isset($_POST['new_price']) ? sanitize_text_field(wp_unslash($_POST['new_price'])) : '';
  1739. if (empty($category_ids)) {
  1740. ob_clean();
  1741. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  1742. return;
  1743. }
  1744. if ($attribute_key === '' || $attribute_value === '') {
  1745. ob_clean();
  1746. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  1747. return;
  1748. }
  1749. if ($new_price === '' || !is_numeric($new_price) || (float) $new_price < 0) {
  1750. ob_clean();
  1751. wp_send_json_error(array('message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage')));
  1752. return;
  1753. }
  1754. $matching = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  1755. if ($matching['count'] === 0) {
  1756. ob_clean();
  1757. wp_send_json_error(array('message' => __('No variations match the current filter.', 'studiou-wc-product-cat-manage')));
  1758. return;
  1759. }
  1760. $result = $this->apply_variant_price($matching['ids'], $new_price);
  1761. ob_clean();
  1762. wp_send_json_success(array(
  1763. 'updated' => $result['updated'],
  1764. 'failed' => $result['failed'],
  1765. 'failed_ids' => $result['failed_ids'],
  1766. 'message' => $result['message'],
  1767. ));
  1768. } catch (Exception $e) {
  1769. error_log('STUDIOU WC UPVP: apply failed - ' . $e->getMessage());
  1770. ob_clean();
  1771. wp_send_json_error(array('message' => $e->getMessage()));
  1772. } finally {
  1773. error_reporting($original_error_reporting);
  1774. ob_end_clean();
  1775. }
  1776. }
  1777. }