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

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