eksrelay_api.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. <?php
  2. /**
  3. * Plugin Name: EKSRelay API
  4. * Description: Dedykowane REST API dla EKSRelay – get_car_data i get_product_compatibility.
  5. * Otwarte endpointy REST (bez autoryzacji) – odpowiedniki nopriv AJAX.
  6. * Wdróż ten plik na serwer WP jako: /wp-content/mu-plugins/eksrelay_api.php
  7. * Version: 1.0.0
  8. */
  9. if ( ! defined( 'ABSPATH' ) ) {
  10. exit;
  11. }
  12. // ═══════════════════════════════════════════════════════════════════
  13. // Rejestracja tras REST
  14. // ═══════════════════════════════════════════════════════════════════
  15. add_action( 'rest_api_init', function () {
  16. register_rest_route( 'eksrelay/v1', '/car-data', [
  17. 'methods' => 'POST',
  18. 'callback' => 'eksrelay_car_data',
  19. 'permission_callback' => '__return_true',
  20. ] );
  21. register_rest_route( 'eksrelay/v1', '/product-compatibility', [
  22. 'methods' => 'POST',
  23. 'callback' => 'eksrelay_product_compatibility',
  24. 'permission_callback' => '__return_true',
  25. ] );
  26. } );
  27. // ═══════════════════════════════════════════════════════════════════
  28. // Handler: POST /wp-json/eksrelay/v1/car-data
  29. //
  30. // Body JSON: { car_year, car_brand?, car_model?, car_engine? }
  31. // ═══════════════════════════════════════════════════════════════════
  32. function eksrelay_car_data( WP_REST_Request $request ) {
  33. $body = $request->get_json_params() ?: [];
  34. if ( empty( $body['car_year'] ) ) {
  35. return [ 'error' => 'car_year jest wymagany' ];
  36. }
  37. $car_year = intval( sanitize_text_field( $body['car_year'] ) );
  38. $has_brand = ! empty( $body['car_brand'] );
  39. $has_model = ! empty( $body['car_model'] );
  40. $car_brand = false;
  41. $car_model = false;
  42. if ( ! $has_brand && ! $has_model ) {
  43. return [ 'error' => 'car_brand lub car_model jest wymagany' ];
  44. }
  45. // ── Tylko brand, bez modelu ──────────────────────────────────────
  46. if ( $has_brand && ! $has_model ) {
  47. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  48. $termIds = get_terms( [ 'name__like' => $car_brand, 'parent' => 0, 'fields' => 'ids' ] );
  49. if ( count( $termIds ) === 1 ) {
  50. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  51. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  52. }
  53. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  54. }
  55. // ── Tylko model, bez brandu ─────────────────────────────────────
  56. if ( $has_model && ! $has_brand ) {
  57. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  58. $termIds = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  59. // exact match → auto-wybierz
  60. foreach ( $termIds as $tid ) {
  61. $term = get_term_by( 'id', $tid, 'car_model' );
  62. if ( $term && eksrelay_replace_ascii( $term->name ) === $car_model ) {
  63. $termIds = [ $term->term_id ];
  64. break;
  65. }
  66. }
  67. if ( count( $termIds ) === 1 ) {
  68. $term = get_term( $termIds[0] );
  69. if ( ! is_wp_error( $term ) && $term->parent !== 0 ) {
  70. $parent = get_term( $term->parent );
  71. if ( ! is_wp_error( $parent ) ) {
  72. $car_brand = $parent->name;
  73. }
  74. } else {
  75. return [ 'error' => 'nie znaleziono takiego modelu', 'car_model' => $car_model ];
  76. }
  77. } else {
  78. $models = [];
  79. foreach ( $termIds as $tid ) {
  80. $t = get_term_by( 'id', $tid, 'car_model' );
  81. if ( $t ) {
  82. $models[] = $t->name;
  83. }
  84. }
  85. if ( $models ) {
  86. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $models, 'filtered' => true ];
  87. }
  88. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  89. }
  90. }
  91. // ── Mamy oba ────────────────────────────────────────────────────
  92. if ( ! $car_brand ) {
  93. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  94. }
  95. if ( ! $car_model ) {
  96. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  97. }
  98. $car_engine = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_engine'] ?? '' ) ) );
  99. $termIds = get_terms( [ 'name__like' => $car_brand, 'fields' => 'ids' ] );
  100. $termIds2 = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  101. if ( ! count( $termIds ) ) {
  102. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  103. }
  104. if ( ! count( $termIds2 ) ) {
  105. if ( count( $termIds ) === 1 ) {
  106. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  107. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  108. }
  109. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  110. }
  111. $query = new WP_Query( [
  112. 'post_type' => 'car',
  113. 'posts_per_page' => -1,
  114. 'tax_query' => [
  115. 'relation' => 'AND',
  116. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  117. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds2 ],
  118. [ 'taxonomy' => 'car_production_year', 'field' => 'slug', 'terms' => (string) $car_year ],
  119. ],
  120. ] );
  121. $cars = $query->get_posts();
  122. $engine_info = eksrelay_get_engines_info( $cars, true, $car_year );
  123. if ( ! $cars ) {
  124. return [
  125. 'error' => 'nie znaleziono auta, ' . get_option(
  126. 'aiac_tool_get_car_data_no_car',
  127. 'Orientacyjnie do 1994 roku włącznie powinien pasować gaz R12, dla aut 1995-2016 gaz R134A a dla aut od 2016 roku gaz R1234YF'
  128. ),
  129. 'car_brand' => $car_brand,
  130. 'car_model' => $car_model,
  131. ];
  132. }
  133. $engine_names = array_column( $engine_info, 'name' );
  134. if ( count( $engine_info ) === 1 ) {
  135. $car_engine = $engine_info[0]['name'];
  136. }
  137. if ( count( $engine_info ) > 1 && ! $car_engine ) {
  138. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  139. }
  140. foreach ( $engine_info as $eng ) {
  141. if ( strtolower( trim( $eng['name'] ) ) !== strtolower( trim( $car_engine ) ) ) {
  142. continue;
  143. }
  144. $car_id = intval( $eng['id'] );
  145. $maybe_diff = get_field( 'custom_ac', $car_id );
  146. $gas_types = array_unique( array_filter( [
  147. get_field( 'ac_gas_type', $car_id ),
  148. $maybe_diff ? get_field( 'ac_gas_type_2', $car_id ) : '',
  149. ] ) );
  150. $year_term = get_terms( [ 'taxonomy' => 'car_production_year', 'name__like' => $car_year ] );
  151. $brand_term = $termIds ? get_term( $termIds[0] ) : false;
  152. $model_term = $termIds2 ? get_term( $termIds2[0] ) : false;
  153. $data = [
  154. 'success' => true,
  155. 'selected_car' => [
  156. 'ek_ac_gas_type' => implode( ',', $gas_types ),
  157. 'ek_brand_id' => $termIds[0] ?? '',
  158. 'ek_brand' => ( $brand_term && ! is_wp_error( $brand_term ) ) ? $brand_term->name : $car_brand,
  159. 'ek_car_id' => $car_id,
  160. 'ek_engine_type' => $eng['name'],
  161. 'ek_info' => '',
  162. 'ek_model_id' => $termIds2[0] ?? '',
  163. 'ek_model' => ( $model_term && ! is_wp_error( $model_term ) ) ? $model_term->name : $car_model,
  164. 'ek_year_id' => ( ! is_wp_error( $year_term ) && $year_term ) ? $year_term[0]->term_id : '',
  165. 'ek_year' => $car_year,
  166. ],
  167. 'shop_url' => $eng['url'],
  168. 'adapters' => get_field( 'adapters', $car_id ) ?: false,
  169. 'ac_gas_type' => get_field( 'ac_gas_type', $car_id ),
  170. 'ac_gas_amount' => ( get_field( 'ac_gas_amount', $car_id ) ?: '-' ) . ' g',
  171. 'ac_ports_count' => intval( get_field( 'ac_ports_count', $car_id ) ),
  172. 'ac_oil' => get_field( 'ac_oil', $car_id ),
  173. 'ac_oil_amount' => ( get_field( 'ac_oil_amount', $car_id ) ?: '-' ) . ' cm3',
  174. 'ac_clutch' => get_field( 'ac_clutch', $car_id ),
  175. 'maybe_different_layout' => $maybe_diff,
  176. ];
  177. if ( $maybe_diff ) {
  178. $data['different_layout_info'] = get_field( 'custom_ac_info', $car_id ) ?: '';
  179. $data['different_layout_adapters'] = get_field( 'adapters_2', $car_id ) ?: false;
  180. $data['different_layout_ac_gas_type'] = get_field( 'ac_gas_type_2', $car_id );
  181. $data['different_layout_ac_gas_amount'] = ( get_field( 'ac_gas_amount_2', $car_id ) ?: '-' ) . ' g';
  182. $data['different_layout_ac_ports_count'] = get_field( 'ac_ports_count_2', $car_id );
  183. $data['different_layout_ac_oil'] = get_field( 'ac_oil_2', $car_id );
  184. $data['different_layout_ac_oil_amount'] = ( get_field( 'ac_oil_amount_2', $car_id ) ?: '-' ) . ' cm3';
  185. $data['different_layout_ac_clutch'] = get_field( 'ac_clutch_2', $car_id );
  186. }
  187. return $data;
  188. }
  189. // podany silnik nie pasuje do żadnego na liście → pokaż opcje
  190. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  191. }
  192. // ═══════════════════════════════════════════════════════════════════
  193. // Handler: POST /wp-json/eksrelay/v1/product-compatibility
  194. //
  195. // Body JSON: { car_year, car_brand?, car_model?, car_engine?, product_name? }
  196. // ═══════════════════════════════════════════════════════════════════
  197. function eksrelay_product_compatibility( WP_REST_Request $request ) {
  198. $body = $request->get_json_params() ?: [];
  199. if ( empty( $body['car_year'] ) ) {
  200. return [ 'error' => 'car_year jest wymagany' ];
  201. }
  202. $lang = sanitize_text_field( $body['lang'] ?? 'pl' );
  203. $car_year = intval( sanitize_text_field( $body['car_year'] ) );
  204. $has_brand = ! empty( $body['car_brand'] );
  205. $has_model = ! empty( $body['car_model'] );
  206. $car_brand = false;
  207. $car_model = false;
  208. // ── Tylko brand ─────────────────────────────────────────────────
  209. if ( $has_brand && ! $has_model ) {
  210. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  211. $termIds = get_terms( [ 'name__like' => $car_brand, 'parent' => 0, 'fields' => 'ids' ] );
  212. if ( count( $termIds ) === 1 ) {
  213. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  214. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  215. }
  216. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  217. }
  218. // ── Tylko model ─────────────────────────────────────────────────
  219. if ( $has_model && ! $has_brand ) {
  220. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  221. $termIds = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  222. if ( count( $termIds ) === 1 ) {
  223. $term = get_term( $termIds[0] );
  224. if ( ! is_wp_error( $term ) && $term->parent !== 0 ) {
  225. $parent = get_term( $term->parent );
  226. if ( ! is_wp_error( $parent ) ) {
  227. $car_brand = $parent->name;
  228. }
  229. } else {
  230. return [ 'error' => 'nie znaleziono takiego modelu', 'car_model' => $car_model ];
  231. }
  232. } else {
  233. $models = [];
  234. foreach ( $termIds as $tid ) {
  235. $t = get_term_by( 'id', $tid, 'car_model' );
  236. if ( $t ) {
  237. $models[] = $t->name;
  238. }
  239. }
  240. if ( $models ) {
  241. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $models, 'filtered' => true ];
  242. }
  243. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  244. }
  245. }
  246. if ( ! $has_brand && ! $has_model ) {
  247. return [ 'error' => 'car_brand lub car_model jest wymagany' ];
  248. }
  249. if ( ! $car_brand ) {
  250. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  251. }
  252. if ( ! $car_model ) {
  253. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  254. }
  255. $car_engine = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_engine'] ?? '' ) ) );
  256. $product_name = eksrelay_replace_ascii( trim( sanitize_text_field( $body['product_name'] ?? '' ) ) );
  257. // ── Znajdź produkt ──────────────────────────────────────────────
  258. $product = false;
  259. if ( $product_name ) {
  260. $products = eksrelay_search_products_by_name( $product_name );
  261. if ( count( $products ) > 1 ) {
  262. // exact match → auto-wybierz
  263. foreach ( $products as $p ) {
  264. if ( eksrelay_replace_ascii( strtolower( trim( $p->get_title() ) ) ) === strtolower( $product_name ) ) {
  265. $product = $p;
  266. break;
  267. }
  268. }
  269. if ( ! $product ) {
  270. return [
  271. 'error' => 'options',
  272. 'field' => 'product_name',
  273. 'options' => array_map( fn( $p ) => $p->get_title(), $products ),
  274. 'filtered' => true,
  275. ];
  276. }
  277. } elseif ( count( $products ) === 1 ) {
  278. $product = $products[0];
  279. }
  280. }
  281. // ── Znajdź auto ─────────────────────────────────────────────────
  282. $termIds = get_terms( [ 'name__like' => $car_brand, 'fields' => 'ids' ] );
  283. $termIds2 = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  284. // Uwaga: celowo bez filtra roku – engine_info filtruje rok wewnętrznie
  285. $query = new WP_Query( [
  286. 'post_type' => 'car',
  287. 'posts_per_page' => -1,
  288. 'tax_query' => [
  289. 'relation' => 'AND',
  290. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  291. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds2 ],
  292. ],
  293. ] );
  294. $cars = $query->get_posts();
  295. $engine_info = eksrelay_get_engines_info( $cars, false, $car_year );
  296. if ( ! $cars ) {
  297. return [ 'error' => 'nie znaleziono takiego samochodu', 'car_brand' => $car_brand, 'car_model' => $car_model ];
  298. }
  299. $engine_names = array_column( $engine_info, 'name' );
  300. if ( count( $engine_info ) === 1 ) {
  301. $car_engine = $engine_info[0]['name'];
  302. }
  303. if ( count( $engine_info ) > 1 && ! $car_engine ) {
  304. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  305. }
  306. foreach ( $engine_info as $eng ) {
  307. if ( strtolower( trim( $eng['name'] ) ) !== strtolower( trim( $car_engine ) ) ) {
  308. continue;
  309. }
  310. $engine_gas = array_values( array_filter( [ $eng['ac_gas_type'] ?? '', $eng['ac_gas_type_2'] ?? '' ] ) );
  311. $engine_adapters = array_values( array_filter( [ $eng['adapters'] ?? '', $eng['adapters_2'] ?? '' ] ) );
  312. if ( ! $engine_gas ) $engine_gas = [ 'no-gas' ];
  313. if ( ! $engine_adapters ) $engine_adapters = [ 'no' ];
  314. if ( $product ) {
  315. // ── Sprawdzenie kompatybilności konkretnego produktu ─────────
  316. $attributes = eksrelay_product_attributes( $product );
  317. foreach ( $attributes as $k => $arr ) {
  318. $attributes[ $k ] = array_map( fn( $slug ) => str_replace( "-{$lang}", '', $slug ), $arr );
  319. }
  320. if ( ! isset( $attributes['pa_rg'] ) || empty( $attributes['pa_rg'] ) ) $attributes['pa_rg'] = [ 'no-gas' ];
  321. if ( ! isset( $attributes['pa_ra'] ) || empty( $attributes['pa_ra'] ) ) $attributes['pa_ra'] = [ 'no' ];
  322. $gas_fit = count( array_intersect( $engine_gas, $attributes['pa_rg'] ) ) > 0;
  323. $adapter_fit = count( array_intersect( $engine_adapters, $attributes['pa_ra'] ) ) > 0;
  324. return [
  325. 'success' => true,
  326. 'fit' => $gas_fit && $adapter_fit,
  327. 'gas_fit' => $gas_fit,
  328. 'adapter_fit' => $adapter_fit,
  329. 'selected_engine' => $eng,
  330. 'selected_product' => [
  331. 'id' => $product->get_id(),
  332. 'title' => $product->get_title(),
  333. 'type' => $product->get_type(),
  334. 'attributes' => $attributes,
  335. ],
  336. ];
  337. }
  338. // ── Brak konkretnego produktu – lista wszystkich kompatybilnych ─
  339. $all_products = wc_get_products( [
  340. 'status' => 'publish',
  341. 'visibility' => 'visible',
  342. 'limit' => -1,
  343. 'orderby' => 'name',
  344. ] );
  345. $compatible = [];
  346. foreach ( $all_products as $p ) {
  347. $attrs = eksrelay_product_attributes( $p );
  348. foreach ( $attrs as $k => $arr ) {
  349. $attrs[ $k ] = array_map( fn( $slug ) => str_replace( "-{$lang}", '', $slug ), $arr );
  350. }
  351. $p_gas = ( isset( $attrs['pa_rg'] ) && ! empty( $attrs['pa_rg'] ) ) ? $attrs['pa_rg'] : [ 'no-gas' ];
  352. $p_adapters = ( isset( $attrs['pa_ra'] ) && ! empty( $attrs['pa_ra'] ) ) ? $attrs['pa_ra'] : [ 'no' ];
  353. if (
  354. count( array_intersect( $engine_gas, $p_gas ) ) > 0 &&
  355. count( array_intersect( $engine_adapters, $p_adapters ) ) > 0
  356. ) {
  357. $compatible[] = [
  358. 'id' => $p->get_id(),
  359. 'title' => $p->get_title(),
  360. 'price' => $p->get_price(),
  361. 'permalink' => get_permalink( $p->get_id() ),
  362. ];
  363. }
  364. }
  365. return [
  366. 'success' => true,
  367. 'compatible_products' => $compatible,
  368. 'selected_engine' => $eng,
  369. ];
  370. }
  371. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  372. }
  373. // ═══════════════════════════════════════════════════════════════════
  374. // Pomocnicze funkcje wewnętrzne
  375. // ═══════════════════════════════════════════════════════════════════
  376. /**
  377. * Zwraca listę modeli dla danej marki (termIds) i roku produkcji.
  378. */
  379. function eksrelay_models_for_brand_year( array $termIds, int $car_year ): array {
  380. $query = new WP_Query( [
  381. 'post_type' => 'car',
  382. 'posts_per_page' => -1,
  383. 'tax_query' => [
  384. 'relation' => 'AND',
  385. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  386. [ 'taxonomy' => 'car_production_year', 'field' => 'slug', 'terms' => [ (string) $car_year ] ],
  387. ],
  388. ] );
  389. $car_models = [];
  390. foreach ( $query->get_posts() as $car ) {
  391. foreach ( wp_get_post_terms( $car->ID, 'car_model' ) as $term ) {
  392. if ( ! in_array( $term->name, $car_models, true ) && $term->parent !== 0 ) {
  393. $car_models[] = $term->name;
  394. }
  395. }
  396. }
  397. return $car_models;
  398. }
  399. /**
  400. * Zwraca listę wszystkich marek aut (terminy car_model z parent=0).
  401. */
  402. function eksrelay_all_brands(): array {
  403. return (array) get_terms( [
  404. 'taxonomy' => 'car_model',
  405. 'parent' => 0,
  406. 'fields' => 'names',
  407. 'hide_empty' => true,
  408. ] );
  409. }
  410. /**
  411. * Zwraca info o silnikach dla podanych postów 'car'.
  412. *
  413. * Parametr $prefiltered:
  414. * true – WP_Query już przefiltrował po roku przez taxonomy (get_car_data)
  415. * false – rok musi być sprawdzony wewnętrznie przez pola ACF year_from / year_to (get_product_compatibility)
  416. *
  417. * Nazwa silnika jest budowana z pól ACF: engine_type, engine_size (ccm), engine_power_kw, engine_power_km.
  418. * Format: "B 1.8 - 141 kW / 192 KM"
  419. *
  420. * Zakres roku pochodzi z pól ACF year_from / year_to (przechowywane jako term_id taksonomii car_production_year).
  421. *
  422. * Dodatkowe warianty silnika mogą być przechowywane w ACF repeaterze 'engines' na poście car.
  423. */
  424. function eksrelay_get_engines_info( array $cars, bool $prefiltered, int $car_year ): array {
  425. $engines = [];
  426. $seen = [];
  427. foreach ( $cars as $car ) {
  428. $car_id = $car->ID;
  429. // ── Filtrowanie zakresu roku przez pola ACF year_from / year_to ─
  430. if ( $car_year ) {
  431. $year_from_id = get_field( 'year_from', $car_id );
  432. $year_to_id = get_field( 'year_to', $car_id );
  433. $year_from = 0;
  434. $year_to = 9999;
  435. if ( $year_from_id ) {
  436. $t = get_term( (int) $year_from_id, 'car_production_year' );
  437. if ( $t && ! is_wp_error( $t ) ) {
  438. $year_from = (int) $t->slug;
  439. }
  440. }
  441. if ( $year_to_id ) {
  442. $t = get_term( (int) $year_to_id, 'car_production_year' );
  443. if ( $t && ! is_wp_error( $t ) ) {
  444. $year_to = (int) $t->slug;
  445. }
  446. }
  447. if ( $car_year < $year_from || $car_year > $year_to ) {
  448. continue;
  449. }
  450. }
  451. // ── Budowanie nazwy silnika z pól ACF ────────────────────────────
  452. $engine_type = (string) ( get_field( 'engine_type', $car_id ) ?: '' );
  453. $engine_size_cc = (float) ( get_field( 'engine_size', $car_id ) ?: 0 );
  454. $power_kw = (string) ( get_field( 'engine_power_kw', $car_id ) ?: '' );
  455. $power_km = (string) ( get_field( 'engine_power_km', $car_id ) ?: '' );
  456. $engine_size = number_format( $engine_size_cc / 1000, 1 );
  457. $name = "{$engine_type} {$engine_size} - {$power_kw} kW / {$power_km} KM";
  458. // ── Typ gazu i adaptery ──────────────────────────────────────────
  459. $ac_gas_type = (string) ( get_field( 'ac_gas_type', $car_id ) ?: '' );
  460. $ac_gas_type_2 = (string) ( get_field( 'ac_gas_type_2', $car_id ) ?: '' );
  461. $adapters_raw = get_field( 'adapters', $car_id );
  462. $adapters_raw2 = get_field( 'adapters_2', $car_id );
  463. $adapters = is_array( $adapters_raw ) ? ( implode( ',', $adapters_raw ) ?: 'no' ) : (string) ( $adapters_raw ?: 'no' );
  464. $adapters_2 = is_array( $adapters_raw2 ) ? implode( ',', $adapters_raw2 ) : (string) ( $adapters_raw2 ?: '' );
  465. // ── Korekty gazu na podstawie roku (sanity check) ────────────────
  466. if ( $car_year ) {
  467. if ( $car_year <= 1994 && $ac_gas_type === '' ) {
  468. $ac_gas_type = 'r12';
  469. } elseif ( $car_year >= 2017 && $ac_gas_type === '' ) {
  470. $ac_gas_type = 'r1234yf';
  471. } elseif ( $car_year >= 1995 && $car_year <= 2016 && $ac_gas_type === '' ) {
  472. $ac_gas_type = 'r134a';
  473. }
  474. }
  475. // ── Główny silnik ────────────────────────────────────────────────
  476. $key = mb_strtolower( $name );
  477. if ( ! isset( $seen[ $key ] ) ) {
  478. $seen[ $key ] = true;
  479. $engines[] = [
  480. 'name' => $name,
  481. 'id' => $car_id,
  482. 'url' => get_permalink( $car_id ),
  483. 'ac_gas_type' => $ac_gas_type,
  484. 'ac_gas_type_2' => $ac_gas_type_2,
  485. 'adapters' => $adapters,
  486. 'adapters_2' => $adapters_2,
  487. ];
  488. }
  489. // ── ACF repeater 'engines' – dodatkowe warianty silnika ──────────
  490. $extra_engines = get_field( 'engines', $car_id );
  491. if ( is_array( $extra_engines ) ) {
  492. foreach ( $extra_engines as $extra ) {
  493. $e_type = (string) ( $extra['engine_type'] ?? '' );
  494. $e_size_cc = (float) ( $extra['engine_size'] ?? 0 );
  495. $e_kw = (string) ( $extra['engine_power_kw'] ?? '' );
  496. $e_km = (string) ( $extra['engine_power_km'] ?? '' );
  497. $e_size = number_format( $e_size_cc / 1000, 1 );
  498. $e_name = "{$e_type} {$e_size} - {$e_kw} kW / {$e_km} KM";
  499. $e_gas = (string) ( $extra['ac_gas_type'] ?? $ac_gas_type );
  500. $e_gas_2 = (string) ( $extra['ac_gas_type_2'] ?? $ac_gas_type_2 );
  501. $e_adp_r = $extra['adapters'] ?? null;
  502. $e_adp_r2 = $extra['adapters_2'] ?? null;
  503. $e_adp = is_array( $e_adp_r ) ? implode( ',', $e_adp_r ) : (string) ( $e_adp_r ?: $adapters );
  504. $e_adp_2 = is_array( $e_adp_r2 ) ? implode( ',', $e_adp_r2 ) : (string) ( $e_adp_r2 ?: $adapters_2 );
  505. $e_key = mb_strtolower( $e_name );
  506. if ( ! isset( $seen[ $e_key ] ) ) {
  507. $seen[ $e_key ] = true;
  508. $engines[] = [
  509. 'name' => $e_name,
  510. 'id' => $car_id,
  511. 'url' => get_permalink( $car_id ),
  512. 'ac_gas_type' => $e_gas,
  513. 'ac_gas_type_2' => $e_gas_2,
  514. 'adapters' => $e_adp,
  515. 'adapters_2' => $e_adp_2,
  516. ];
  517. }
  518. }
  519. }
  520. }
  521. return $engines;
  522. }
  523. /**
  524. * Zwraca atrybuty produktu WC jako [ slug_atrybutu => [ slug_wartości, ... ] ].
  525. * Używane do sprawdzania pa_rg (typ gazu) i pa_ra (adapter).
  526. *
  527. * Implementacja wzorowana na aiac_get_product_attributes_as_str_arr() z aiac_chat_api.php:
  528. * – dla wariantów (variation): [ $attr_val ] (pojedyncza wartość ze zmiennej produktowej)
  529. * – dla pozostałych typów: $attr_obj->get_slugs()
  530. */
  531. function eksrelay_product_attributes( WC_Product $product ): array {
  532. $result = [];
  533. $attributes = $product->get_attributes();
  534. if ( $product->is_type( 'variation' ) ) {
  535. foreach ( $attributes as $attr_key => $attr_val ) {
  536. $result[ $attr_key ] = [ $attr_val ];
  537. }
  538. } else {
  539. foreach ( $attributes as $attr_key => $attr_obj ) {
  540. $result[ $attr_key ] = $attr_obj->get_slugs();
  541. }
  542. }
  543. return $result;
  544. }
  545. /**
  546. * Wyszukuje produkty WooCommerce po fragmencie nazwy (fulltext search).
  547. */
  548. function eksrelay_search_products_by_name( string $product_name ): array {
  549. add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'eksrelay_wc_query_like', 10, 2 );
  550. $products = wc_get_products( [
  551. 'status' => 'publish',
  552. 'limit' => -1,
  553. 'like' => $product_name,
  554. ] );
  555. remove_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'eksrelay_wc_query_like', 10 );
  556. return $products;
  557. }
  558. function eksrelay_wc_query_like( array $query, array $query_vars ): array {
  559. if ( ! empty( $query_vars['like'] ) ) {
  560. $query['s'] = esc_attr( $query_vars['like'] );
  561. }
  562. return $query;
  563. }
  564. /**
  565. * Usuwa znaki diakrytyczne z ciągu znaków.
  566. * Mapowanie identyczne z replace_ascii() w aiac_chat_api.php.
  567. */
  568. function eksrelay_replace_ascii( string $string ): string {
  569. $map = [
  570. 'Š' => 'S', 'š' => 's', 'ë' => 'e', 'Ë' => 'E',
  571. 'ä' => 'a', 'Ä' => 'A', 'ö' => 'o', 'Ö' => 'O',
  572. 'ü' => 'u', 'Ü' => 'U', 'ß' => 'ss',
  573. 'ó' => 'o', 'Ó' => 'O', 'ł' => 'l', 'Ł' => 'L',
  574. 'ń' => 'n', 'Ń' => 'N', 'ć' => 'c', 'Ć' => 'C',
  575. 'ę' => 'e', 'Ę' => 'E', 'ź' => 'z', 'Ź' => 'Z',
  576. 'ż' => 'z', 'Ż' => 'Z', 'á' => 'a', 'Á' => 'A',
  577. 'č' => 'c', 'Č' => 'C', 'ď' => 'd', 'Ď' => 'D',
  578. 'é' => 'e', 'É' => 'E', 'ě' => 'e', 'Ě' => 'E',
  579. 'í' => 'i', 'Í' => 'I', 'ň' => 'n', 'Ň' => 'N',
  580. 'ř' => 'r', 'Ř' => 'R', 'ś' => 's', 'Ś' => 'S',
  581. 'ť' => 't', 'Ť' => 'T', 'ů' => 'u', 'Ů' => 'U',
  582. 'ý' => 'y', 'Ý' => 'Y', 'ą' => 'a', 'Ą' => 'A',
  583. 'ș' => 's', 'Ș' => 'S', 'î' => 'i', 'Î' => 'I',
  584. 'â' => 'a', 'Â' => 'A', 'ț' => 't', 'Ț' => 'T',
  585. 'ğ' => 'g', 'Ğ' => 'G', 'İ' => 'I', 'ı' => 'i',
  586. 'ç' => 'c', 'Ç' => 'C',
  587. ];
  588. return str_replace( array_keys( $map ), array_values( $map ), $string );
  589. }