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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 a test AJAX handler to verify AJAX is working
  32. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  33. // Debug: Log that the handler is being registered
  34. if (defined('WP_DEBUG') && WP_DEBUG) {
  35. error_log('STUDIOU WC: AJAX handler wp_ajax_studiou_wcpcm_move_products registered');
  36. }
  37. }
  38. /**
  39. * Test AJAX handler to verify AJAX is working
  40. */
  41. public function handle_test_ajax() {
  42. error_log('STUDIOU WC: Test AJAX handler called');
  43. wp_send_json_success(array('message' => 'AJAX is working'));
  44. }
  45. /**
  46. * Handle AJAX move products request
  47. */
  48. public function handle_move_products_ajax() {
  49. // Clean all output buffers and prevent any output
  50. while (ob_get_level()) {
  51. ob_end_clean();
  52. }
  53. // Start a new output buffer to catch any unwanted output
  54. ob_start();
  55. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  56. $original_error_reporting = error_reporting();
  57. error_reporting(0);
  58. // Enable error logging only
  59. if (defined('WP_DEBUG') && WP_DEBUG) {
  60. error_log('STUDIOU WC: AJAX handler called');
  61. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  62. }
  63. try {
  64. // Check nonce
  65. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  66. wp_send_json_error(array(
  67. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  68. ));
  69. }
  70. // Check permissions
  71. if (!current_user_can('manage_woocommerce')) {
  72. wp_send_json_error(array(
  73. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  74. ));
  75. }
  76. // Validate input
  77. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  78. wp_send_json_error(array(
  79. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  80. ));
  81. }
  82. $source_category_id = intval($_POST['source_category']);
  83. $target_category_id = intval($_POST['target_category']);
  84. // Debug logging
  85. if (defined('WP_DEBUG') && WP_DEBUG) {
  86. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  87. }
  88. // Validate categories
  89. if ($source_category_id === $target_category_id) {
  90. wp_send_json_error(array(
  91. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  92. ));
  93. }
  94. if ($source_category_id <= 0 || $target_category_id <= 0) {
  95. wp_send_json_error(array(
  96. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  97. ));
  98. }
  99. // Execute move operation
  100. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  101. // Debug logging
  102. if (defined('WP_DEBUG') && WP_DEBUG) {
  103. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  104. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  105. }
  106. // Clean any output that might have been generated
  107. ob_clean();
  108. // Return success response
  109. wp_send_json_success(array(
  110. 'message' => $result['message'],
  111. 'moved_count' => $result['moved_count'],
  112. 'source_count' => $result['source_count'],
  113. 'target_count' => $result['target_count'],
  114. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  115. ));
  116. } catch (Exception $e) {
  117. // Debug logging
  118. if (defined('WP_DEBUG') && WP_DEBUG) {
  119. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  120. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  121. }
  122. // Clean any output that might have been generated
  123. ob_clean();
  124. wp_send_json_error(array(
  125. 'message' => sprintf(
  126. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  127. $e->getMessage()
  128. )
  129. ));
  130. } finally {
  131. // Restore original error reporting
  132. error_reporting($original_error_reporting);
  133. // End the output buffer
  134. ob_end_clean();
  135. }
  136. }
  137. /**
  138. * Move all products from source category to target category
  139. *
  140. * @param int $source_category_id Source category ID
  141. * @param int $target_category_id Target category ID
  142. * @return array Result with counts and message
  143. * @throws Exception On error
  144. */
  145. public function move_products_between_categories($source_category_id, $target_category_id) {
  146. // Get source and target category terms
  147. $source_category = get_term($source_category_id, 'product_cat');
  148. $target_category = get_term($target_category_id, 'product_cat');
  149. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  150. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  151. }
  152. // Get initial count of products in source category using direct DB query
  153. $initial_source_count = $this->get_category_product_count($source_category_id);
  154. // Check if source category has any products
  155. if ($initial_source_count === 0) {
  156. $message = sprintf(
  157. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  158. $source_category->name
  159. );
  160. return array(
  161. 'moved_count' => 0,
  162. 'source_count' => 0,
  163. 'target_count' => $this->get_category_product_count($target_category_id),
  164. 'message' => $message
  165. );
  166. }
  167. // Get all products in source category using direct DB query
  168. $products = $this->get_products_in_category($source_category_id);
  169. $moved_count = 0;
  170. $failed_count = 0;
  171. if (defined('WP_DEBUG') && WP_DEBUG) {
  172. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  173. }
  174. // Move each product
  175. foreach ($products as $product_id) {
  176. // Get current categories for the product
  177. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  178. if (is_wp_error($current_categories)) {
  179. $failed_count++;
  180. if (defined('WP_DEBUG') && WP_DEBUG) {
  181. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  182. }
  183. continue;
  184. }
  185. // Remove source category and add target category
  186. $new_categories = array_diff($current_categories, array($source_category_id));
  187. $new_categories[] = $target_category_id;
  188. // Update product categories
  189. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  190. if (!is_wp_error($result)) {
  191. $moved_count++;
  192. if (defined('WP_DEBUG') && WP_DEBUG) {
  193. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  194. }
  195. } else {
  196. $failed_count++;
  197. if (defined('WP_DEBUG') && WP_DEBUG) {
  198. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  199. }
  200. }
  201. }
  202. // Get updated counts using direct DB query
  203. $source_count = $this->get_category_product_count($source_category_id);
  204. $target_count = $this->get_category_product_count($target_category_id);
  205. // Generate detailed result message
  206. if ($moved_count === 0 && count($products) > 0) {
  207. $message = sprintf(
  208. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  209. $source_category->name,
  210. $target_category->name,
  211. count($products)
  212. );
  213. } else {
  214. $message = sprintf(
  215. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  216. $moved_count,
  217. $source_category->name,
  218. $target_category->name,
  219. $source_count,
  220. $target_count
  221. );
  222. if ($failed_count > 0) {
  223. $message .= ' ' . sprintf(
  224. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  225. $failed_count
  226. );
  227. }
  228. }
  229. return array(
  230. 'moved_count' => $moved_count,
  231. 'source_count' => $source_count,
  232. 'target_count' => $target_count,
  233. 'failed_count' => $failed_count,
  234. 'message' => $message
  235. );
  236. }
  237. /**
  238. * Get product count for a category
  239. *
  240. * @param int $category_id Category ID
  241. * @return int Product count
  242. */
  243. private function get_category_product_count($category_id) {
  244. global $wpdb;
  245. // Use direct database query for more accurate counting
  246. $sql = "
  247. SELECT COUNT(DISTINCT p.ID)
  248. FROM {$wpdb->posts} p
  249. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  250. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  251. WHERE tt.term_id = %d
  252. AND tt.taxonomy = 'product_cat'
  253. AND p.post_type = 'product'
  254. AND p.post_status IN ('publish', 'private', 'draft')
  255. ";
  256. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  257. if (defined('WP_DEBUG') && WP_DEBUG) {
  258. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  259. }
  260. return intval($count);
  261. }
  262. /**
  263. * Get all products in a category
  264. *
  265. * @param int $category_id Category ID
  266. * @return array Array of product IDs
  267. */
  268. private function get_products_in_category($category_id) {
  269. global $wpdb;
  270. // Use direct database query to get products
  271. $sql = "
  272. SELECT DISTINCT p.ID
  273. FROM {$wpdb->posts} p
  274. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  275. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  276. WHERE tt.term_id = %d
  277. AND tt.taxonomy = 'product_cat'
  278. AND p.post_type = 'product'
  279. AND p.post_status IN ('publish', 'private', 'draft')
  280. ";
  281. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  282. if (defined('WP_DEBUG') && WP_DEBUG) {
  283. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  284. if (!empty($products)) {
  285. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  286. }
  287. }
  288. return $products ? array_map('intval', $products) : array();
  289. }
  290. /**
  291. * Get all categories with product counts for select lists
  292. *
  293. * @return array Array of categories with ID, name, and product count
  294. */
  295. public function get_categories_with_counts() {
  296. $args = array(
  297. 'taxonomy' => 'product_cat',
  298. 'orderby' => 'name',
  299. 'hide_empty' => false,
  300. );
  301. $categories = get_terms($args);
  302. $categories_with_counts = array();
  303. if (!is_wp_error($categories)) {
  304. foreach ($categories as $category) {
  305. $product_count = $this->get_category_product_count($category->term_id);
  306. $categories_with_counts[] = array(
  307. 'id' => $category->term_id,
  308. 'name' => $category->name,
  309. 'count' => $product_count,
  310. 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
  311. );
  312. }
  313. }
  314. return $categories_with_counts;
  315. }
  316. }