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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 a test AJAX handler to verify AJAX is working
  37. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  38. // Debug: Log that the handler is being registered
  39. if (defined('WP_DEBUG') && WP_DEBUG) {
  40. error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
  41. }
  42. }
  43. /**
  44. * Handle AJAX batch description request
  45. */
  46. public function handle_batch_description_ajax() {
  47. // Clean all output buffers and prevent any output
  48. while (ob_get_level()) {
  49. ob_end_clean();
  50. }
  51. // Start a new output buffer to catch any unwanted output
  52. ob_start();
  53. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  54. $original_error_reporting = error_reporting();
  55. error_reporting(0);
  56. // Enable error logging only
  57. if (defined('WP_DEBUG') && WP_DEBUG) {
  58. error_log('STUDIOU WC: Batch description AJAX handler called');
  59. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  60. }
  61. try {
  62. // Check nonce
  63. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  64. wp_send_json_error(array(
  65. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  66. ));
  67. }
  68. // Check permissions
  69. if (!current_user_can('manage_woocommerce')) {
  70. wp_send_json_error(array(
  71. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  72. ));
  73. }
  74. // Validate input
  75. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  76. wp_send_json_error(array(
  77. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  78. ));
  79. }
  80. $selected_categories = array_map('intval', $_POST['selected_categories']);
  81. $description = sanitize_textarea_field($_POST['description']);
  82. // Debug logging
  83. if (defined('WP_DEBUG') && WP_DEBUG) {
  84. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  85. error_log('STUDIOU WC: Description: ' . $description);
  86. }
  87. // Validate categories
  88. if (empty($selected_categories)) {
  89. wp_send_json_error(array(
  90. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  91. ));
  92. }
  93. // Execute batch description operation
  94. $result = $this->update_categories_description($selected_categories, $description);
  95. // Debug logging
  96. if (defined('WP_DEBUG') && WP_DEBUG) {
  97. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  98. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  99. }
  100. // Clean any output that might have been generated
  101. ob_clean();
  102. // Return success response
  103. wp_send_json_success(array(
  104. 'message' => $result['message'],
  105. 'updated_count' => $result['updated_count'],
  106. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  107. ));
  108. } catch (Exception $e) {
  109. // Debug logging
  110. if (defined('WP_DEBUG') && WP_DEBUG) {
  111. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  112. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  113. }
  114. // Clean any output that might have been generated
  115. ob_clean();
  116. wp_send_json_error(array(
  117. 'message' => sprintf(
  118. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  119. $e->getMessage()
  120. )
  121. ));
  122. } finally {
  123. // Restore original error reporting
  124. error_reporting($original_error_reporting);
  125. // End the output buffer
  126. ob_end_clean();
  127. }
  128. }
  129. /**
  130. * Handle AJAX move products request
  131. */
  132. public function handle_move_products_ajax() {
  133. // Clean all output buffers and prevent any output
  134. while (ob_get_level()) {
  135. ob_end_clean();
  136. }
  137. // Start a new output buffer to catch any unwanted output
  138. ob_start();
  139. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  140. $original_error_reporting = error_reporting();
  141. error_reporting(0);
  142. // Enable error logging only
  143. if (defined('WP_DEBUG') && WP_DEBUG) {
  144. error_log('STUDIOU WC: AJAX handler called');
  145. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  146. }
  147. try {
  148. // Check nonce
  149. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  150. wp_send_json_error(array(
  151. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  152. ));
  153. }
  154. // Check permissions
  155. if (!current_user_can('manage_woocommerce')) {
  156. wp_send_json_error(array(
  157. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  158. ));
  159. }
  160. // Validate input
  161. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  162. wp_send_json_error(array(
  163. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  164. ));
  165. }
  166. $source_category_id = intval($_POST['source_category']);
  167. $target_category_id = intval($_POST['target_category']);
  168. // Debug logging
  169. if (defined('WP_DEBUG') && WP_DEBUG) {
  170. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  171. }
  172. // Validate categories
  173. if ($source_category_id === $target_category_id) {
  174. wp_send_json_error(array(
  175. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  176. ));
  177. }
  178. if ($source_category_id <= 0 || $target_category_id <= 0) {
  179. wp_send_json_error(array(
  180. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  181. ));
  182. }
  183. // Execute move operation
  184. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  185. // Debug logging
  186. if (defined('WP_DEBUG') && WP_DEBUG) {
  187. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  188. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  189. }
  190. // Clean any output that might have been generated
  191. ob_clean();
  192. // Return success response
  193. wp_send_json_success(array(
  194. 'message' => $result['message'],
  195. 'moved_count' => $result['moved_count'],
  196. 'source_count' => $result['source_count'],
  197. 'target_count' => $result['target_count'],
  198. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  199. ));
  200. } catch (Exception $e) {
  201. // Debug logging
  202. if (defined('WP_DEBUG') && WP_DEBUG) {
  203. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  204. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  205. }
  206. // Clean any output that might have been generated
  207. ob_clean();
  208. wp_send_json_error(array(
  209. 'message' => sprintf(
  210. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  211. $e->getMessage()
  212. )
  213. ));
  214. } finally {
  215. // Restore original error reporting
  216. error_reporting($original_error_reporting);
  217. // End the output buffer
  218. ob_end_clean();
  219. }
  220. }
  221. /**
  222. * Move all products from source category to target category
  223. *
  224. * @param int $source_category_id Source category ID
  225. * @param int $target_category_id Target category ID
  226. * @return array Result with counts and message
  227. * @throws Exception On error
  228. */
  229. public function move_products_between_categories($source_category_id, $target_category_id) {
  230. // Get source and target category terms
  231. $source_category = get_term($source_category_id, 'product_cat');
  232. $target_category = get_term($target_category_id, 'product_cat');
  233. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  234. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  235. }
  236. // Get initial count of products in source category using direct DB query
  237. $initial_source_count = $this->get_category_product_count($source_category_id);
  238. // Check if source category has any products
  239. if ($initial_source_count === 0) {
  240. $message = sprintf(
  241. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  242. $source_category->name
  243. );
  244. return array(
  245. 'moved_count' => 0,
  246. 'source_count' => 0,
  247. 'target_count' => $this->get_category_product_count($target_category_id),
  248. 'message' => $message
  249. );
  250. }
  251. // Get all products in source category using direct DB query
  252. $products = $this->get_products_in_category($source_category_id);
  253. $moved_count = 0;
  254. $failed_count = 0;
  255. if (defined('WP_DEBUG') && WP_DEBUG) {
  256. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  257. }
  258. // Move each product
  259. foreach ($products as $product_id) {
  260. // Get current categories for the product
  261. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  262. if (is_wp_error($current_categories)) {
  263. $failed_count++;
  264. if (defined('WP_DEBUG') && WP_DEBUG) {
  265. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  266. }
  267. continue;
  268. }
  269. // Remove source category and add target category
  270. $new_categories = array_diff($current_categories, array($source_category_id));
  271. $new_categories[] = $target_category_id;
  272. // Update product categories
  273. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  274. if (!is_wp_error($result)) {
  275. $moved_count++;
  276. if (defined('WP_DEBUG') && WP_DEBUG) {
  277. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  278. }
  279. } else {
  280. $failed_count++;
  281. if (defined('WP_DEBUG') && WP_DEBUG) {
  282. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  283. }
  284. }
  285. }
  286. // Get updated counts using direct DB query
  287. $source_count = $this->get_category_product_count($source_category_id);
  288. $target_count = $this->get_category_product_count($target_category_id);
  289. // Generate detailed result message
  290. if ($moved_count === 0 && count($products) > 0) {
  291. $message = sprintf(
  292. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  293. $source_category->name,
  294. $target_category->name,
  295. count($products)
  296. );
  297. } else {
  298. $message = sprintf(
  299. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  300. $moved_count,
  301. $source_category->name,
  302. $target_category->name,
  303. $source_count,
  304. $target_count
  305. );
  306. if ($failed_count > 0) {
  307. $message .= ' ' . sprintf(
  308. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  309. $failed_count
  310. );
  311. }
  312. }
  313. return array(
  314. 'moved_count' => $moved_count,
  315. 'source_count' => $source_count,
  316. 'target_count' => $target_count,
  317. 'failed_count' => $failed_count,
  318. 'message' => $message
  319. );
  320. }
  321. /**
  322. * Get product count for a category
  323. *
  324. * @param int $category_id Category ID
  325. * @return int Product count
  326. */
  327. private function get_category_product_count($category_id) {
  328. global $wpdb;
  329. // Use direct database query for more accurate counting
  330. $sql = "
  331. SELECT COUNT(DISTINCT p.ID)
  332. FROM {$wpdb->posts} p
  333. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  334. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  335. WHERE tt.term_id = %d
  336. AND tt.taxonomy = 'product_cat'
  337. AND p.post_type = 'product'
  338. AND p.post_status IN ('publish', 'private', 'draft')
  339. ";
  340. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  341. if (defined('WP_DEBUG') && WP_DEBUG) {
  342. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  343. }
  344. return intval($count);
  345. }
  346. /**
  347. * Get all products in a category
  348. *
  349. * @param int $category_id Category ID
  350. * @return array Array of product IDs
  351. */
  352. private function get_products_in_category($category_id) {
  353. global $wpdb;
  354. // Use direct database query to get products
  355. $sql = "
  356. SELECT DISTINCT p.ID
  357. FROM {$wpdb->posts} p
  358. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  359. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  360. WHERE tt.term_id = %d
  361. AND tt.taxonomy = 'product_cat'
  362. AND p.post_type = 'product'
  363. AND p.post_status IN ('publish', 'private', 'draft')
  364. ";
  365. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  366. if (defined('WP_DEBUG') && WP_DEBUG) {
  367. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  368. if (!empty($products)) {
  369. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  370. }
  371. }
  372. return $products ? array_map('intval', $products) : array();
  373. }
  374. /**
  375. * Update descriptions for multiple categories
  376. *
  377. * @param array $category_ids Array of category IDs
  378. * @param string $description New description for categories
  379. * @return array Result with counts and message
  380. * @throws Exception On error
  381. */
  382. public function update_categories_description($category_ids, $description) {
  383. $updated_count = 0;
  384. $failed_count = 0;
  385. $category_names = array();
  386. // Debug logging
  387. if (defined('WP_DEBUG') && WP_DEBUG) {
  388. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  389. }
  390. // Update each category
  391. foreach ($category_ids as $category_id) {
  392. // Get category term
  393. $category = get_term($category_id, 'product_cat');
  394. if (is_wp_error($category) || !$category) {
  395. $failed_count++;
  396. if (defined('WP_DEBUG') && WP_DEBUG) {
  397. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  398. }
  399. continue;
  400. }
  401. // Update category description
  402. $result = wp_update_term($category_id, 'product_cat', array(
  403. 'description' => $description
  404. ));
  405. if (!is_wp_error($result)) {
  406. $updated_count++;
  407. $category_names[] = $category->name;
  408. if (defined('WP_DEBUG') && WP_DEBUG) {
  409. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  410. }
  411. } else {
  412. $failed_count++;
  413. if (defined('WP_DEBUG') && WP_DEBUG) {
  414. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  415. }
  416. }
  417. }
  418. // Generate result message
  419. if ($updated_count === 0) {
  420. $message = sprintf(
  421. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  422. $failed_count
  423. );
  424. } else {
  425. $message = sprintf(
  426. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  427. $updated_count,
  428. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  429. );
  430. if ($failed_count > 0) {
  431. $message .= ' ' . sprintf(
  432. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  433. $failed_count
  434. );
  435. }
  436. }
  437. return array(
  438. 'updated_count' => $updated_count,
  439. 'failed_count' => $failed_count,
  440. 'message' => $message
  441. );
  442. }
  443. /**
  444. * Get all categories with product counts for select lists
  445. *
  446. * @return array Array of categories with ID, name, and product count
  447. */
  448. public function get_categories_with_counts() {
  449. $args = array(
  450. 'taxonomy' => 'product_cat',
  451. 'orderby' => 'name',
  452. 'hide_empty' => false,
  453. );
  454. $categories = get_terms($args);
  455. $categories_with_counts = array();
  456. if (!is_wp_error($categories)) {
  457. foreach ($categories as $category) {
  458. $product_count = $this->get_category_product_count($category->term_id);
  459. $categories_with_counts[] = array(
  460. 'id' => $category->term_id,
  461. 'name' => $category->name,
  462. 'count' => $product_count,
  463. 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
  464. );
  465. }
  466. }
  467. return $categories_with_counts;
  468. }
  469. /**
  470. * Handle AJAX delete products request (initial request to get product IDs)
  471. */
  472. public function handle_delete_products_ajax() {
  473. // Clean all output buffers and prevent any output
  474. while (ob_get_level()) {
  475. ob_end_clean();
  476. }
  477. // Start a new output buffer to catch any unwanted output
  478. ob_start();
  479. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  480. $original_error_reporting = error_reporting();
  481. error_reporting(0);
  482. // Enable error logging only
  483. if (defined('WP_DEBUG') && WP_DEBUG) {
  484. error_log('STUDIOU WC: Delete products AJAX handler called');
  485. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  486. }
  487. try {
  488. // Check nonce
  489. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  490. wp_send_json_error(array(
  491. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  492. ));
  493. }
  494. // Check permissions
  495. if (!current_user_can('manage_woocommerce')) {
  496. wp_send_json_error(array(
  497. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  498. ));
  499. }
  500. // Validate input
  501. if (!isset($_POST['delete_categories'])) {
  502. wp_send_json_error(array(
  503. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  504. ));
  505. }
  506. $category_ids = array_map('intval', $_POST['delete_categories']);
  507. // Debug logging
  508. if (defined('WP_DEBUG') && WP_DEBUG) {
  509. error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
  510. }
  511. // Validate categories
  512. if (empty($category_ids)) {
  513. wp_send_json_error(array(
  514. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  515. ));
  516. }
  517. // Get all products from selected categories
  518. $product_ids = $this->get_products_from_categories($category_ids);
  519. // Debug logging
  520. if (defined('WP_DEBUG') && WP_DEBUG) {
  521. error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
  522. }
  523. // Clean any output that might have been generated
  524. ob_clean();
  525. // Return product IDs for batch processing
  526. wp_send_json_success(array(
  527. 'product_ids' => $product_ids,
  528. 'total_count' => count($product_ids),
  529. 'message' => sprintf(
  530. __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
  531. count($product_ids)
  532. )
  533. ));
  534. } catch (Exception $e) {
  535. // Debug logging
  536. if (defined('WP_DEBUG') && WP_DEBUG) {
  537. error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
  538. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  539. }
  540. // Clean any output that might have been generated
  541. ob_clean();
  542. wp_send_json_error(array(
  543. 'message' => sprintf(
  544. __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
  545. $e->getMessage()
  546. )
  547. ));
  548. } finally {
  549. // Restore original error reporting
  550. error_reporting($original_error_reporting);
  551. // End the output buffer
  552. ob_end_clean();
  553. }
  554. }
  555. /**
  556. * Handle AJAX delete products batch request (processes products in batches)
  557. */
  558. public function handle_delete_products_batch_ajax() {
  559. // Clean all output buffers and prevent any output
  560. while (ob_get_level()) {
  561. ob_end_clean();
  562. }
  563. // Start a new output buffer to catch any unwanted output
  564. ob_start();
  565. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  566. $original_error_reporting = error_reporting();
  567. error_reporting(0);
  568. // Enable error logging only
  569. if (defined('WP_DEBUG') && WP_DEBUG) {
  570. error_log('STUDIOU WC: Delete products batch AJAX handler called');
  571. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  572. }
  573. try {
  574. // Check nonce
  575. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  576. wp_send_json_error(array(
  577. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  578. ));
  579. }
  580. // Check permissions
  581. if (!current_user_can('manage_woocommerce')) {
  582. wp_send_json_error(array(
  583. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  584. ));
  585. }
  586. // Validate input
  587. if (!isset($_POST['product_ids'])) {
  588. wp_send_json_error(array(
  589. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  590. ));
  591. }
  592. $product_ids = array_map('intval', $_POST['product_ids']);
  593. // Debug logging
  594. if (defined('WP_DEBUG') && WP_DEBUG) {
  595. error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
  596. }
  597. // Delete products in this batch
  598. $result = $this->delete_products_batch($product_ids);
  599. // Debug logging
  600. if (defined('WP_DEBUG') && WP_DEBUG) {
  601. error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  602. }
  603. // Clean any output that might have been generated
  604. ob_clean();
  605. // Return success response
  606. wp_send_json_success(array(
  607. 'deleted_count' => $result['deleted_count'],
  608. 'failed_count' => $result['failed_count'],
  609. 'failed_products' => $result['failed_products']
  610. ));
  611. } catch (Exception $e) {
  612. // Debug logging
  613. if (defined('WP_DEBUG') && WP_DEBUG) {
  614. error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
  615. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  616. }
  617. // Clean any output that might have been generated
  618. ob_clean();
  619. wp_send_json_error(array(
  620. 'message' => sprintf(
  621. __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
  622. $e->getMessage()
  623. )
  624. ));
  625. } finally {
  626. // Restore original error reporting
  627. error_reporting($original_error_reporting);
  628. // End the output buffer
  629. ob_end_clean();
  630. }
  631. }
  632. /**
  633. * Get all products from multiple categories
  634. *
  635. * @param array $category_ids Array of category IDs
  636. * @return array Array of unique product IDs (including parent products with variants)
  637. */
  638. private function get_products_from_categories($category_ids) {
  639. global $wpdb;
  640. if (empty($category_ids)) {
  641. return array();
  642. }
  643. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  644. // Get all products from selected categories (both simple and parent products)
  645. $sql = "
  646. SELECT DISTINCT p.ID
  647. FROM {$wpdb->posts} p
  648. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  649. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  650. WHERE tt.term_id IN ($placeholders)
  651. AND tt.taxonomy = 'product_cat'
  652. AND p.post_type = 'product'
  653. AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
  654. ";
  655. $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
  656. if (defined('WP_DEBUG') && WP_DEBUG) {
  657. error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
  658. }
  659. return $products ? array_map('intval', $products) : array();
  660. }
  661. /**
  662. * Delete a batch of products and their variants
  663. *
  664. * @param array $product_ids Array of product IDs to delete
  665. * @return array Result with counts
  666. */
  667. private function delete_products_batch($product_ids) {
  668. $deleted_count = 0;
  669. $failed_count = 0;
  670. $failed_products = array();
  671. foreach ($product_ids as $product_id) {
  672. try {
  673. // Get the product object
  674. $product = wc_get_product($product_id);
  675. if (!$product) {
  676. $failed_count++;
  677. $failed_products[] = $product_id;
  678. if (defined('WP_DEBUG') && WP_DEBUG) {
  679. error_log('STUDIOU WC: Product ' . $product_id . ' not found');
  680. }
  681. continue;
  682. }
  683. // If it's a variable product, delete all variations first
  684. if ($product->is_type('variable')) {
  685. $variations = $product->get_children();
  686. if (defined('WP_DEBUG') && WP_DEBUG) {
  687. error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
  688. }
  689. foreach ($variations as $variation_id) {
  690. $variation = wc_get_product($variation_id);
  691. if ($variation) {
  692. $variation->delete(true); // true = force delete permanently
  693. }
  694. }
  695. }
  696. // Delete the product permanently
  697. $result = $product->delete(true); // true = force delete permanently
  698. if ($result) {
  699. $deleted_count++;
  700. if (defined('WP_DEBUG') && WP_DEBUG) {
  701. error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
  702. }
  703. } else {
  704. $failed_count++;
  705. $failed_products[] = $product_id;
  706. if (defined('WP_DEBUG') && WP_DEBUG) {
  707. error_log('STUDIOU WC: Failed to delete product ' . $product_id);
  708. }
  709. }
  710. } catch (Exception $e) {
  711. $failed_count++;
  712. $failed_products[] = $product_id;
  713. if (defined('WP_DEBUG') && WP_DEBUG) {
  714. error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
  715. }
  716. }
  717. }
  718. return array(
  719. 'deleted_count' => $deleted_count,
  720. 'failed_count' => $failed_count,
  721. 'failed_products' => $failed_products
  722. );
  723. }
  724. /**
  725. * Get all media categories with file counts for select lists
  726. *
  727. * @return array Array of media categories with ID, name, and file count
  728. */
  729. public function get_media_categories_with_counts() {
  730. $taxonomy = $this->get_media_category_taxonomy();
  731. if (!$taxonomy) {
  732. return array();
  733. }
  734. $args = array(
  735. 'taxonomy' => $taxonomy,
  736. 'orderby' => 'name',
  737. 'hide_empty' => false,
  738. );
  739. $categories = get_terms($args);
  740. $categories_with_counts = array();
  741. if (!is_wp_error($categories)) {
  742. foreach ($categories as $category) {
  743. $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
  744. $categories_with_counts[] = array(
  745. 'id' => $category->term_id,
  746. 'name' => $category->name,
  747. 'count' => $file_count,
  748. 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
  749. );
  750. }
  751. }
  752. return $categories_with_counts;
  753. }
  754. /**
  755. * Get the media category taxonomy name
  756. *
  757. * Checks for common media category taxonomies used by popular plugins
  758. *
  759. * @return string|false Taxonomy name or false if none found
  760. */
  761. private function get_media_category_taxonomy() {
  762. $possible_taxonomies = array(
  763. 'media_category',
  764. 'attachment_category',
  765. 'media-category',
  766. );
  767. foreach ($possible_taxonomies as $taxonomy) {
  768. if (taxonomy_exists($taxonomy)) {
  769. return $taxonomy;
  770. }
  771. }
  772. return false;
  773. }
  774. /**
  775. * Get file count for a media category
  776. *
  777. * @param int $category_id Category term ID
  778. * @param string $taxonomy Taxonomy name
  779. * @return int File count
  780. */
  781. private function get_media_category_file_count($category_id, $taxonomy) {
  782. global $wpdb;
  783. $sql = "
  784. SELECT COUNT(DISTINCT p.ID)
  785. FROM {$wpdb->posts} p
  786. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  787. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  788. WHERE tt.term_id = %d
  789. AND tt.taxonomy = %s
  790. AND p.post_type = 'attachment'
  791. ";
  792. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
  793. return intval($count);
  794. }
  795. /**
  796. * Get all media IDs from multiple media categories
  797. *
  798. * @param array $category_ids Array of category term IDs
  799. * @return array Array of unique attachment IDs
  800. */
  801. private function get_media_from_categories($category_ids) {
  802. global $wpdb;
  803. $taxonomy = $this->get_media_category_taxonomy();
  804. if (!$taxonomy || empty($category_ids)) {
  805. return array();
  806. }
  807. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  808. $sql = "
  809. SELECT DISTINCT p.ID
  810. FROM {$wpdb->posts} p
  811. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  812. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  813. WHERE tt.term_id IN ($placeholders)
  814. AND tt.taxonomy = %s
  815. AND p.post_type = 'attachment'
  816. ";
  817. $params = array_merge($category_ids, array($taxonomy));
  818. $media = $wpdb->get_col($wpdb->prepare($sql, $params));
  819. if (defined('WP_DEBUG') && WP_DEBUG) {
  820. error_log('STUDIOU WC: Found ' . count($media) . ' media files in media categories ' . implode(', ', $category_ids));
  821. }
  822. return $media ? array_map('intval', $media) : array();
  823. }
  824. /**
  825. * Delete a batch of media files permanently
  826. *
  827. * @param array $media_ids Array of attachment IDs to delete
  828. * @return array Result with counts
  829. */
  830. private function delete_media_batch($media_ids) {
  831. $deleted_count = 0;
  832. $failed_count = 0;
  833. $failed_media = array();
  834. foreach ($media_ids as $media_id) {
  835. try {
  836. $attachment = get_post($media_id);
  837. if (!$attachment || $attachment->post_type !== 'attachment') {
  838. $failed_count++;
  839. $failed_media[] = $media_id;
  840. if (defined('WP_DEBUG') && WP_DEBUG) {
  841. error_log('STUDIOU WC: Media file ' . $media_id . ' not found or not an attachment');
  842. }
  843. continue;
  844. }
  845. // Force delete attachment and its files from disk
  846. $result = wp_delete_attachment($media_id, true);
  847. if ($result) {
  848. $deleted_count++;
  849. if (defined('WP_DEBUG') && WP_DEBUG) {
  850. error_log('STUDIOU WC: Successfully deleted media file ' . $media_id);
  851. }
  852. } else {
  853. $failed_count++;
  854. $failed_media[] = $media_id;
  855. if (defined('WP_DEBUG') && WP_DEBUG) {
  856. error_log('STUDIOU WC: Failed to delete media file ' . $media_id);
  857. }
  858. }
  859. } catch (Exception $e) {
  860. $failed_count++;
  861. $failed_media[] = $media_id;
  862. if (defined('WP_DEBUG') && WP_DEBUG) {
  863. error_log('STUDIOU WC: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
  864. }
  865. }
  866. }
  867. return array(
  868. 'deleted_count' => $deleted_count,
  869. 'failed_count' => $failed_count,
  870. 'failed_media' => $failed_media
  871. );
  872. }
  873. /**
  874. * Handle AJAX clear media request (initial request to get media IDs)
  875. */
  876. public function handle_clear_media_ajax() {
  877. while (ob_get_level()) {
  878. ob_end_clean();
  879. }
  880. ob_start();
  881. $original_error_reporting = error_reporting();
  882. error_reporting(0);
  883. if (defined('WP_DEBUG') && WP_DEBUG) {
  884. error_log('STUDIOU WC: Clear media AJAX handler called');
  885. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  886. }
  887. try {
  888. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  889. wp_send_json_error(array(
  890. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  891. ));
  892. }
  893. if (!current_user_can('manage_woocommerce')) {
  894. wp_send_json_error(array(
  895. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  896. ));
  897. }
  898. if (!isset($_POST['media_categories'])) {
  899. wp_send_json_error(array(
  900. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  901. ));
  902. }
  903. $category_ids = array_map('intval', $_POST['media_categories']);
  904. if (empty($category_ids)) {
  905. wp_send_json_error(array(
  906. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  907. ));
  908. }
  909. $media_ids = $this->get_media_from_categories($category_ids);
  910. if (defined('WP_DEBUG') && WP_DEBUG) {
  911. error_log('STUDIOU WC: Found ' . count($media_ids) . ' media files to delete');
  912. }
  913. ob_clean();
  914. wp_send_json_success(array(
  915. 'media_ids' => $media_ids,
  916. 'total_count' => count($media_ids),
  917. 'message' => sprintf(
  918. __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
  919. count($media_ids)
  920. )
  921. ));
  922. } catch (Exception $e) {
  923. if (defined('WP_DEBUG') && WP_DEBUG) {
  924. error_log('STUDIOU WC: Clear media operation failed - ' . $e->getMessage());
  925. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  926. }
  927. ob_clean();
  928. wp_send_json_error(array(
  929. 'message' => sprintf(
  930. __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
  931. $e->getMessage()
  932. )
  933. ));
  934. } finally {
  935. error_reporting($original_error_reporting);
  936. ob_end_clean();
  937. }
  938. }
  939. /**
  940. * Handle AJAX clear media batch request (processes media in batches)
  941. */
  942. public function handle_clear_media_batch_ajax() {
  943. while (ob_get_level()) {
  944. ob_end_clean();
  945. }
  946. ob_start();
  947. $original_error_reporting = error_reporting();
  948. error_reporting(0);
  949. if (defined('WP_DEBUG') && WP_DEBUG) {
  950. error_log('STUDIOU WC: Clear media batch AJAX handler called');
  951. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  952. }
  953. try {
  954. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  955. wp_send_json_error(array(
  956. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  957. ));
  958. }
  959. if (!current_user_can('manage_woocommerce')) {
  960. wp_send_json_error(array(
  961. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  962. ));
  963. }
  964. if (!isset($_POST['media_ids'])) {
  965. wp_send_json_error(array(
  966. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  967. ));
  968. }
  969. $media_ids = array_map('intval', $_POST['media_ids']);
  970. if (defined('WP_DEBUG') && WP_DEBUG) {
  971. error_log('STUDIOU WC: Processing batch of ' . count($media_ids) . ' media files for deletion');
  972. }
  973. $result = $this->delete_media_batch($media_ids);
  974. if (defined('WP_DEBUG') && WP_DEBUG) {
  975. error_log('STUDIOU WC: Batch media deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  976. }
  977. ob_clean();
  978. wp_send_json_success(array(
  979. 'deleted_count' => $result['deleted_count'],
  980. 'failed_count' => $result['failed_count'],
  981. 'failed_media' => $result['failed_media']
  982. ));
  983. } catch (Exception $e) {
  984. if (defined('WP_DEBUG') && WP_DEBUG) {
  985. error_log('STUDIOU WC: Clear media batch operation failed - ' . $e->getMessage());
  986. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  987. }
  988. ob_clean();
  989. wp_send_json_error(array(
  990. 'message' => sprintf(
  991. __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
  992. $e->getMessage()
  993. )
  994. ));
  995. } finally {
  996. error_reporting($original_error_reporting);
  997. ob_end_clean();
  998. }
  999. }
  1000. }