class-studiou-wc-product-manage-product-import.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. <?php
  2. /**
  3. * Product import class
  4. *
  5. * Handles product import from CSV files
  6. *
  7. * @since 1.4.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_Manage_Product_Import {
  16. /**
  17. * @var Studiou_WC_Product_Manage_Product_DB
  18. */
  19. private $db;
  20. /**
  21. * In-request cache of trimmed source URL => attachment ID, so the same URL
  22. * appearing multiple times within one AJAX batch costs at most one DB lookup.
  23. *
  24. * @var array<string,int>
  25. */
  26. private static $url_cache = array();
  27. /**
  28. * Constructor
  29. *
  30. * @param Studiou_WC_Product_Manage_Product_DB $db Database instance
  31. */
  32. public function __construct($db) {
  33. $this->db = $db;
  34. }
  35. /**
  36. * Parse CSV file and store data for batch processing
  37. *
  38. * @param string $file_path Path to CSV file
  39. * @return array Result with total count and transient key
  40. */
  41. public function parse_csv_for_batch($file_path) {
  42. if (!file_exists($file_path)) {
  43. return array('error' => __('File not found', 'studiou-wc-product-cat-manage'));
  44. }
  45. // Open CSV file
  46. $handle = fopen($file_path, 'r');
  47. if (!$handle) {
  48. return array('error' => __('Could not open file', 'studiou-wc-product-cat-manage'));
  49. }
  50. // Read header row
  51. $header = fgetcsv($handle, 0, ',', '"');
  52. if (!$header) {
  53. fclose($handle);
  54. return array('error' => __('Invalid CSV format', 'studiou-wc-product-cat-manage'));
  55. }
  56. // Read all data rows
  57. $rows = array();
  58. $row_number = 1;
  59. while (($row = fgetcsv($handle, 0, ',', '"')) !== false) {
  60. $row_number++;
  61. // Skip empty rows
  62. if (empty(array_filter($row))) {
  63. continue;
  64. }
  65. // Combine header with row data
  66. $data = array_combine($header, $row);
  67. $rows[] = array(
  68. 'row_number' => $row_number,
  69. 'data' => $data
  70. );
  71. }
  72. fclose($handle);
  73. // Store data in transient (expires in 1 hour)
  74. $transient_key = 'studiou_wcpcm_import_' . uniqid();
  75. set_transient($transient_key, $rows, 3600);
  76. return array(
  77. 'transient_key' => $transient_key,
  78. 'total' => count($rows)
  79. );
  80. }
  81. /**
  82. * Process batch of products
  83. *
  84. * @param string $transient_key Transient key with CSV data
  85. * @param int $offset Starting offset
  86. * @param int $batch_size Number of items to process
  87. * @return array Result with statistics
  88. */
  89. public function process_batch($transient_key, $offset = 0, $batch_size = 5) {
  90. $rows = get_transient($transient_key);
  91. if (!$rows) {
  92. return array('error' => __('Import data not found or expired', 'studiou-wc-product-cat-manage'));
  93. }
  94. $result = array(
  95. 'success' => 0,
  96. 'failed' => 0,
  97. 'skipped' => 0,
  98. 'failed_items' => array(),
  99. 'messages' => array(),
  100. 'processed' => 0,
  101. 'total' => count($rows)
  102. );
  103. // Get batch of rows to process
  104. $batch = array_slice($rows, $offset, $batch_size);
  105. foreach ($batch as $item) {
  106. $row_number = $item['row_number'];
  107. $data = $item['data'];
  108. // Process the product
  109. $process_result = $this->process_product_row($data, $row_number);
  110. if ($process_result['status'] === 'success') {
  111. $result['success']++;
  112. // Don't add success messages to log
  113. } elseif ($process_result['status'] === 'skipped') {
  114. $result['skipped']++;
  115. $result['messages'][] = sprintf(
  116. __('Row %d: SKIPPED - %s', 'studiou-wc-product-cat-manage'),
  117. $row_number,
  118. $process_result['message']
  119. );
  120. // Add to failed items for re-processing
  121. $result['failed_items'][] = $data;
  122. } else {
  123. $result['failed']++;
  124. $result['messages'][] = sprintf(
  125. __('Row %d: FAILED - %s', 'studiou-wc-product-cat-manage'),
  126. $row_number,
  127. $process_result['message']
  128. );
  129. // Add to failed items
  130. $result['failed_items'][] = $data;
  131. }
  132. }
  133. $result['processed'] = $offset + count($batch);
  134. return $result;
  135. }
  136. /**
  137. * Process single product row
  138. *
  139. * @param array $data Product data
  140. * @param int $row_number Row number for error reporting
  141. * @return array Result with status and message
  142. */
  143. private function process_product_row($data, $row_number) {
  144. // Validate required fields
  145. if (!isset($data['Typ']) || empty($data['Typ'])) {
  146. return array(
  147. 'status' => 'skipped',
  148. 'message' => __('Missing product type', 'studiou-wc-product-cat-manage')
  149. );
  150. }
  151. // Rule 3: Only allow "variable" or "variation" types
  152. $type = trim($data['Typ']);
  153. if (!in_array($type, array('variable', 'variation'))) {
  154. return array(
  155. 'status' => 'skipped',
  156. 'message' => sprintf(
  157. __('Invalid product type: %s (only "variable" or "variation" allowed)', 'studiou-wc-product-cat-manage'),
  158. $type
  159. )
  160. );
  161. }
  162. // Get product ID
  163. $product_id = isset($data['ID']) ? intval($data['ID']) : 0;
  164. $sku = isset($data['Katalogové číslo']) ? trim($data['Katalogové číslo']) : '';
  165. // Rule 4: SKU must be unique
  166. if (empty($sku)) {
  167. return array(
  168. 'status' => 'skipped',
  169. 'message' => __('Missing SKU (Katalogové číslo)', 'studiou-wc-product-cat-manage')
  170. );
  171. }
  172. if (!$this->db->is_sku_unique($sku, $product_id)) {
  173. return array(
  174. 'status' => 'skipped',
  175. 'message' => sprintf(
  176. __('SKU "%s" already exists', 'studiou-wc-product-cat-manage'),
  177. $sku
  178. )
  179. );
  180. }
  181. // Rule 5: Validate image URL if provided
  182. $image_url = isset($data['Obrázky']) ? trim($data['Obrázky']) : '';
  183. if (!empty($image_url) && !$this->db->validate_image_url($image_url)) {
  184. return array(
  185. 'status' => 'skipped',
  186. 'message' => sprintf(
  187. __('Invalid image URL: %s', 'studiou-wc-product-cat-manage'),
  188. $image_url
  189. )
  190. );
  191. }
  192. // Process based on product type
  193. if ($type === 'variation') {
  194. return $this->process_variation($data, $product_id);
  195. } else {
  196. return $this->process_variable_product($data, $product_id);
  197. }
  198. }
  199. /**
  200. * Process variable product
  201. *
  202. * @param array $data Product data
  203. * @param int $product_id Product ID (0 for new product)
  204. * @return array Result with status and message
  205. */
  206. private function process_variable_product($data, $product_id) {
  207. try {
  208. // Create or update product
  209. if ($product_id == 0) {
  210. $product = new WC_Product_Variable();
  211. } else {
  212. $product = wc_get_product($product_id);
  213. if (!$product || !$product->is_type('variable')) {
  214. return array(
  215. 'status' => 'error',
  216. 'message' => sprintf(
  217. __('Product ID %d is not a variable product', 'studiou-wc-product-cat-manage'),
  218. $product_id
  219. )
  220. );
  221. }
  222. }
  223. // Set basic data
  224. $product->set_name(isset($data['Jméno']) ? $data['Jméno'] : '');
  225. $product->set_sku(isset($data['Katalogové číslo']) ? $data['Katalogové číslo'] : '');
  226. $product->set_short_description(isset($data['Krátký popis']) ? $data['Krátký popis'] : '');
  227. $product->set_description(isset($data['Popis']) ? $data['Popis'] : '');
  228. // Set categories
  229. if (isset($data['Kategorie']) && !empty($data['Kategorie'])) {
  230. $categories = array_map('trim', explode('|', $data['Kategorie']));
  231. $category_ids = array();
  232. error_log('STUDIOU WC IMPORT: Processing categories for product: ' . $product->get_name());
  233. error_log('STUDIOU WC IMPORT: Categories string from CSV: ' . $data['Kategorie']);
  234. foreach ($categories as $category_name) {
  235. if (empty($category_name)) {
  236. continue;
  237. }
  238. $category_id = $this->find_category_by_name($category_name);
  239. error_log('STUDIOU WC IMPORT: Looking for category "' . $category_name . '" - Result: ' . ($category_id ? 'FOUND ID=' . $category_id : 'NOT FOUND'));
  240. if ($category_id) {
  241. $category_ids[] = $category_id;
  242. }
  243. }
  244. error_log('STUDIOU WC IMPORT: Total category IDs found: ' . count($category_ids) . ' - IDs: ' . implode(',', $category_ids));
  245. if (!empty($category_ids)) {
  246. $product->set_category_ids($category_ids);
  247. error_log('STUDIOU WC IMPORT: Categories assigned to product via set_category_ids()');
  248. } else {
  249. error_log('STUDIOU WC IMPORT: WARNING - No valid category IDs found for: ' . $data['Kategorie']);
  250. }
  251. } else {
  252. error_log('STUDIOU WC IMPORT: No categories in CSV for product: ' . $product->get_name());
  253. }
  254. // Handle image
  255. if (isset($data['Obrázky']) && !empty($data['Obrázky'])) {
  256. $image_id = $this->upload_image_from_url($data['Obrázky']);
  257. if ($image_id) {
  258. $product->set_image_id($image_id);
  259. }
  260. }
  261. // Set reviews enabled
  262. $reviews_enabled = isset($data['Povolit zákaznické recenze?']) && $data['Povolit zákaznické recenze?'] === '1';
  263. $product->set_reviews_allowed($reviews_enabled);
  264. // Handle product attribute
  265. if (isset($data['Název 1 vlastnosti']) && !empty($data['Název 1 vlastnosti'])) {
  266. $attribute_name = $data['Název 1 vlastnosti'];
  267. $attribute_values = isset($data['Hodnota(y) 1 vlastnosti']) ? $data['Hodnota(y) 1 vlastnosti'] : '';
  268. $is_visible = isset($data['Vlastnost 1 viditelnost']) && $data['Vlastnost 1 viditelnost'] === '1';
  269. $is_variation = isset($data['Vlastnost 1 varianta']) && $data['Vlastnost 1 varianta'] === '1';
  270. // Create attribute taxonomy if it doesn't exist
  271. $this->db->create_attribute_if_not_exists($attribute_name);
  272. $attribute = new WC_Product_Attribute();
  273. $attribute->set_name(wc_attribute_taxonomy_name($attribute_name));
  274. $attribute->set_visible($is_visible);
  275. $attribute->set_variation($is_variation);
  276. // Set attribute options (terms)
  277. $values = array_map('trim', explode('|', $attribute_values));
  278. $attribute->set_options($values);
  279. $product->set_attributes(array($attribute));
  280. }
  281. // Handle minimum/maximum quantity
  282. if (isset($data['Minimum Quantity']) && !empty($data['Minimum Quantity'])) {
  283. $product->update_meta_data('_minimum_quantity', intval($data['Minimum Quantity']));
  284. }
  285. if (isset($data['Maximum Quantity']) && !empty($data['Maximum Quantity'])) {
  286. $product->update_meta_data('_maximum_quantity', intval($data['Maximum Quantity']));
  287. }
  288. // Save product
  289. $saved_id = $product->save();
  290. $message = $product_id == 0 ?
  291. sprintf(__('Created variable product: %s', 'studiou-wc-product-cat-manage'), $product->get_name()) :
  292. sprintf(__('Updated variable product: %s', 'studiou-wc-product-cat-manage'), $product->get_name());
  293. return array(
  294. 'status' => 'success',
  295. 'message' => $message
  296. );
  297. } catch (Exception $e) {
  298. return array(
  299. 'status' => 'error',
  300. 'message' => $e->getMessage()
  301. );
  302. }
  303. }
  304. /**
  305. * Process product variation
  306. *
  307. * @param array $data Product data
  308. * @param int $variation_id Variation ID (0 for new variation)
  309. * @return array Result with status and message
  310. */
  311. private function process_variation($data, $variation_id) {
  312. try {
  313. // Rule 6: Must have parent reference
  314. if (!isset($data['Nadřazené']) || empty($data['Nadřazené'])) {
  315. return array(
  316. 'status' => 'skipped',
  317. 'message' => __('Missing parent product reference (Nadřazené)', 'studiou-wc-product-cat-manage')
  318. );
  319. }
  320. // Rule 7: Must have regular price
  321. if (!isset($data['Běžná cena']) || empty($data['Běžná cena'])) {
  322. return array(
  323. 'status' => 'skipped',
  324. 'message' => __('Missing regular price (Běžná cena)', 'studiou-wc-product-cat-manage')
  325. );
  326. }
  327. // Find parent product by SKU
  328. $parent_sku = trim($data['Nadřazené']);
  329. $parent_product = $this->db->get_product_by_sku($parent_sku);
  330. if (!$parent_product || !$parent_product->is_type('variable')) {
  331. return array(
  332. 'status' => 'skipped',
  333. 'message' => sprintf(
  334. __('Parent product with SKU "%s" not found or not variable', 'studiou-wc-product-cat-manage'),
  335. $parent_sku
  336. )
  337. );
  338. }
  339. // Create or update variation
  340. if ($variation_id == 0) {
  341. $variation = new WC_Product_Variation();
  342. $variation->set_parent_id($parent_product->get_id());
  343. } else {
  344. $variation = wc_get_product($variation_id);
  345. if (!$variation || !$variation->is_type('variation')) {
  346. return array(
  347. 'status' => 'error',
  348. 'message' => sprintf(
  349. __('Product ID %d is not a variation', 'studiou-wc-product-cat-manage'),
  350. $variation_id
  351. )
  352. );
  353. }
  354. }
  355. // Set basic data
  356. $variation->set_name(isset($data['Jméno']) ? $data['Jméno'] : '');
  357. $variation->set_sku(isset($data['Katalogové číslo']) ? $data['Katalogové číslo'] : '');
  358. $variation->set_description(isset($data['Popis']) ? $data['Popis'] : '');
  359. $variation->set_regular_price($data['Běžná cena']);
  360. // Handle image
  361. if (isset($data['Obrázky']) && !empty($data['Obrázky'])) {
  362. $image_id = $this->upload_image_from_url($data['Obrázky']);
  363. if ($image_id) {
  364. $variation->set_image_id($image_id);
  365. }
  366. }
  367. // Set variation attributes
  368. if (isset($data['Název 1 vlastnosti']) && !empty($data['Název 1 vlastnosti']) &&
  369. isset($data['Hodnota(y) 1 vlastnosti']) && !empty($data['Hodnota(y) 1 vlastnosti'])) {
  370. $attribute_name = wc_attribute_taxonomy_name($data['Název 1 vlastnosti']);
  371. $attribute_value = $data['Hodnota(y) 1 vlastnosti'];
  372. $variation->set_attributes(array(
  373. $attribute_name => $attribute_value
  374. ));
  375. }
  376. // Handle minimum/maximum quantity
  377. if (isset($data['Minimum Quantity']) && !empty($data['Minimum Quantity'])) {
  378. $variation->update_meta_data('_minimum_quantity', intval($data['Minimum Quantity']));
  379. }
  380. if (isset($data['Maximum Quantity']) && !empty($data['Maximum Quantity'])) {
  381. $variation->update_meta_data('_maximum_quantity', intval($data['Maximum Quantity']));
  382. }
  383. // Save variation
  384. $saved_id = $variation->save();
  385. $message = $variation_id == 0 ?
  386. sprintf(__('Created variation: %s', 'studiou-wc-product-cat-manage'), $variation->get_name()) :
  387. sprintf(__('Updated variation: %s', 'studiou-wc-product-cat-manage'), $variation->get_name());
  388. return array(
  389. 'status' => 'success',
  390. 'message' => $message
  391. );
  392. } catch (Exception $e) {
  393. return array(
  394. 'status' => 'error',
  395. 'message' => $e->getMessage()
  396. );
  397. }
  398. }
  399. /**
  400. * Find an attachment previously imported from this exact source URL.
  401. *
  402. * Uses get_posts (not a raw $wpdb query) so a row whose attachment post was
  403. * deleted but whose meta was somehow orphaned can't resolve to a missing post.
  404. * Orders by ID ascending so the earliest (canonical) attachment wins
  405. * deterministically if more than one ever carries the same source URL.
  406. *
  407. * @param string $url Trimmed source URL.
  408. * @return int Attachment ID, or 0 if none.
  409. */
  410. private function find_attachment_by_source_url($url) {
  411. $ids = get_posts(array(
  412. 'post_type' => 'attachment',
  413. 'post_status' => 'inherit',
  414. 'posts_per_page' => 1,
  415. 'orderby' => 'ID',
  416. 'order' => 'ASC',
  417. 'fields' => 'ids',
  418. 'no_found_rows' => true,
  419. 'update_post_meta_cache' => false,
  420. 'update_post_term_cache' => false,
  421. 'meta_query' => array(
  422. array(
  423. 'key' => '_studiou_wcpcm_source_url',
  424. 'value' => $url,
  425. 'compare' => '=',
  426. ),
  427. ),
  428. ));
  429. return !empty($ids) ? (int) $ids[0] : 0;
  430. }
  431. /**
  432. * Upload an image from a URL, deduplicating by source URL.
  433. *
  434. * A given source URL is downloaded at most once: an in-request static cache
  435. * absorbs repeats within a batch, and a `_studiou_wcpcm_source_url` postmeta
  436. * lookup reuses attachments across batches and across imports.
  437. *
  438. * @param string $url Image URL (raw value from the Obrázky column).
  439. * @return int|null Attachment ID, or null on empty input / download failure.
  440. */
  441. private function upload_image_from_url($url) {
  442. // Normalize the key. process_product_row() validates a *trimmed* URL but
  443. // the callers pass the raw cell, so trim here to keep the cache key, the
  444. // DB lookup, the download, and the stored postmeta all identical to the
  445. // value that was validated (and to collapse whitespace-only variants).
  446. $url = is_string($url) ? trim($url) : '';
  447. if ($url === '') {
  448. return null;
  449. }
  450. // Layer 2 — in-request static cache.
  451. if (isset(self::$url_cache[$url])) {
  452. if (defined('WP_DEBUG') && WP_DEBUG) {
  453. error_log('STUDIOU WC IMPORT: image cache HIT (request) ' . $url . ' -> ' . self::$url_cache[$url]);
  454. }
  455. return self::$url_cache[$url];
  456. }
  457. // Layer 1 — persistent postmeta lookup (across batches and re-imports).
  458. $existing = $this->find_attachment_by_source_url($url);
  459. if ($existing) {
  460. self::$url_cache[$url] = $existing;
  461. if (defined('WP_DEBUG') && WP_DEBUG) {
  462. error_log('STUDIOU WC IMPORT: image cache HIT (db) ' . $url . ' -> ' . $existing);
  463. }
  464. return $existing;
  465. }
  466. // Layer 0 — fresh sideload.
  467. require_once(ABSPATH . 'wp-admin/includes/media.php');
  468. require_once(ABSPATH . 'wp-admin/includes/file.php');
  469. require_once(ABSPATH . 'wp-admin/includes/image.php');
  470. // Suppress intermediate sizes for import speed. Use the stable
  471. // '__return_empty_array' callable (not a fresh closure) so remove_filter()
  472. // can actually match it, and detach it in finally so it can never leak
  473. // into later media operations in this request.
  474. add_filter('intermediate_image_sizes_advanced', '__return_empty_array');
  475. try {
  476. // download_url()'s second arg sets the request timeout (30s); no
  477. // http_request_timeout filter is needed.
  478. $tmp = download_url($url, 30);
  479. if (is_wp_error($tmp)) {
  480. error_log('STUDIOU WC IMPORT: image download failed for ' . $url . ' - ' . $tmp->get_error_message());
  481. return null;
  482. }
  483. // Derive a clean on-disk filename. parse_url() strips any query string
  484. // (img.jpg?v=2 -> img.jpg) so wp_unique_filename() doesn't fold the
  485. // query into the basename. Null-safe: parse_url() may return null/false
  486. // and basename(null) is deprecated on PHP 8.1+ (we require 8.2).
  487. $path = parse_url($url, PHP_URL_PATH);
  488. $name = (is_string($path) && $path !== '') ? basename($path) : '';
  489. if ($name === '') {
  490. $name = 'image-' . md5($url) . '.jpg';
  491. }
  492. $file_array = array(
  493. 'name' => $name,
  494. 'tmp_name' => $tmp,
  495. );
  496. $id = media_handle_sideload($file_array, 0);
  497. if (is_wp_error($id)) {
  498. @unlink($tmp);
  499. error_log('STUDIOU WC IMPORT: image sideload failed for ' . $url . ' - ' . $id->get_error_message());
  500. return null;
  501. }
  502. // Tag the attachment so future rows / batches / imports dedup on it.
  503. update_post_meta($id, '_studiou_wcpcm_source_url', $url);
  504. self::$url_cache[$url] = (int) $id;
  505. if (defined('WP_DEBUG') && WP_DEBUG) {
  506. error_log('STUDIOU WC IMPORT: image sideloaded ' . $url . ' -> ' . $id);
  507. }
  508. return (int) $id;
  509. } catch (Exception $e) {
  510. error_log('STUDIOU WC IMPORT: image upload exception for ' . $url . ' - ' . $e->getMessage());
  511. return null;
  512. } finally {
  513. remove_filter('intermediate_image_sizes_advanced', '__return_empty_array');
  514. }
  515. }
  516. /**
  517. * Find category by name (simple lookup, categories have unique names)
  518. *
  519. * @param string $category_name Category name
  520. * @return int|null Category ID or null if not found
  521. */
  522. private function find_category_by_name($category_name) {
  523. // Trim and normalize the category name
  524. $category_name = trim($category_name);
  525. if (empty($category_name)) {
  526. return null;
  527. }
  528. // Simple name lookup only (no hierarchy detection)
  529. // Categories have unique names throughout the system
  530. error_log('STUDIOU WC IMPORT: find_category_by_name() called for: "' . $category_name . '"');
  531. // Method 1: Exact name match
  532. $term = get_term_by('name', $category_name, 'product_cat');
  533. if ($term) {
  534. error_log('STUDIOU WC IMPORT: Found by exact name match - ID: ' . $term->term_id);
  535. return $term->term_id;
  536. }
  537. // Method 2: Try by slug
  538. $slug = sanitize_title($category_name);
  539. error_log('STUDIOU WC IMPORT: Exact name failed, trying slug: "' . $slug . '"');
  540. $term = get_term_by('slug', $slug, 'product_cat');
  541. if ($term) {
  542. error_log('STUDIOU WC IMPORT: Found by slug match - ID: ' . $term->term_id);
  543. return $term->term_id;
  544. }
  545. // Method 3: Search case-insensitively through all categories
  546. $all_terms = get_terms(array(
  547. 'taxonomy' => 'product_cat',
  548. 'hide_empty' => false
  549. ));
  550. error_log('STUDIOU WC IMPORT: Slug failed, searching ' . count($all_terms) . ' categories case-insensitively');
  551. foreach ($all_terms as $t) {
  552. if (strcasecmp($t->name, $category_name) === 0) {
  553. error_log('STUDIOU WC IMPORT: Found by case-insensitive match - ID: ' . $t->term_id . ', name: "' . $t->name . '"');
  554. return $t->term_id;
  555. }
  556. }
  557. // Not found - try to create it
  558. error_log('STUDIOU WC IMPORT: Category NOT FOUND: "' . $category_name . '" - Attempting to create it');
  559. $new_term = wp_insert_term(
  560. $category_name,
  561. 'product_cat',
  562. array(
  563. 'slug' => $slug
  564. )
  565. );
  566. if (is_wp_error($new_term)) {
  567. error_log('STUDIOU WC IMPORT: Failed to create category "' . $category_name . '": ' . $new_term->get_error_message());
  568. error_log('STUDIOU WC IMPORT: Total available categories: ' . count($all_terms));
  569. // Show first 20 categories for debugging
  570. $sample_cats = array_slice($all_terms, 0, 20);
  571. foreach ($sample_cats as $cat) {
  572. error_log('STUDIOU WC IMPORT: Available: "' . $cat->name . '" (ID: ' . $cat->term_id . ', slug: ' . $cat->slug . ')');
  573. }
  574. return null;
  575. } else {
  576. $term_id = $new_term['term_id'];
  577. error_log('STUDIOU WC IMPORT: Successfully created category "' . $category_name . '" with ID: ' . $term_id);
  578. return $term_id;
  579. }
  580. }
  581. /**
  582. * Generate CSV with failed items
  583. *
  584. * @param array $failed_items Array of failed product data
  585. * @return string CSV content
  586. */
  587. public function generate_failed_csv($failed_items) {
  588. if (empty($failed_items)) {
  589. return '';
  590. }
  591. // Define CSV header
  592. $header = array(
  593. 'ID', 'Typ', 'Katalogové číslo', 'Jméno', 'Nadřazené', 'Krátký popis', 'Popis',
  594. 'Název 1 vlastnosti', 'Hodnota(y) 1 vlastnosti', 'Kategorie', 'Obrázky', 'Běžná cena',
  595. 'Vlastnost 1 viditelnost', 'Vlastnost 1 globální', 'Vlastnost 1 varianta',
  596. 'Povolit zákaznické recenze?', 'Minimum Quantity', 'Maximum Quantity'
  597. );
  598. // Start CSV output
  599. $csv = '';
  600. $csv .= '"' . implode('","', $header) . '"' . "\n";
  601. // Add failed items
  602. foreach ($failed_items as $item) {
  603. $row = array();
  604. foreach ($header as $column) {
  605. $value = isset($item[$column]) ? $item[$column] : '';
  606. $row[] = '"' . str_replace('"', '""', $value) . '"';
  607. }
  608. $csv .= implode(',', $row) . "\n";
  609. }
  610. return $csv;
  611. }
  612. }