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

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