PluginProbe
SuperFrete / 3.3.2
SuperFrete v3.3.2
trunk 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 3.2.1 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4
superfrete / app / App.php

App.php in SuperFrete 3.3.2, at app/App.php

737 lines 31.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace SuperFrete_API;
4
5 use SuperFrete_API\Helpers\Logger;
6
7 if (!defined('ABSPATH')) {
8 exit; // Segurança para evitar acesso direto
9 }
10
11 class App
12 {
13
14 /**
15 * Construtor que inicializa o plugin
16 */
17 public function __construct()
18 {
19 $this->includes();
20 add_action('plugins_loaded', [$this, 'init_plugin']);
21 $this->register_ajax_actions();
22 add_action('woocommerce_shipping_init', function () {
23 if (class_exists('WC_Shipping_Method')) {
24 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteBase.php';
25 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFretePAC.php';
26 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteSEDEX.php';
27 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteMiniEnvio.php';
28 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteJadlog.php';
29 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteLoggi.php';
30 }
31 });
32
33 add_filter('woocommerce_shipping_methods', function ($methods) {
34 // Register all individual shipping methods
35 $methods['superfrete_pac'] = '\SuperFrete_API\Shipping\SuperFretePAC';
36 $methods['superfrete_sedex'] = '\SuperFrete_API\Shipping\SuperFreteSEDEX';
37 $methods['superfrete_mini_envio'] = '\SuperFrete_API\Shipping\SuperFreteMiniEnvios';
38 $methods['superfrete_jadlog'] = '\SuperFrete_API\Shipping\SuperFreteJadlog';
39 $methods['superfrete_loggi'] = '\SuperFrete_API\Shipping\SuperFreteLoggi';
40
41 // Remove the consolidated method if it exists
42 unset($methods['superfrete_shipping']);
43
44 return $methods;
45 });
46
47
48 }
49
50 /**
51 * Inclui os arquivos necessários do plugin
52 */
53 private function includes()
54 {
55 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_Settings.php';
56 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/Admin_Menu.php';
57 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/WebhookAdmin.php';
58 require_once plugin_dir_path(__FILE__) . '../api/Http/Request.php';
59 require_once plugin_dir_path(__FILE__) . '../api/Http/WebhookVerifier.php';
60 require_once plugin_dir_path(__FILE__) . '../api/Helpers/Logger.php';
61 require_once plugin_dir_path(__FILE__) . 'Controllers/ProductShipping.php';
62 require_once plugin_dir_path(__FILE__) . 'Controllers/SuperFrete_Order.php';
63 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_OrderActions.php';
64 require_once plugin_dir_path(__FILE__) . 'Controllers/WebhookController.php';
65 require_once plugin_dir_path(__FILE__) . 'Controllers/WebhookRetryManager.php';
66 require_once plugin_dir_path(__FILE__) . 'Controllers/OAuthController.php';
67 require_once plugin_dir_path(__FILE__) . 'Controllers/DocumentFields.php';
68 require_once plugin_dir_path(__FILE__) . 'Controllers/CheckoutFields.php';
69 require_once plugin_dir_path(__FILE__) . 'Helpers/AddressHelper.php';
70 require_once plugin_dir_path(__FILE__) . 'Helpers/ShippingMigration.php';
71 require_once plugin_dir_path(__FILE__) . 'Helpers/SuperFrete_Notice.php';
72
73 // Include database migrations if file exists
74 $migrations_file = plugin_dir_path(__FILE__) . '../database/webhook_migrations.php';
75 if (file_exists($migrations_file)) {
76 require_once $migrations_file;
77 }
78 }
79
80 /**
81 * Inicializa o plugin e adiciona suas funcionalidades
82 */
83 public function init_plugin()
84 {
85
86 new \SuperFrete_API\Admin\SuperFrete_OrderActions();
87 new \SuperFrete_API\Admin\SuperFrete_Settings();
88 new \SuperFrete_API\Admin\WebhookAdmin();
89 new \SuperFrete_API\Controllers\ProductShipping();
90 if (class_exists('\SuperFrete_API\Admin\Admin_Menu')) {
91 new \SuperFrete_API\Admin\Admin_Menu();
92 }
93 new \SuperFrete_API\Controllers\SuperFrete_Order();
94 new \SuperFrete_API\Controllers\WebhookController();
95 new \SuperFrete_API\Controllers\WebhookRetryManager();
96 new \SuperFrete_API\Controllers\OAuthController();
97 \SuperFrete_API\Helpers\Logger::init();
98
99 // Initialize webhook database tables (if class exists)
100 if (class_exists('\SuperFrete_API\Database\WebhookMigrations')) {
101 \SuperFrete_API\Database\WebhookMigrations::run_migrations();
102 }
103
104 add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
105 add_action('wp', function () {
106 if (!wp_next_scheduled('superfrete_clear_log_event')) {
107 wp_schedule_event(time(), 'every_five_days', 'superfrete_clear_log_event');
108 }
109 });
110 add_filter('woocommerce_package_rates', [$this, 'ordenar_metodos_frete_por_preco'], 100, 2);
111
112 // Also try hooking at an even later stage to ensure our sorting is final
113 add_filter('woocommerce_shipping_package_rates', [$this, 'ordenar_metodos_frete_por_preco'], 999, 2);
114
115 // Adiciona os campos 'Número' e 'Bairro' nas configurações da loja
116 add_filter('woocommerce_general_settings', [$this, 'add_custom_store_address_fields']);
117
118 add_filter('cron_schedules', function ($schedules) {
119 $schedules['every_five_days'] = [
120 'interval' => 5 * DAY_IN_SECONDS,
121 'display' => __('A cada 5 dias')
122 ];
123 return $schedules;
124 });
125
126 if (!empty(get_option('woocommerce_store_postcode')) && (!empty(get_option('superfrete_api_token')) || (get_option('superfrete_sandbox_mode') === 'yes' && !empty(get_option('superfrete_api_token_sandbox'))))) {
127 new \SuperFrete_API\Controllers\ProductShipping();
128 } else {
129 add_action('admin_notices', [$this, 'superfrete_configs_setup_notice']);
130 }
131 add_action('superfrete_clear_log_event', function () {
132 \SuperFrete_API\Helpers\Logger::clear_log();
133 // Also cleanup old webhook logs (if class exists)
134 if (class_exists('\SuperFrete_API\Database\WebhookMigrations')) {
135 \SuperFrete_API\Database\WebhookMigrations::cleanup_old_logs();
136 }
137 // Clear old shipping cache entries
138 if (class_exists('\SuperFrete_API\Shipping\SuperFreteBase')) {
139 \SuperFrete_API\Shipping\SuperFreteBase::clear_cache();
140 }
141 });
142
143 // Register custom order statuses
144 add_action('init', [$this, 'register_custom_order_statuses']);
145
146 // Run migration and create shipping zone after shipping methods are registered
147 add_action('wp_loaded', function () {
148 // Make sure WooCommerce is loaded
149 if (!class_exists('WooCommerce') || !class_exists('WC_Shipping_Zones')) {
150 return;
151 }
152 // Check if we need to force migration due to plugin update
153 $current_version = get_option('superfrete_plugin_version', '0.0.0');
154 $plugin_file = plugin_dir_path(__FILE__) . '../superfrete.php';
155
156 if (file_exists($plugin_file)) {
157 if (!function_exists('get_plugin_data')) {
158 require_once ABSPATH . 'wp-admin/includes/plugin.php';
159 }
160 $plugin_data = get_plugin_data($plugin_file);
161 $new_version = $plugin_data['Version'] ?? '1.0.0';
162
163 // If version changed, reset migration to force re-run
164 if (version_compare($current_version, $new_version, '<')) {
165 delete_option('superfrete_shipping_migrated');
166 delete_option('superfrete_individual_methods_migrated'); // New migration flag
167 update_option('superfrete_plugin_version', $new_version);
168 Logger::log('SuperFrete', "Plugin updated from $current_version to $new_version - forcing migration");
169 }
170
171 // Force migration for individual methods (version 3.2.0+)
172 if (version_compare($current_version, '3.2.0', '<') && version_compare($new_version, '3.2.0', '>=')) {
173 delete_option('superfrete_shipping_migrated');
174 delete_option('superfrete_individual_methods_migrated');
175 Logger::log('SuperFrete', "Forcing migration to individual shipping methods (v3.2.0)");
176 }
177 }
178
179 // Delay migration to ensure shipping methods are registered
180 // Only run migration once per request to avoid loops
181 if (!get_transient('superfrete_migration_running')) {
182 set_transient('superfrete_migration_running', true, 30); // 30 second lock
183 \SuperFrete_API\Helpers\ShippingMigration::migrate_shipping_methods();
184 delete_transient('superfrete_migration_running');
185 }
186 if (!class_exists('\WC_Shipping_Zones')) return;
187
188 $zone_name = 'Brasil - SuperFrete';
189 $existing_zones = \WC_Shipping_Zones::get_zones();
190
191 foreach ($existing_zones as $zone) {
192 if ($zone['zone_name'] === $zone_name) return;
193 }
194
195 $zone = new \WC_Shipping_Zone();
196 $zone->set_zone_name($zone_name);
197 $zone->save();
198
199 $zone_id = $zone->get_id();
200 $locations = [
201 ['code' => 'BR', 'type' => 'country'],
202 ];
203
204 global $wpdb;
205 foreach ($locations as $location) {
206 $wpdb->insert("{$wpdb->prefix}woocommerce_zone_locations", [
207 'zone_id' => $zone_id,
208 'location_code' => $location['code'],
209 'location_type' => $location['type'],
210 ]);
211 }
212 // Add all individual SuperFrete methods
213 $method_ids = ['superfrete_pac', 'superfrete_sedex', 'superfrete_jadlog', 'superfrete_mini_envio', 'superfrete_loggi'];
214
215 // Check if the shipping methods are registered
216 $wc_shipping = \WC_Shipping::instance();
217 $available_methods = $wc_shipping->get_shipping_methods();
218
219 foreach ($method_ids as $method_id) {
220 if (isset($available_methods[$method_id])) {
221 $instance_id = $zone->add_shipping_method($method_id);
222
223 // Get the method instance and enable it
224 $methods = $zone->get_shipping_methods();
225 foreach ($methods as $method) {
226 if ($method->id === $method_id && $method->get_instance_id() == $instance_id) {
227 $method->enabled = 'yes';
228 $method->update_option('enabled', 'yes');
229 $method->update_option('title', $method->method_title);
230 $method->save();
231 error_log("�
232 SuperFrete shipping method $method_id enabled in zone (Instance ID: $instance_id)");
233 break;
234 }
235 }
236 } else {
237 error_log(" SuperFrete shipping method $method_id not registered yet");
238 }
239 }
240
241 error_log('�
242 Zona de entrega "Brasil - SuperFrete" criada com o método ativado.');
243 });
244 }
245
246 public function ordenar_metodos_frete_por_preco($rates, $package)
247 {
248 if (empty($rates))
249 return $rates;
250
251 // Log original order for debugging
252 $original_order = [];
253 foreach ($rates as $rate_id => $rate) {
254 $original_order[] = $rate->label . ' - R$ ' . number_format(floatval($rate->cost), 2, ',', '.');
255 }
256 error_log('SuperFrete: Original shipping order: ' . implode(' | ', $original_order));
257
258 // Reordena os métodos de frete pelo valor (crescente - do menor para o maior)
259 uasort($rates, function ($a, $b) {
260 $cost_a = floatval($a->cost);
261 $cost_b = floatval($b->cost);
262
263 // Free shipping (cost = 0) should come first
264 if ($cost_a == 0 && $cost_b > 0) return -1;
265 if ($cost_b == 0 && $cost_a > 0) return 1;
266
267 // Both free or both paid - sort by cost ascending
268 if ($cost_a == $cost_b) {
269 // If costs are equal, sort by delivery time (faster first)
270 $time_a = isset($a->meta_data['delivery_time']) ? intval($a->meta_data['delivery_time']) : 999;
271 $time_b = isset($b->meta_data['delivery_time']) ? intval($b->meta_data['delivery_time']) : 999;
272 return $time_a <=> $time_b;
273 }
274
275 return $cost_a <=> $cost_b;
276 });
277
278 // Log sorted order for debugging
279 $sorted_order = [];
280 foreach ($rates as $rate_id => $rate) {
281 $sorted_order[] = $rate->label . ' - R$ ' . number_format(floatval($rate->cost), 2, ',', '.');
282 }
283 error_log('SuperFrete: Sorted shipping order: ' . implode(' | ', $sorted_order));
284
285 return $rates;
286 }
287
288
289 function add_custom_store_address_fields($settings)
290 {
291 $new_settings = [];
292
293 foreach ($settings as $setting) {
294 $new_settings[] = $setting;
295
296 // Após o campo de endereço 1
297 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_address') {
298 $new_settings[] = [
299 'title' => 'Número',
300 'desc_tip' => 'Número do endereço da loja',
301 'id' => 'woocommerce_store_number',
302 'type' => 'text',
303 'css' => 'min-width:300px;',
304 'default' => '',
305 'autoload' => false,
306 ];
307 }
308
309 // Após o campo de cidade
310 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_city') {
311 $new_settings[] = [
312 'title' => 'Bairro',
313 'desc_tip' => 'Bairro da loja',
314 'id' => 'woocommerce_store_neighborhood',
315 'type' => 'text',
316 'css' => 'min-width:300px;',
317 'default' => '',
318 'autoload' => false,
319 ];
320 }
321 }
322
323 return $new_settings;
324 }
325
326 /**
327 * Register custom order statuses for better tracking
328 */
329 public function register_custom_order_statuses()
330 {
331 // Register custom 'shipped' status
332 register_post_status('wc-shipped', [
333 'label' => 'Enviado',
334 'public' => true,
335 'exclude_from_search' => false,
336 'show_in_admin_all_list' => true,
337 'show_in_admin_status_list' => true,
338 'label_count' => _n_noop('Enviado <span class="count">(%s)</span>', 'Enviado <span class="count">(%s)</span>')
339 ]);
340
341 // Add custom statuses to WooCommerce order statuses
342 add_filter('wc_order_statuses', function($order_statuses) {
343 $order_statuses['wc-shipped'] = 'Enviado';
344 return $order_statuses;
345 });
346 }
347
348 public function superfrete_configs_setup_notice()
349 {
350 ?>
351 <div class="error notice">
352 <p><b>SuperFrete</b></p>
353 <p>
354 Para utilizar o plugin você deve
355 <a
356 href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description')); ?>">
357 configurar seu acesso a SuperFrete
358 </a>
359 e configurar um
360 <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings')); ?>">
361 endereço
362 </a>.
363 </p>
364 </div>
365 <?php
366 }
367
368 /**
369 * Adiciona um link para as configurações na página de plugins.
370 */
371 public static function superfrete_add_settings_link($links)
372 {
373 $settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description') . '">Configurações</a>';
374 array_unshift($links, $settings_link);
375 return $links;
376 }
377
378 // Criar a função que limpa os logs
379
380
381
382 static function singleShippingCountry()
383 {
384 if (!function_exists('WC') || !is_object(WC()->countries))
385 return false;
386
387 $countries = WC()->countries->get_shipping_countries();
388
389 if (count($countries) == 1) {
390 foreach (WC()->countries->get_shipping_countries() as $key => $value) {
391 return $key;
392 }
393 }
394
395 return false;
396 }
397
398 public function enqueue_assets()
399 {
400
401 wp_localize_script(
402 'jquery',
403 'superfrete_setting',
404 array(
405 'wc_ajax_url' => \WC_AJAX::get_endpoint('%%endpoint%%'),
406 'ajaxUrl' => admin_url('admin-ajax.php'),
407 'loading' => 'Loading..',
408 'auto_select_country' => apply_filters('pisol_ppscw_auto_select_country', self::singleShippingCountry()),
409 'load_location_by_ajax' => 1
410 )
411 );
412
413 wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0');
414
415 // Add shipping sorting script on checkout
416 if (is_checkout()) {
417 add_action('wp_footer', [$this, 'add_shipping_sorting_script']);
418
419 // Enqueue document field script for checkout
420 wp_enqueue_script(
421 'superfrete-document-field',
422 plugin_dir_url(__FILE__) . '../assets/js/document-field.js',
423 ['jquery'],
424 '1.0.0',
425 true
426 );
427 }
428
429 // Add theme customization support
430 add_action('wp_head', [$this, 'add_theme_customization_styles'], 100);
431 wp_enqueue_script(
432 'superfrete-popup',
433 plugin_dir_url(__FILE__) . '../assets/scripts/superfrete-popup.js',
434 ['jquery'],
435 '1.0.0', // Versão do script
436 true
437 );
438 wp_localize_script('superfrete-popup', 'superfrete_ajax', [
439 'ajax_url' => admin_url('admin-ajax.php'),
440 ]);
441 }
442
443 public function register_ajax_actions()
444 {
445 add_action('wp_ajax_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
446 add_action('wp_ajax_nopriv_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
447 }
448
449 // Criar a função que limpa os logs
450
451
452 public function handle_superfrete_update_address()
453 {
454 // Verifica o nonce
455 if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'superfrete_update_address_nonce')) {
456 wp_send_json_error(['message' => 'Requisição inválida.'], 403);
457 }
458
459 if (!session_id()) {
460 session_start();
461 }
462
463 if (!isset($_POST['order_id'])) {
464 wp_send_json_error(['message' => 'ID do pedido ausente.'], 400);
465 }
466
467 $order_id = intval($_POST['order_id']);
468 $order = wc_get_order($order_id);
469
470 if (!$order) {
471 wp_send_json_error(['message' => 'Pedido não encontrado.'], 404);
472 }
473
474 $current_shipping = $order->get_address('shipping');
475
476 $updated_data = [
477 'first_name' => sanitize_text_field($_POST['name']),
478 'address_1' => sanitize_text_field($_POST['address']),
479 'address_2' => sanitize_text_field($_POST['complement']),
480 'number' => sanitize_text_field($_POST['number']),
481 'neighborhood' => sanitize_text_field($_POST['district']),
482 'city' => sanitize_text_field($_POST['city']),
483 'state' => sanitize_text_field($_POST['state_abbr']),
484 'postcode' => sanitize_text_field($_POST['postal_code'])
485 ];
486 if (!empty($updated_data['number'])) {
487 $order->update_meta_data('_shipping_number', $updated_data['number']);
488 }
489 if (!empty($updated_data['neighborhood'])) {
490 $order->update_meta_data('_shipping_neighborhood', $updated_data['neighborhood']);
491 }
492
493 foreach ($updated_data as $key => $value) {
494 if (empty($current_shipping[$key]) && !empty($value)) {
495 $current_shipping[$key] = $value;
496 }
497 }
498 $order->set_address($current_shipping, 'shipping');
499 $order->save();
500 $_SESSION['superfrete_correction'][$order_id] = $current_shipping;
501
502 wp_send_json_success(['message' => 'Campos vazios preenchidos e endereço atualizado!', 'order_id' => $order_id]);
503 }
504
505 /**
506 * Add theme customization styles with CSS variables
507 */
508 public function add_theme_customization_styles() {
509 // Complete CSS variables with SuperFrete brand defaults
510 $default_variables = array(
511 // Primary brand colors
512 '--superfrete-primary-color' => '#0fae79',
513 '--superfrete-primary-hover' => '#0d9969',
514 '--superfrete-secondary-color' => '#c3ff01',
515 '--superfrete-secondary-hover' => '#b3e600',
516 '--superfrete-success-color' => '#4CAF50',
517 '--superfrete-error-color' => '#e74c3c',
518 '--superfrete-info-color' => '#2196F3',
519 '--superfrete-warning-color' => '#ff9800',
520
521 // Background colors
522 '--superfrete-bg-color' => '#ffffff',
523 '--superfrete-bg-white' => '#ffffff',
524 '--superfrete-bg-light' => '#f8f9fa',
525 '--superfrete-bg-dark' => '#1a1a1a',
526
527 // Text colors
528 '--superfrete-text-color' => '#1a1a1a',
529 '--superfrete-text-light' => '#777777',
530 '--superfrete-text-white' => '#ffffff',
531 '--superfrete-heading-color' => '#1a1a1a',
532
533 // Border colors
534 '--superfrete-border-color' => '#e0e0e0',
535 '--superfrete-border-light' => '#f0f0f0',
536 '--superfrete-border-dark' => '#cccccc',
537
538 // Typography
539 '--superfrete-font-family' => 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
540 '--superfrete-font-size-small' => '12px',
541 '--superfrete-font-size-base' => '14px',
542 '--superfrete-font-size-large' => '16px',
543 '--superfrete-font-size-xl' => '18px',
544 '--superfrete-font-weight-normal' => '400',
545 '--superfrete-font-weight-medium' => '500',
546 '--superfrete-font-weight-bold' => '600',
547 '--superfrete-line-height' => '1.5',
548
549 // Spacing
550 '--superfrete-spacing-xs' => '4px',
551 '--superfrete-spacing-sm' => '8px',
552 '--superfrete-spacing-md' => '12px',
553 '--superfrete-spacing-lg' => '16px',
554 '--superfrete-spacing-xl' => '24px',
555 '--superfrete-spacing-xxl' => '32px',
556
557 // Border radius
558 '--superfrete-radius-sm' => '4px',
559 '--superfrete-radius-md' => '6px',
560 '--superfrete-radius-lg' => '8px',
561 '--superfrete-radius-xl' => '12px',
562 '--superfrete-radius-full' => '50px',
563
564 // Shadows
565 '--superfrete-shadow-sm' => '0 1px 3px rgba(0, 0, 0, 0.1)',
566 '--superfrete-shadow-md' => '0 2px 6px rgba(0, 0, 0, 0.1)',
567 '--superfrete-shadow-lg' => '0 4px 12px rgba(0, 0, 0, 0.15)',
568
569 // Z-index
570 '--superfrete-z-base' => '1',
571 '--superfrete-z-overlay' => '100',
572 '--superfrete-z-loading' => '101',
573 '--superfrete-z-modal' => '200',
574
575 // Animation
576 '--superfrete-transition-fast' => '0.15s ease',
577 '--superfrete-transition-normal' => '0.3s ease',
578 '--superfrete-transition-slow' => '0.5s ease',
579 );
580
581 // Get custom CSS variables from database
582 $custom_variables = get_option('superfrete_custom_css_vars', array());
583
584 // Merge defaults with custom variables
585 $merged_variables = array_merge($default_variables, $custom_variables);
586
587 // Allow themes to modify CSS variables
588 $css_variables = apply_filters('superfrete_css_variables', $merged_variables);
589
590 // Build CSS string
591 $custom_css = ':root {';
592 foreach ($css_variables as $variable => $value) {
593 $custom_css .= sprintf('%s: %s;', esc_attr($variable), esc_attr($value));
594 }
595 $custom_css .= '}';
596
597 // Allow themes to add custom CSS
598 $additional_css = apply_filters('superfrete_custom_css', '');
599
600 // Output the styles
601 if (!empty($custom_css) || !empty($additional_css)) {
602 echo '<style id="superfrete-theme-customization">';
603 echo $custom_css;
604 echo $additional_css;
605 echo '</style>';
606 }
607 }
608
609 /**
610 * Add JavaScript to sort shipping options by price on the frontend
611 */
612 public function add_shipping_sorting_script() {
613 ?>
614 <script type="text/javascript">
615 jQuery(document).ready(function($) {
616 function sortShippingOptions() {
617 console.log('SuperFrete: Attempting to sort shipping options...');
618
619 // Try multiple selectors to find shipping options
620 var $containers = [
621 $('#shipping_method'),
622 $('.woocommerce-shipping-methods'),
623 $('ul.woocommerce-shipping-methods'),
624 $('.shipping-methods'),
625 $('[id*="shipping_method"]'),
626 $('ul li input[name^="shipping_method"]').closest('ul')
627 ];
628
629 var foundContainer = false;
630
631 $.each($containers, function(index, $container) {
632 if ($container.length > 0) {
633 console.log('SuperFrete: Found container #' + index + ':', $container);
634
635 var $options = $container.find('li');
636 if ($options.length <= 1) {
637 console.log('SuperFrete: Not enough options to sort (' + $options.length + ')');
638 return true; // Continue to next container
639 }
640
641 foundContainer = true;
642 console.log('SuperFrete: Found ' + $options.length + ' shipping options to sort');
643
644 // Log original order
645 $options.each(function(i) {
646 var text = $(this).text();
647 var price = extractPrice(text);
648 console.log('SuperFrete: Option ' + i + ': ' + text.substring(0, 50) + '... (Price: ' + price + ')');
649 });
650
651 // Convert to array and sort
652 var sortedOptions = $options.get().sort(function(a, b) {
653 var priceA = extractPrice($(a).text());
654 var priceB = extractPrice($(b).text());
655
656 // Free shipping (0) comes first
657 if (priceA === 0 && priceB > 0) return -1;
658 if (priceB === 0 && priceA > 0) return 1;
659
660 // Sort by price ascending
661 return priceA - priceB;
662 });
663
664 // Reorder the DOM elements
665 $.each(sortedOptions, function(index, element) {
666 $container.append(element);
667 });
668
669 console.log('SuperFrete: Shipping options sorted successfully!');
670
671 // Log sorted order
672 $container.find('li').each(function(i) {
673 var text = $(this).text();
674 var price = extractPrice(text);
675 console.log('SuperFrete: Sorted option ' + i + ': ' + text.substring(0, 50) + '... (Price: ' + price + ')');
676 });
677
678 return false; // Break out of loop
679 }
680 });
681
682 if (!foundContainer) {
683 console.log('SuperFrete: No shipping container found. Available elements:');
684 console.log('- #shipping_method:', $('#shipping_method').length);
685 console.log('- .woocommerce-shipping-methods:', $('.woocommerce-shipping-methods').length);
686 console.log('- ul.woocommerce-shipping-methods:', $('ul.woocommerce-shipping-methods').length);
687 console.log('- All shipping method inputs:', $('input[name^="shipping_method"]').length);
688 }
689 }
690
691 function extractPrice(text) {
692 // Extract price from text like "R$ 23,72", "R$ 15,49", "Grátis"
693 if (text.toLowerCase().includes('grátis') || text.toLowerCase().includes('gratuito') || text.toLowerCase().includes('free')) {
694 return 0;
695 }
696
697 // Match pattern like "R$ 23,72" or "23,72"
698 var match = text.match(/R\$?\s*(\d+)[,.](\d{2})/);
699 if (match) {
700 return parseFloat(match[1] + '.' + match[2]);
701 }
702
703 // Match pattern like "R$ 23" or "23"
704 match = text.match(/R\$?\s*(\d+)/);
705 if (match) {
706 return parseFloat(match[1]);
707 }
708
709 console.log('SuperFrete: Could not extract price from: ' + text);
710 return 999999; // Unknown prices go to the end
711 }
712
713 // Sort on initial load with multiple attempts
714 console.log('SuperFrete: Initializing shipping sort...');
715 setTimeout(sortShippingOptions, 500);
716 setTimeout(sortShippingOptions, 1000);
717 setTimeout(sortShippingOptions, 2000);
718 setTimeout(sortShippingOptions, 3000);
719
720 // Sort when shipping is recalculated
721 $(document.body).on('updated_checkout updated_shipping_method wc_checkout_place_order', function(e) {
722 console.log('SuperFrete: Checkout updated, re-sorting shipping...', e.type);
723 setTimeout(sortShippingOptions, 200);
724 setTimeout(sortShippingOptions, 500);
725 });
726
727 // Also try when any shipping method is changed
728 $(document).on('change', 'input[name^="shipping_method"]', function() {
729 console.log('SuperFrete: Shipping method changed, re-sorting...');
730 setTimeout(sortShippingOptions, 100);
731 });
732 });
733 </script>
734 <?php
735 }
736 }
737