eksrelay_api.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. * GET /wp-json/eksrelay/v1/shipping-costs?zone_id=X&currency=EUR
  28. *
  29. * Returns shipping methods for a zone with costs in the requested currency.
  30. * WCML stores per-currency costs in wp_options under the key
  31. * woocommerce_{method_id}_{instance_id}_settings as cost_EUR, cost_CZK, etc.
  32. */
  33. register_rest_route( 'eksrelay/v1', '/shipping-costs', [
  34. 'methods' => 'GET',
  35. 'callback' => 'eksrelay_shipping_costs',
  36. 'permission_callback' => '__return_true',
  37. ] );
  38. register_rest_route( 'eksrelay/v1', '/shipping-eligibility', [
  39. 'methods' => 'POST',
  40. 'callback' => 'eksrelay_shipping_eligibility',
  41. 'permission_callback' => '__return_true',
  42. ] );
  43. } );
  44. // ═══════════════════════════════════════════════════════════════════
  45. // Handler: POST /wp-json/eksrelay/v1/car-data
  46. //
  47. // Body JSON: { car_year, car_brand?, car_model?, car_engine? }
  48. // ═══════════════════════════════════════════════════════════════════
  49. function eksrelay_car_data( WP_REST_Request $request ) {
  50. $body = $request->get_json_params() ?: [];
  51. if ( empty( $body['car_year'] ) ) {
  52. return [ 'error' => 'car_year jest wymagany' ];
  53. }
  54. $car_year = intval( sanitize_text_field( $body['car_year'] ) );
  55. $has_brand = ! empty( $body['car_brand'] );
  56. $has_model = ! empty( $body['car_model'] );
  57. $car_brand = false;
  58. $car_model = false;
  59. if ( ! $has_brand && ! $has_model ) {
  60. return [ 'error' => 'car_brand lub car_model jest wymagany' ];
  61. }
  62. // ── Tylko brand, bez modelu ──────────────────────────────────────
  63. if ( $has_brand && ! $has_model ) {
  64. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  65. $termIds = get_terms( [ 'name__like' => $car_brand, 'parent' => 0, 'fields' => 'ids' ] );
  66. if ( count( $termIds ) === 1 ) {
  67. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  68. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  69. }
  70. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  71. }
  72. // ── Tylko model, bez brandu ─────────────────────────────────────
  73. if ( $has_model && ! $has_brand ) {
  74. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  75. $termIds = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  76. // exact match → auto-wybierz
  77. foreach ( $termIds as $tid ) {
  78. $term = get_term_by( 'id', $tid, 'car_model' );
  79. if ( $term && eksrelay_replace_ascii( $term->name ) === $car_model ) {
  80. $termIds = [ $term->term_id ];
  81. break;
  82. }
  83. }
  84. if ( count( $termIds ) === 1 ) {
  85. $term = get_term( $termIds[0] );
  86. if ( ! is_wp_error( $term ) && $term->parent !== 0 ) {
  87. $parent = get_term( $term->parent );
  88. if ( ! is_wp_error( $parent ) ) {
  89. $car_brand = $parent->name;
  90. }
  91. } else {
  92. return [ 'error' => 'nie znaleziono takiego modelu', 'car_model' => $car_model ];
  93. }
  94. } else {
  95. $models = [];
  96. foreach ( $termIds as $tid ) {
  97. $t = get_term_by( 'id', $tid, 'car_model' );
  98. if ( $t ) {
  99. $models[] = $t->name;
  100. }
  101. }
  102. if ( $models ) {
  103. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $models, 'filtered' => true ];
  104. }
  105. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  106. }
  107. }
  108. // ── Mamy oba ────────────────────────────────────────────────────
  109. if ( ! $car_brand ) {
  110. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  111. }
  112. if ( ! $car_model ) {
  113. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  114. }
  115. $car_engine = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_engine'] ?? '' ) ) );
  116. $termIds = get_terms( [ 'name__like' => $car_brand, 'fields' => 'ids' ] );
  117. $termIds2 = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  118. if ( ! count( $termIds ) ) {
  119. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  120. }
  121. if ( ! count( $termIds2 ) ) {
  122. if ( count( $termIds ) === 1 ) {
  123. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  124. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  125. }
  126. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  127. }
  128. $query = new WP_Query( [
  129. 'post_type' => 'car',
  130. 'posts_per_page' => -1,
  131. 'tax_query' => [
  132. 'relation' => 'AND',
  133. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  134. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds2 ],
  135. [ 'taxonomy' => 'car_production_year', 'field' => 'slug', 'terms' => (string) $car_year ],
  136. ],
  137. ] );
  138. $cars = $query->get_posts();
  139. $engine_info = eksrelay_get_engines_info( $cars, true, $car_year );
  140. if ( ! $cars ) {
  141. return [
  142. 'error' => 'nie znaleziono auta, ' . get_option(
  143. 'aiac_tool_get_car_data_no_car',
  144. 'Orientacyjnie do 1994 roku włącznie powinien pasować gaz R12, dla aut 1995-2016 gaz R134A a dla aut od 2016 roku gaz R1234YF'
  145. ),
  146. 'car_brand' => $car_brand,
  147. 'car_model' => $car_model,
  148. ];
  149. }
  150. $engine_names = array_column( $engine_info, 'name' );
  151. if ( count( $engine_info ) === 1 ) {
  152. $car_engine = $engine_info[0]['name'];
  153. }
  154. if ( count( $engine_info ) > 1 && ! $car_engine ) {
  155. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  156. }
  157. foreach ( $engine_info as $eng ) {
  158. if ( strtolower( trim( $eng['name'] ) ) !== strtolower( trim( $car_engine ) ) ) {
  159. continue;
  160. }
  161. $car_id = intval( $eng['id'] );
  162. $maybe_diff = get_field( 'custom_ac', $car_id );
  163. $gas_types = array_unique( array_filter( [
  164. get_field( 'ac_gas_type', $car_id ),
  165. $maybe_diff ? get_field( 'ac_gas_type_2', $car_id ) : '',
  166. ] ) );
  167. $year_term = get_terms( [ 'taxonomy' => 'car_production_year', 'name__like' => $car_year ] );
  168. $brand_term = $termIds ? get_term( $termIds[0] ) : false;
  169. $model_term = $termIds2 ? get_term( $termIds2[0] ) : false;
  170. $data = [
  171. 'success' => true,
  172. 'selected_car' => [
  173. 'ek_ac_gas_type' => implode( ',', $gas_types ),
  174. 'ek_brand_id' => $termIds[0] ?? '',
  175. 'ek_brand' => ( $brand_term && ! is_wp_error( $brand_term ) ) ? $brand_term->name : $car_brand,
  176. 'ek_car_id' => $car_id,
  177. 'ek_engine_type' => $eng['name'],
  178. 'ek_info' => '',
  179. 'ek_model_id' => $termIds2[0] ?? '',
  180. 'ek_model' => ( $model_term && ! is_wp_error( $model_term ) ) ? $model_term->name : $car_model,
  181. 'ek_year_id' => ( ! is_wp_error( $year_term ) && $year_term ) ? $year_term[0]->term_id : '',
  182. 'ek_year' => $car_year,
  183. ],
  184. 'shop_url' => $eng['url'],
  185. 'adapters' => get_field( 'adapters', $car_id ) ?: false,
  186. 'ac_gas_type' => get_field( 'ac_gas_type', $car_id ),
  187. 'ac_gas_amount' => ( get_field( 'ac_gas_amount', $car_id ) ?: '-' ) . ' g',
  188. 'ac_ports_count' => intval( get_field( 'ac_ports_count', $car_id ) ),
  189. 'ac_oil' => get_field( 'ac_oil', $car_id ),
  190. 'ac_oil_amount' => ( get_field( 'ac_oil_amount', $car_id ) ?: '-' ) . ' cm3',
  191. 'ac_clutch' => get_field( 'ac_clutch', $car_id ),
  192. 'maybe_different_layout' => $maybe_diff,
  193. ];
  194. if ( $maybe_diff ) {
  195. $data['different_layout_info'] = get_field( 'custom_ac_info', $car_id ) ?: '';
  196. $data['different_layout_adapters'] = get_field( 'adapters_2', $car_id ) ?: false;
  197. $data['different_layout_ac_gas_type'] = get_field( 'ac_gas_type_2', $car_id );
  198. $data['different_layout_ac_gas_amount'] = ( get_field( 'ac_gas_amount_2', $car_id ) ?: '-' ) . ' g';
  199. $data['different_layout_ac_ports_count'] = get_field( 'ac_ports_count_2', $car_id );
  200. $data['different_layout_ac_oil'] = get_field( 'ac_oil_2', $car_id );
  201. $data['different_layout_ac_oil_amount'] = ( get_field( 'ac_oil_amount_2', $car_id ) ?: '-' ) . ' cm3';
  202. $data['different_layout_ac_clutch'] = get_field( 'ac_clutch_2', $car_id );
  203. }
  204. return $data;
  205. }
  206. // podany silnik nie pasuje do żadnego na liście → pokaż opcje
  207. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_names, 'filtered' => false ];
  208. }
  209. // ═══════════════════════════════════════════════════════════════════
  210. // Handler: POST /wp-json/eksrelay/v1/product-compatibility
  211. //
  212. // Body JSON: { car_year, car_brand?, car_model?, car_engine?, product_name? }
  213. // ═══════════════════════════════════════════════════════════════════
  214. function eksrelay_product_compatibility( WP_REST_Request $request ) {
  215. $body = $request->get_json_params() ?: [];
  216. if ( empty( $body['car_year'] ) ) {
  217. return [ 'error' => 'car_year jest wymagany' ];
  218. }
  219. $lang = sanitize_text_field( $body['lang'] ?? 'pl' );
  220. $currency = strtoupper( sanitize_text_field( $body['currency'] ?? 'PLN' ) );
  221. $car_year = intval( sanitize_text_field( $body['car_year'] ) );
  222. $has_brand = ! empty( $body['car_brand'] );
  223. $has_model = ! empty( $body['car_model'] );
  224. $car_brand = false;
  225. $car_model = false;
  226. // ── Tylko brand ─────────────────────────────────────────────────
  227. if ( $has_brand && ! $has_model ) {
  228. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  229. $termIds = get_terms( [ 'name__like' => $car_brand, 'parent' => 0, 'fields' => 'ids' ] );
  230. if ( count( $termIds ) === 1 ) {
  231. $car_models = eksrelay_models_for_brand_year( $termIds, $car_year );
  232. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $car_models, 'filtered' => false ];
  233. }
  234. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  235. }
  236. // ── Tylko model ─────────────────────────────────────────────────
  237. if ( $has_model && ! $has_brand ) {
  238. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  239. $termIds = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  240. if ( count( $termIds ) === 1 ) {
  241. $term = get_term( $termIds[0] );
  242. if ( ! is_wp_error( $term ) && $term->parent !== 0 ) {
  243. $parent = get_term( $term->parent );
  244. if ( ! is_wp_error( $parent ) ) {
  245. $car_brand = $parent->name;
  246. }
  247. } else {
  248. return [ 'error' => 'nie znaleziono takiego modelu', 'car_model' => $car_model ];
  249. }
  250. } else {
  251. $models = [];
  252. foreach ( $termIds as $tid ) {
  253. $t = get_term_by( 'id', $tid, 'car_model' );
  254. if ( $t ) {
  255. $models[] = $t->name;
  256. }
  257. }
  258. if ( $models ) {
  259. return [ 'error' => 'options', 'field' => 'car_model', 'options' => $models, 'filtered' => true ];
  260. }
  261. return [ 'error' => 'options', 'field' => 'car_brand', 'options' => eksrelay_all_brands(), 'filtered' => false ];
  262. }
  263. }
  264. if ( ! $has_brand && ! $has_model ) {
  265. return [ 'error' => 'car_brand lub car_model jest wymagany' ];
  266. }
  267. if ( ! $car_brand ) {
  268. $car_brand = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_brand'] ) ) );
  269. }
  270. if ( ! $car_model ) {
  271. $car_model = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_model'] ) ) );
  272. }
  273. $car_engine = eksrelay_replace_ascii( trim( sanitize_text_field( $body['car_engine'] ?? '' ) ) );
  274. $car_engine_index = isset( $body['car_engine_index'] ) ? intval( $body['car_engine_index'] ) : -1;
  275. $product_name = eksrelay_replace_ascii( trim( sanitize_text_field( $body['product_name'] ?? '' ) ) );
  276. $product_id = intval( $body['product_id'] ?? 0 );
  277. // ── Znajdź produkt ──────────────────────────────────────────────
  278. $product = false;
  279. if ( $product_id > 0 ) {
  280. $p = wc_get_product( $product_id );
  281. if ( $p && ! is_wp_error( $p ) ) {
  282. $product = $p;
  283. }
  284. } elseif ( $product_name ) {
  285. $products = eksrelay_search_products_by_name( $product_name );
  286. if ( count( $products ) > 1 ) {
  287. // exact match → auto-wybierz
  288. foreach ( $products as $p ) {
  289. if ( eksrelay_replace_ascii( strtolower( trim( $p->get_title() ) ) ) === strtolower( $product_name ) ) {
  290. $product = $p;
  291. break;
  292. }
  293. }
  294. if ( ! $product ) {
  295. return [
  296. 'error' => 'options',
  297. 'field' => 'product_name',
  298. 'options' => array_map( fn( $p ) => [ 'id' => $p->get_id(), 'title' => $p->get_title() ], $products ),
  299. 'filtered' => true,
  300. ];
  301. }
  302. } elseif ( count( $products ) === 1 ) {
  303. $product = $products[0];
  304. }
  305. }
  306. // ── Znajdź auto ─────────────────────────────────────────────────
  307. $termIds = get_terms( [ 'name__like' => $car_brand, 'fields' => 'ids' ] );
  308. $termIds2 = get_terms( [ 'name__like' => $car_model, 'fields' => 'ids' ] );
  309. // Uwaga: celowo bez filtra roku – engine_info filtruje rok wewnętrznie
  310. $query = new WP_Query( [
  311. 'post_type' => 'car',
  312. 'posts_per_page' => -1,
  313. 'tax_query' => [
  314. 'relation' => 'AND',
  315. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  316. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds2 ],
  317. ],
  318. ] );
  319. $cars = $query->get_posts();
  320. $engine_info = eksrelay_get_engines_info( $cars, false, $car_year );
  321. if ( ! $cars ) {
  322. return [ 'error' => 'nie znaleziono takiego samochodu', 'car_brand' => $car_brand, 'car_model' => $car_model ];
  323. }
  324. // If year filter returns nothing, fall back to all engines for this model (year=0 disables filter).
  325. // This handles cases where the user provides an approximate or incorrect year.
  326. if ( empty( $engine_info ) && $car_year ) {
  327. $engine_info = eksrelay_get_engines_info( $cars, false, 0 );
  328. }
  329. $engine_names = array_column( $engine_info, 'name' );
  330. if ( count( $engine_info ) === 1 ) {
  331. $car_engine = $engine_info[0]['name'];
  332. }
  333. if ( count( $engine_info ) > 1 && ! $car_engine && $car_engine_index < 0 ) {
  334. // Return options as {index, name} objects so the caller can select by numeric index,
  335. // avoiding string-matching issues (e.g. LLM stripping engine-type prefixes like "B ", "D ").
  336. $engine_options = array_map(
  337. fn( $i, $eng ) => [ 'index' => $i, 'name' => $eng['name'] ],
  338. array_keys( $engine_info ),
  339. array_values( $engine_info )
  340. );
  341. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_options, 'filtered' => false ];
  342. }
  343. foreach ( $engine_info as $idx => $eng ) {
  344. // Prefer index-based selection (unambiguous) over name-based (fragile string match).
  345. if ( $car_engine_index >= 0 ) {
  346. if ( $idx !== $car_engine_index ) continue;
  347. } else {
  348. if ( strtolower( trim( $eng['name'] ) ) !== strtolower( trim( $car_engine ) ) ) continue;
  349. }
  350. $engine_gas = array_values( array_filter( [ $eng['ac_gas_type'] ?? '', $eng['ac_gas_type_2'] ?? '' ] ) );
  351. $engine_adapters = array_values( array_filter( [ $eng['adapters'] ?? '', $eng['adapters_2'] ?? '' ] ) );
  352. if ( ! $engine_gas ) $engine_gas = [ 'no-gas' ];
  353. if ( ! $engine_adapters ) $engine_adapters = [ 'no' ];
  354. if ( $product ) {
  355. // ── Sprawdzenie kompatybilności konkretnego produktu ─────────
  356. $attributes = eksrelay_product_attributes( $product );
  357. foreach ( $attributes as $k => $arr ) {
  358. $attributes[ $k ] = array_map( fn( $slug ) => str_replace( "-{$lang}", '', $slug ), $arr );
  359. }
  360. if ( ! isset( $attributes['pa_rg'] ) || empty( $attributes['pa_rg'] ) ) $attributes['pa_rg'] = [ 'no-gas' ];
  361. if ( ! isset( $attributes['pa_ra'] ) || empty( $attributes['pa_ra'] ) ) $attributes['pa_ra'] = [ 'no' ];
  362. $gas_fit = count( array_intersect( $engine_gas, $attributes['pa_rg'] ) ) > 0;
  363. $adapter_fit = count( array_intersect( $engine_adapters, $attributes['pa_ra'] ) ) > 0;
  364. return [
  365. 'success' => true,
  366. 'fit' => $gas_fit && $adapter_fit,
  367. 'gas_fit' => $gas_fit,
  368. 'adapter_fit' => $adapter_fit,
  369. 'selected_engine' => $eng,
  370. 'selected_product' => [
  371. 'id' => $product->get_id(),
  372. 'title' => $product->get_title(),
  373. 'type' => $product->get_type(),
  374. 'attributes' => $attributes,
  375. ],
  376. ];
  377. }
  378. // ── Brak konkretnego produktu – lista wszystkich kompatybilnych ─
  379. // Switch WPML language so product titles and WCML prices are returned
  380. // in the requested language/currency. Restored in finally block below.
  381. if ( $lang && $lang !== 'pl' ) {
  382. do_action( 'wpml_switch_language', $lang );
  383. }
  384. try {
  385. $all_products = wc_get_products( [
  386. 'status' => 'publish',
  387. 'visibility' => 'visible',
  388. 'limit' => -1,
  389. 'orderby' => 'name',
  390. ] );
  391. $compatible = [];
  392. foreach ( $all_products as $p ) {
  393. $attrs = eksrelay_product_attributes( $p );
  394. foreach ( $attrs as $k => $arr ) {
  395. $attrs[ $k ] = array_map( fn( $slug ) => str_replace( "-{$lang}", '', $slug ), $arr );
  396. }
  397. $p_gas = ( isset( $attrs['pa_rg'] ) && ! empty( $attrs['pa_rg'] ) ) ? $attrs['pa_rg'] : [ 'no-gas' ];
  398. $p_adapters = ( isset( $attrs['pa_ra'] ) && ! empty( $attrs['pa_ra'] ) ) ? $attrs['pa_ra'] : [ 'no' ];
  399. if (
  400. count( array_intersect( $engine_gas, $p_gas ) ) > 0 &&
  401. count( array_intersect( $engine_adapters, $p_adapters ) ) > 0
  402. ) {
  403. $compatible[] = [
  404. 'id' => $p->get_id(),
  405. 'title' => $p->get_title(),
  406. 'price' => $p->get_price(),
  407. 'permalink' => get_permalink( $p->get_id() ),
  408. ];
  409. }
  410. }
  411. } finally {
  412. if ( $lang && $lang !== 'pl' ) {
  413. do_action( 'wpml_switch_language', null );
  414. }
  415. }
  416. return [
  417. 'success' => true,
  418. 'compatible_products' => $compatible,
  419. 'selected_engine' => $eng,
  420. ];
  421. }
  422. // No engine matched — return options again so user can pick
  423. $engine_options = array_map(
  424. fn( $i, $eng ) => [ 'index' => $i, 'name' => $eng['name'] ],
  425. array_keys( $engine_info ),
  426. array_values( $engine_info )
  427. );
  428. return [ 'error' => 'options', 'field' => 'car_engine', 'options' => $engine_options, 'filtered' => false ];
  429. }
  430. // ═══════════════════════════════════════════════════════════════════
  431. // Pomocnicze funkcje wewnętrzne
  432. // ═══════════════════════════════════════════════════════════════════
  433. /**
  434. * Zwraca listę modeli dla danej marki (termIds) i roku produkcji.
  435. */
  436. function eksrelay_models_for_brand_year( array $termIds, int $car_year ): array {
  437. $query = new WP_Query( [
  438. 'post_type' => 'car',
  439. 'posts_per_page' => -1,
  440. 'tax_query' => [
  441. 'relation' => 'AND',
  442. [ 'taxonomy' => 'car_model', 'field' => 'id', 'terms' => $termIds ],
  443. [ 'taxonomy' => 'car_production_year', 'field' => 'slug', 'terms' => [ (string) $car_year ] ],
  444. ],
  445. ] );
  446. $car_models = [];
  447. foreach ( $query->get_posts() as $car ) {
  448. foreach ( wp_get_post_terms( $car->ID, 'car_model' ) as $term ) {
  449. if ( ! in_array( $term->name, $car_models, true ) && $term->parent !== 0 ) {
  450. $car_models[] = $term->name;
  451. }
  452. }
  453. }
  454. return $car_models;
  455. }
  456. /**
  457. * Zwraca listę wszystkich marek aut (terminy car_model z parent=0).
  458. */
  459. function eksrelay_all_brands(): array {
  460. return (array) get_terms( [
  461. 'taxonomy' => 'car_model',
  462. 'parent' => 0,
  463. 'fields' => 'names',
  464. 'hide_empty' => true,
  465. ] );
  466. }
  467. /**
  468. * Zwraca info o silnikach dla podanych postów 'car'.
  469. *
  470. * Parametr $prefiltered:
  471. * true – WP_Query już przefiltrował po roku przez taxonomy (get_car_data)
  472. * false – rok musi być sprawdzony wewnętrznie przez pola ACF year_from / year_to (get_product_compatibility)
  473. *
  474. * Nazwa silnika jest budowana z pól ACF: engine_type, engine_size (ccm), engine_power_kw, engine_power_km.
  475. * Format: "B 1.8 - 141 kW / 192 KM"
  476. *
  477. * Zakres roku pochodzi z pól ACF year_from / year_to (przechowywane jako term_id taksonomii car_production_year).
  478. *
  479. * Dodatkowe warianty silnika mogą być przechowywane w ACF repeaterze 'engines' na poście car.
  480. */
  481. function eksrelay_get_engines_info( array $cars, bool $prefiltered, int $car_year ): array {
  482. $engines = [];
  483. $seen = [];
  484. foreach ( $cars as $car ) {
  485. $car_id = $car->ID;
  486. // ── Filtrowanie zakresu roku przez pola ACF year_from / year_to ─
  487. if ( $car_year ) {
  488. $year_from_id = get_field( 'year_from', $car_id );
  489. $year_to_id = get_field( 'year_to', $car_id );
  490. $year_from = 0;
  491. $year_to = 9999;
  492. if ( $year_from_id ) {
  493. $t = get_term( (int) $year_from_id, 'car_production_year' );
  494. if ( $t && ! is_wp_error( $t ) ) {
  495. $year_from = (int) $t->slug;
  496. }
  497. }
  498. if ( $year_to_id ) {
  499. $t = get_term( (int) $year_to_id, 'car_production_year' );
  500. if ( $t && ! is_wp_error( $t ) ) {
  501. $year_to = (int) $t->slug;
  502. }
  503. }
  504. if ( $car_year < $year_from || $car_year > $year_to ) {
  505. continue;
  506. }
  507. }
  508. // ── Budowanie nazwy silnika z pól ACF ────────────────────────────
  509. $engine_type = (string) ( get_field( 'engine_type', $car_id ) ?: '' );
  510. $engine_size_cc = (float) ( get_field( 'engine_size', $car_id ) ?: 0 );
  511. $power_kw = (string) ( get_field( 'engine_power_kw', $car_id ) ?: '' );
  512. $power_km = (string) ( get_field( 'engine_power_km', $car_id ) ?: '' );
  513. $engine_size = number_format( $engine_size_cc / 1000, 1 );
  514. $name = "{$engine_type} {$engine_size} - {$power_kw} kW / {$power_km} KM";
  515. // ── Typ gazu i adaptery ──────────────────────────────────────────
  516. $ac_gas_type = (string) ( get_field( 'ac_gas_type', $car_id ) ?: '' );
  517. $ac_gas_type_2 = (string) ( get_field( 'ac_gas_type_2', $car_id ) ?: '' );
  518. $adapters_raw = get_field( 'adapters', $car_id );
  519. $adapters_raw2 = get_field( 'adapters_2', $car_id );
  520. $adapters = is_array( $adapters_raw ) ? ( implode( ',', $adapters_raw ) ?: 'no' ) : (string) ( $adapters_raw ?: 'no' );
  521. $adapters_2 = is_array( $adapters_raw2 ) ? implode( ',', $adapters_raw2 ) : (string) ( $adapters_raw2 ?: '' );
  522. // ── Korekty gazu na podstawie roku (sanity check) ────────────────
  523. if ( $car_year ) {
  524. if ( $car_year <= 1994 && $ac_gas_type === '' ) {
  525. $ac_gas_type = 'r12';
  526. } elseif ( $car_year >= 2017 && $ac_gas_type === '' ) {
  527. $ac_gas_type = 'r1234yf';
  528. } elseif ( $car_year >= 1995 && $car_year <= 2016 && $ac_gas_type === '' ) {
  529. $ac_gas_type = 'r134a';
  530. }
  531. }
  532. // ── Główny silnik ────────────────────────────────────────────────
  533. $key = mb_strtolower( $name );
  534. if ( ! isset( $seen[ $key ] ) ) {
  535. $seen[ $key ] = true;
  536. $engines[] = [
  537. 'name' => $name,
  538. 'id' => $car_id,
  539. 'url' => get_permalink( $car_id ),
  540. 'ac_gas_type' => $ac_gas_type,
  541. 'ac_gas_type_2' => $ac_gas_type_2,
  542. 'adapters' => $adapters,
  543. 'adapters_2' => $adapters_2,
  544. ];
  545. }
  546. // ── ACF repeater 'engines' – dodatkowe warianty silnika ──────────
  547. $extra_engines = get_field( 'engines', $car_id );
  548. if ( is_array( $extra_engines ) ) {
  549. foreach ( $extra_engines as $extra ) {
  550. $e_type = (string) ( $extra['engine_type'] ?? '' );
  551. $e_size_cc = (float) ( $extra['engine_size'] ?? 0 );
  552. $e_kw = (string) ( $extra['engine_power_kw'] ?? '' );
  553. $e_km = (string) ( $extra['engine_power_km'] ?? '' );
  554. $e_size = number_format( $e_size_cc / 1000, 1 );
  555. $e_name = "{$e_type} {$e_size} - {$e_kw} kW / {$e_km} KM";
  556. $e_gas = (string) ( $extra['ac_gas_type'] ?? $ac_gas_type );
  557. $e_gas_2 = (string) ( $extra['ac_gas_type_2'] ?? $ac_gas_type_2 );
  558. $e_adp_r = $extra['adapters'] ?? null;
  559. $e_adp_r2 = $extra['adapters_2'] ?? null;
  560. $e_adp = is_array( $e_adp_r ) ? implode( ',', $e_adp_r ) : (string) ( $e_adp_r ?: $adapters );
  561. $e_adp_2 = is_array( $e_adp_r2 ) ? implode( ',', $e_adp_r2 ) : (string) ( $e_adp_r2 ?: $adapters_2 );
  562. $e_key = mb_strtolower( $e_name );
  563. if ( ! isset( $seen[ $e_key ] ) ) {
  564. $seen[ $e_key ] = true;
  565. $engines[] = [
  566. 'name' => $e_name,
  567. 'id' => $car_id,
  568. 'url' => get_permalink( $car_id ),
  569. 'ac_gas_type' => $e_gas,
  570. 'ac_gas_type_2' => $e_gas_2,
  571. 'adapters' => $e_adp,
  572. 'adapters_2' => $e_adp_2,
  573. ];
  574. }
  575. }
  576. }
  577. }
  578. return $engines;
  579. }
  580. /**
  581. * Zwraca atrybuty produktu WC jako [ slug_atrybutu => [ slug_wartości, ... ] ].
  582. * Używane do sprawdzania pa_rg (typ gazu) i pa_ra (adapter).
  583. *
  584. * Implementacja wzorowana na aiac_get_product_attributes_as_str_arr() z aiac_chat_api.php:
  585. * – dla wariantów (variation): [ $attr_val ] (pojedyncza wartość ze zmiennej produktowej)
  586. * – dla pozostałych typów: $attr_obj->get_slugs()
  587. */
  588. function eksrelay_product_attributes( WC_Product $product ): array {
  589. $result = [];
  590. $attributes = $product->get_attributes();
  591. if ( $product->is_type( 'variation' ) ) {
  592. foreach ( $attributes as $attr_key => $attr_val ) {
  593. $result[ $attr_key ] = [ $attr_val ];
  594. }
  595. } else {
  596. foreach ( $attributes as $attr_key => $attr_obj ) {
  597. $result[ $attr_key ] = $attr_obj->get_slugs();
  598. }
  599. }
  600. return $result;
  601. }
  602. /**
  603. * Wyszukuje produkty WooCommerce po fragmencie nazwy (fulltext search).
  604. */
  605. function eksrelay_search_products_by_name( string $product_name ): array {
  606. add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'eksrelay_wc_query_like', 10, 2 );
  607. $products = wc_get_products( [
  608. 'status' => 'publish',
  609. 'limit' => -1,
  610. 'like' => $product_name,
  611. ] );
  612. remove_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'eksrelay_wc_query_like', 10 );
  613. return $products;
  614. }
  615. function eksrelay_wc_query_like( array $query, array $query_vars ): array {
  616. if ( ! empty( $query_vars['like'] ) ) {
  617. $query['s'] = esc_attr( $query_vars['like'] );
  618. }
  619. return $query;
  620. }
  621. // ═══════════════════════════════════════════════════════════════════
  622. // Handler: GET /wp-json/eksrelay/v1/shipping-costs?zone_id=X&currency=EUR
  623. //
  624. // Returns shipping methods for a zone with costs in the requested currency.
  625. // WCML stores per-currency costs in wp_options:
  626. // woocommerce_{method_id}_{instance_id}_settings → cost_EUR, cost_CZK, etc.
  627. // ═══════════════════════════════════════════════════════════════════
  628. function eksrelay_shipping_eligibility( WP_REST_Request $request ) {
  629. $body = $request->get_json_params() ?: [];
  630. $country = strtoupper( sanitize_text_field( $body['country'] ?? $request->get_param( 'country' ) ?? '' ) );
  631. $postcode = strtoupper( preg_replace( '/\s+/', '', sanitize_text_field( $body['postcode'] ?? $body['postalCode'] ?? $body['postal_code'] ?? $request->get_param( 'postcode' ) ?? '' ) ) );
  632. if ( $country === '' || $postcode === '' ) {
  633. return new WP_Error( 'eksrelay_missing_params', 'country and postcode are required', [ 'status' => 400 ] );
  634. }
  635. $blocked = false;
  636. $matched = null;
  637. $source = 'aiac_disable_dpd_using_postcode';
  638. if ( function_exists( 'aiac_get_blocked_postcodes' ) && function_exists( 'aiac_is_postcode_blocked_for_dpd' ) ) {
  639. $rules = aiac_get_blocked_postcodes();
  640. $patterns = is_array( $rules ) && isset( $rules[ $country ] ) && is_array( $rules[ $country ] ) ? $rules[ $country ] : [];
  641. foreach ( $patterns as $pattern ) {
  642. if ( aiac_is_postcode_blocked_for_dpd( $postcode, [ $pattern ] ) ) {
  643. $blocked = true;
  644. $matched = (string) $pattern;
  645. break;
  646. }
  647. }
  648. } else {
  649. $source = 'fallback_es_ranges';
  650. $fallback = [
  651. 'ES' => [ '35000-35999', '38001-38999', '51001-51015', '52001-52006' ],
  652. ];
  653. foreach ( $fallback[ $country ] ?? [] as $pattern ) {
  654. if ( eksrelay_postcode_matches_pattern( $postcode, $pattern ) ) {
  655. $blocked = true;
  656. $matched = $pattern;
  657. break;
  658. }
  659. }
  660. }
  661. return [
  662. 'ok' => true,
  663. 'eligible' => ! $blocked,
  664. 'country' => $country,
  665. 'postcode' => $postcode,
  666. 'reason_code' => $blocked ? 'blocked_postcode' : 'eligible',
  667. 'reason' => $blocked ? 'Nie wysyłamy do tego regionu/kodu pocztowego.' : 'Brak blokady dla tego kodu pocztowego w regułach sklepu.',
  668. 'matched_rule' => $matched,
  669. 'source' => $source,
  670. ];
  671. }
  672. function eksrelay_postcode_matches_pattern( $postcode, $pattern ) {
  673. $postcode_digits = preg_replace( '/\D/', '', (string) $postcode );
  674. $pattern = strtoupper( preg_replace( '/\s+/', '', (string) $pattern ) );
  675. if ( strpos( $pattern, '-' ) !== false ) {
  676. list( $from, $to ) = array_map( 'trim', explode( '-', $pattern, 2 ) );
  677. if ( ctype_digit( $from ) && ctype_digit( $to ) && $postcode_digits !== '' ) {
  678. $pc_int = (int) $postcode_digits;
  679. return $pc_int >= (int) $from && $pc_int <= (int) $to;
  680. }
  681. }
  682. if ( substr( $pattern, -1 ) === '*' ) {
  683. return strpos( strtoupper( (string) $postcode ), rtrim( $pattern, '*' ) ) === 0;
  684. }
  685. return strtoupper( (string) $postcode ) === $pattern || $postcode_digits === preg_replace( '/\D/', '', $pattern );
  686. }
  687. function eksrelay_shipping_costs( WP_REST_Request $request ) {
  688. $zone_id = intval( $request->get_param( 'zone_id' ) );
  689. $currency = strtoupper( sanitize_text_field( $request->get_param( 'currency' ) ?: 'PLN' ) );
  690. $zone = new WC_Shipping_Zone( $zone_id );
  691. $methods = $zone->get_shipping_methods( true ); // true = enabled only
  692. $result = [];
  693. foreach ( $methods as $method ) {
  694. $instance_id = $method->instance_id;
  695. $method_id = $method->id; // e.g. 'flat_rate', 'free_shipping'
  696. // WCML stores per-currency costs in wp_options
  697. $option_key = "woocommerce_{$method_id}_{$instance_id}_settings";
  698. $settings = get_option( $option_key, [] );
  699. // Base cost is the default (PLN) cost
  700. $base_cost = $settings['cost'] ?? '0';
  701. $cost_key = "cost_{$currency}";
  702. if ( $currency !== 'PLN' && isset( $settings[ $cost_key ] ) && $settings[ $cost_key ] !== '' ) {
  703. $cost = $settings[ $cost_key ];
  704. $cost_currency = $currency;
  705. } else {
  706. $cost = $base_cost;
  707. $cost_currency = 'PLN';
  708. }
  709. $result[] = [
  710. 'instance_id' => $instance_id,
  711. 'method_id' => $method_id,
  712. 'title' => $method->get_title(),
  713. 'cost' => $cost,
  714. 'cost_currency' => $cost_currency,
  715. ];
  716. }
  717. return [
  718. 'zone_id' => $zone_id,
  719. 'currency' => $currency,
  720. 'methods' => $result,
  721. ];
  722. }
  723. /**
  724. * Usuwa znaki diakrytyczne z ciągu znaków.
  725. * Mapowanie identyczne z replace_ascii() w aiac_chat_api.php.
  726. */
  727. function eksrelay_replace_ascii( string $string ): string {
  728. $map = [
  729. 'Š' => 'S', 'š' => 's', 'ë' => 'e', 'Ë' => 'E',
  730. 'ä' => 'a', 'Ä' => 'A', 'ö' => 'o', 'Ö' => 'O',
  731. 'ü' => 'u', 'Ü' => 'U', 'ß' => 'ss',
  732. 'ó' => 'o', 'Ó' => 'O', 'ł' => 'l', 'Ł' => 'L',
  733. 'ń' => 'n', 'Ń' => 'N', 'ć' => 'c', 'Ć' => 'C',
  734. 'ę' => 'e', 'Ę' => 'E', 'ź' => 'z', 'Ź' => 'Z',
  735. 'ż' => 'z', 'Ż' => 'Z', 'á' => 'a', 'Á' => 'A',
  736. 'č' => 'c', 'Č' => 'C', 'ď' => 'd', 'Ď' => 'D',
  737. 'é' => 'e', 'É' => 'E', 'ě' => 'e', 'Ě' => 'E',
  738. 'í' => 'i', 'Í' => 'I', 'ň' => 'n', 'Ň' => 'N',
  739. 'ř' => 'r', 'Ř' => 'R', 'ś' => 's', 'Ś' => 'S',
  740. 'ť' => 't', 'Ť' => 'T', 'ů' => 'u', 'Ů' => 'U',
  741. 'ý' => 'y', 'Ý' => 'Y', 'ą' => 'a', 'Ą' => 'A',
  742. 'ș' => 's', 'Ș' => 'S', 'î' => 'i', 'Î' => 'I',
  743. 'â' => 'a', 'Â' => 'A', 'ț' => 't', 'Ț' => 'T',
  744. 'ğ' => 'g', 'Ğ' => 'G', 'İ' => 'I', 'ı' => 'i',
  745. 'ç' => 'c', 'Ç' => 'C',
  746. ];
  747. return str_replace( array_keys( $map ), array_values( $map ), $string );
  748. }