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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 a test AJAX handler to verify AJAX is working
  33. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  34. // Debug: Log that the handler is being registered
  35. if (defined('WP_DEBUG') && WP_DEBUG) {
  36. error_log('STUDIOU WC: AJAX handlers registered - move_products and batch_description');
  37. }
  38. }
  39. /**
  40. * Handle AJAX batch description request
  41. */
  42. public function handle_batch_description_ajax() {
  43. // Clean all output buffers and prevent any output
  44. while (ob_get_level()) {
  45. ob_end_clean();
  46. }
  47. // Start a new output buffer to catch any unwanted output
  48. ob_start();
  49. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  50. $original_error_reporting = error_reporting();
  51. error_reporting(0);
  52. // Enable error logging only
  53. if (defined('WP_DEBUG') && WP_DEBUG) {
  54. error_log('STUDIOU WC: Batch description AJAX handler called');
  55. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  56. }
  57. try {
  58. // Check nonce
  59. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  60. wp_send_json_error(array(
  61. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  62. ));
  63. }
  64. // Check permissions
  65. if (!current_user_can('manage_woocommerce')) {
  66. wp_send_json_error(array(
  67. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  68. ));
  69. }
  70. // Validate input
  71. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  72. wp_send_json_error(array(
  73. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  74. ));
  75. }
  76. $selected_categories = array_map('intval', $_POST['selected_categories']);
  77. $description = sanitize_textarea_field($_POST['description']);
  78. // Debug logging
  79. if (defined('WP_DEBUG') && WP_DEBUG) {
  80. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  81. error_log('STUDIOU WC: Description: ' . $description);
  82. }
  83. // Validate categories
  84. if (empty($selected_categories)) {
  85. wp_send_json_error(array(
  86. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  87. ));
  88. }
  89. // Execute batch description operation
  90. $result = $this->update_categories_description($selected_categories, $description);
  91. // Debug logging
  92. if (defined('WP_DEBUG') && WP_DEBUG) {
  93. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  94. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  95. }
  96. // Clean any output that might have been generated
  97. ob_clean();
  98. // Return success response
  99. wp_send_json_success(array(
  100. 'message' => $result['message'],
  101. 'updated_count' => $result['updated_count'],
  102. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  103. ));
  104. } catch (Exception $e) {
  105. // Debug logging
  106. if (defined('WP_DEBUG') && WP_DEBUG) {
  107. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  108. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  109. }
  110. // Clean any output that might have been generated
  111. ob_clean();
  112. wp_send_json_error(array(
  113. 'message' => sprintf(
  114. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  115. $e->getMessage()
  116. )
  117. ));
  118. } finally {
  119. // Restore original error reporting
  120. error_reporting($original_error_reporting);
  121. // End the output buffer
  122. ob_end_clean();
  123. }
  124. }
  125. /**
  126. * Handle AJAX move products request
  127. */
  128. public function handle_move_products_ajax() {
  129. // Clean all output buffers and prevent any output
  130. while (ob_get_level()) {
  131. ob_end_clean();
  132. }
  133. // Start a new output buffer to catch any unwanted output
  134. ob_start();
  135. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  136. $original_error_reporting = error_reporting();
  137. error_reporting(0);
  138. // Enable error logging only
  139. if (defined('WP_DEBUG') && WP_DEBUG) {
  140. error_log('STUDIOU WC: AJAX handler called');
  141. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  142. }
  143. try {
  144. // Check nonce
  145. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  146. wp_send_json_error(array(
  147. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  148. ));
  149. }
  150. // Check permissions
  151. if (!current_user_can('manage_woocommerce')) {
  152. wp_send_json_error(array(
  153. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  154. ));
  155. }
  156. // Validate input
  157. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  158. wp_send_json_error(array(
  159. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  160. ));
  161. }
  162. $source_category_id = intval($_POST['source_category']);
  163. $target_category_id = intval($_POST['target_category']);
  164. // Debug logging
  165. if (defined('WP_DEBUG') && WP_DEBUG) {
  166. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  167. }
  168. // Validate categories
  169. if ($source_category_id === $target_category_id) {
  170. wp_send_json_error(array(
  171. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  172. ));
  173. }
  174. if ($source_category_id <= 0 || $target_category_id <= 0) {
  175. wp_send_json_error(array(
  176. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  177. ));
  178. }
  179. // Execute move operation
  180. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  181. // Debug logging
  182. if (defined('WP_DEBUG') && WP_DEBUG) {
  183. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  184. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  185. }
  186. // Clean any output that might have been generated
  187. ob_clean();
  188. // Return success response
  189. wp_send_json_success(array(
  190. 'message' => $result['message'],
  191. 'moved_count' => $result['moved_count'],
  192. 'source_count' => $result['source_count'],
  193. 'target_count' => $result['target_count'],
  194. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  195. ));
  196. } catch (Exception $e) {
  197. // Debug logging
  198. if (defined('WP_DEBUG') && WP_DEBUG) {
  199. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  200. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  201. }
  202. // Clean any output that might have been generated
  203. ob_clean();
  204. wp_send_json_error(array(
  205. 'message' => sprintf(
  206. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  207. $e->getMessage()
  208. )
  209. ));
  210. } finally {
  211. // Restore original error reporting
  212. error_reporting($original_error_reporting);
  213. // End the output buffer
  214. ob_end_clean();
  215. }
  216. }
  217. /**
  218. * Move all products from source category to target category
  219. *
  220. * @param int $source_category_id Source category ID
  221. * @param int $target_category_id Target category ID
  222. * @return array Result with counts and message
  223. * @throws Exception On error
  224. */
  225. public function move_products_between_categories($source_category_id, $target_category_id) {
  226. // Get source and target category terms
  227. $source_category = get_term($source_category_id, 'product_cat');
  228. $target_category = get_term($target_category_id, 'product_cat');
  229. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  230. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  231. }
  232. // Get initial count of products in source category using direct DB query
  233. $initial_source_count = $this->get_category_product_count($source_category_id);
  234. // Check if source category has any products
  235. if ($initial_source_count === 0) {
  236. $message = sprintf(
  237. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  238. $source_category->name
  239. );
  240. return array(
  241. 'moved_count' => 0,
  242. 'source_count' => 0,
  243. 'target_count' => $this->get_category_product_count($target_category_id),
  244. 'message' => $message
  245. );
  246. }
  247. // Get all products in source category using direct DB query
  248. $products = $this->get_products_in_category($source_category_id);
  249. $moved_count = 0;
  250. $failed_count = 0;
  251. if (defined('WP_DEBUG') && WP_DEBUG) {
  252. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  253. }
  254. // Move each product
  255. foreach ($products as $product_id) {
  256. // Get current categories for the product
  257. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  258. if (is_wp_error($current_categories)) {
  259. $failed_count++;
  260. if (defined('WP_DEBUG') && WP_DEBUG) {
  261. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  262. }
  263. continue;
  264. }
  265. // Remove source category and add target category
  266. $new_categories = array_diff($current_categories, array($source_category_id));
  267. $new_categories[] = $target_category_id;
  268. // Update product categories
  269. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  270. if (!is_wp_error($result)) {
  271. $moved_count++;
  272. if (defined('WP_DEBUG') && WP_DEBUG) {
  273. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  274. }
  275. } else {
  276. $failed_count++;
  277. if (defined('WP_DEBUG') && WP_DEBUG) {
  278. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  279. }
  280. }
  281. }
  282. // Get updated counts using direct DB query
  283. $source_count = $this->get_category_product_count($source_category_id);
  284. $target_count = $this->get_category_product_count($target_category_id);
  285. // Generate detailed result message
  286. if ($moved_count === 0 && count($products) > 0) {
  287. $message = sprintf(
  288. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  289. $source_category->name,
  290. $target_category->name,
  291. count($products)
  292. );
  293. } else {
  294. $message = sprintf(
  295. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  296. $moved_count,
  297. $source_category->name,
  298. $target_category->name,
  299. $source_count,
  300. $target_count
  301. );
  302. if ($failed_count > 0) {
  303. $message .= ' ' . sprintf(
  304. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  305. $failed_count
  306. );
  307. }
  308. }
  309. return array(
  310. 'moved_count' => $moved_count,
  311. 'source_count' => $source_count,
  312. 'target_count' => $target_count,
  313. 'failed_count' => $failed_count,
  314. 'message' => $message
  315. );
  316. }
  317. /**
  318. * Get product count for a category
  319. *
  320. * @param int $category_id Category ID
  321. * @return int Product count
  322. */
  323. private function get_category_product_count($category_id) {
  324. global $wpdb;
  325. // Use direct database query for more accurate counting
  326. $sql = "
  327. SELECT COUNT(DISTINCT p.ID)
  328. FROM {$wpdb->posts} p
  329. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  330. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  331. WHERE tt.term_id = %d
  332. AND tt.taxonomy = 'product_cat'
  333. AND p.post_type = 'product'
  334. AND p.post_status IN ('publish', 'private', 'draft')
  335. ";
  336. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  337. if (defined('WP_DEBUG') && WP_DEBUG) {
  338. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  339. }
  340. return intval($count);
  341. }
  342. /**
  343. * Get all products in a category
  344. *
  345. * @param int $category_id Category ID
  346. * @return array Array of product IDs
  347. */
  348. private function get_products_in_category($category_id) {
  349. global $wpdb;
  350. // Use direct database query to get products
  351. $sql = "
  352. SELECT DISTINCT p.ID
  353. FROM {$wpdb->posts} p
  354. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  355. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  356. WHERE tt.term_id = %d
  357. AND tt.taxonomy = 'product_cat'
  358. AND p.post_type = 'product'
  359. AND p.post_status IN ('publish', 'private', 'draft')
  360. ";
  361. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  362. if (defined('WP_DEBUG') && WP_DEBUG) {
  363. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  364. if (!empty($products)) {
  365. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  366. }
  367. }
  368. return $products ? array_map('intval', $products) : array();
  369. }
  370. /**
  371. * Update descriptions for multiple categories
  372. *
  373. * @param array $category_ids Array of category IDs
  374. * @param string $description New description for categories
  375. * @return array Result with counts and message
  376. * @throws Exception On error
  377. */
  378. public function update_categories_description($category_ids, $description) {
  379. $updated_count = 0;
  380. $failed_count = 0;
  381. $category_names = array();
  382. // Debug logging
  383. if (defined('WP_DEBUG') && WP_DEBUG) {
  384. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  385. }
  386. // Update each category
  387. foreach ($category_ids as $category_id) {
  388. // Get category term
  389. $category = get_term($category_id, 'product_cat');
  390. if (is_wp_error($category) || !$category) {
  391. $failed_count++;
  392. if (defined('WP_DEBUG') && WP_DEBUG) {
  393. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  394. }
  395. continue;
  396. }
  397. // Update category description
  398. $result = wp_update_term($category_id, 'product_cat', array(
  399. 'description' => $description
  400. ));
  401. if (!is_wp_error($result)) {
  402. $updated_count++;
  403. $category_names[] = $category->name;
  404. if (defined('WP_DEBUG') && WP_DEBUG) {
  405. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  406. }
  407. } else {
  408. $failed_count++;
  409. if (defined('WP_DEBUG') && WP_DEBUG) {
  410. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  411. }
  412. }
  413. }
  414. // Generate result message
  415. if ($updated_count === 0) {
  416. $message = sprintf(
  417. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  418. $failed_count
  419. );
  420. } else {
  421. $message = sprintf(
  422. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  423. $updated_count,
  424. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  425. );
  426. if ($failed_count > 0) {
  427. $message .= ' ' . sprintf(
  428. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  429. $failed_count
  430. );
  431. }
  432. }
  433. return array(
  434. 'updated_count' => $updated_count,
  435. 'failed_count' => $failed_count,
  436. 'message' => $message
  437. );
  438. }
  439. /**
  440. * Get all categories with product counts for select lists
  441. *
  442. * @return array Array of categories with ID, name, and product count
  443. */
  444. public function get_categories_with_counts() {
  445. $args = array(
  446. 'taxonomy' => 'product_cat',
  447. 'orderby' => 'name',
  448. 'hide_empty' => false,
  449. );
  450. $categories = get_terms($args);
  451. $categories_with_counts = array();
  452. if (!is_wp_error($categories)) {
  453. foreach ($categories as $category) {
  454. $product_count = $this->get_category_product_count($category->term_id);
  455. $categories_with_counts[] = array(
  456. 'id' => $category->term_id,
  457. 'name' => $category->name,
  458. 'count' => $product_count,
  459. 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
  460. );
  461. }
  462. }
  463. return $categories_with_counts;
  464. }
  465. }