<?php

/**
 * Plugin Name: Profit Warden
 * Description: Calculates real profit and margin for each order directly in your dashboard.
 * Version: 3.1.15
 * Requires at least: 5.3
 * License: GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: profit-warden
 */
if (!defined('ABSPATH')) {
    exit;
}
if (function_exists('profwabr_fs')) {
    profwabr_fs()->set_basename(false, __FILE__);
} else {
    if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
        add_action('admin_notices', function () {
            echo '<div class="notice notice-error"><p><strong>Profit Warden Error:</strong> Missing dependencies. Please download the fully built plugin zip or run <code>composer install</code> in the plugin folder.</p></div>';
        });
        return;
    }
    require_once __DIR__ . '/vendor/autoload.php';
    /**
     * DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE
     * `function_exists` CALL ABOVE TO PROPERLY WORK.
     */
    if (!function_exists('profwabr_fs')) {
        // Create a helper function for easy SDK access.
        function profwabr_fs()
        {
            global $profwabr_fs;
            if (!isset($profwabr_fs)) {
                // Include Freemius SDK.
                $profwabr_fs = fs_dynamic_init(array(
                    'id' => '25249',
                    'slug' => 'profit-warden',
                    'type' => 'plugin',
                    'public_key' => 'pk_1ff923b46baa2cbd1a335537aee3c',
                    'is_premium' => false,
                    'premium_suffix' => 'Pro',
                    'has_addons' => false,
                    'has_paid_plans' => false,
                    'is_org_compliant' => true,
                    'menu' => array(
                        'slug' => 'profit-warden',
                        'first-path' => 'admin.php?page=profit-warden',
                        'contact' => false,
                        'support' => false,
                    ),
                    'is_live' => true,
                ));
            }
            return $profwabr_fs;
        }

        // Init Freemius.
        profwabr_fs();
        // Signal that SDK was initiated.
        do_action('profwabr_fs_loaded');
    }
    if (in_array('woocommerce/woocommerce.php', (array) get_option('active_plugins', array()), true)) {
        // 0. PAGINA IMPOSTAZIONI (Nuova Sezione)
        add_action('admin_menu', 'profwabr_add_admin_menu');
        function profwabr_add_admin_menu()
        {
            add_menu_page(
                'Profit Warden',
                'Profit Warden',
                'manage_options',
                'profit-warden',
                'profwabr_dashboard_page',
                'dashicons-shield',
                30
            );
            add_submenu_page(
                'profit-warden',
                'Dashboard',
                'Dashboard',
                'manage_options',
                'profit-warden',
                'profwabr_dashboard_page'
            );
            add_submenu_page(
                'profit-warden',
                'Costs',
                'Costs',
                'manage_options',
                'profit-warden-costs',
                'profwabr_costs_page'
            );
            add_submenu_page(
                'profit-warden',
                'Settings',
                'Settings',
                'manage_options',
                'profit-warden-settings',
                'profwabr_options_page'
            );
            add_submenu_page(
                'profit-warden',
                'Ads Integration',
                'Ads Integration',
                'manage_options',
                'profit-warden-ads',
                'profwabr_ads_page'
            );
            // Pagina di setup nascosta (non appare nel menu)
            add_submenu_page(
                null,
                'Profit Warden Setup',
                'Setup',
                'manage_options',
                'profwabr-setup',
                'profwabr_setup_page'
            );
        }

        add_action('admin_init', 'profwabr_settings_init');
        // Redirect al setup wizard dopo l'attivazione
        add_action('admin_init', 'profwabr_maybe_redirect_to_setup');
        function profwabr_maybe_redirect_to_setup()
        {
            if (get_transient('profwabr_activation_redirect')) {
                delete_transient('profwabr_activation_redirect');
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only check on activation redirect, no data processed
                if (!isset($_GET['activate-multi']) && current_user_can('manage_options')) {
                    wp_safe_redirect(admin_url('admin.php?page=profwabr-setup'));
                    exit;
                }
            }
        }

        function profwabr_settings_init()
        {
            register_setting('profwabrPlugin', 'profwabr_settings', 'profwabr_sanitize_settings');
            // Main Settings Page
            add_settings_section(
                'profwabr_plugin_main',
                'API & Email Configuration',
                '__return_false',
                'profit-warden-settings'
            );
            // Costs Page
            add_settings_section(
                'profwabr_plugin_costs_var',
                'Variable Costs (Per Order)',
                '__return_false',
                'profit-warden-costs'
            );
            add_settings_section(
                'profwabr_plugin_costs_fixed',
                'Fixed Costs (Monthly)',
                '__return_false',
                'profit-warden-costs'
            );
            // Main Settings Fields
            $fields_main = [
                [
                    'id' => 'enable_api_sync',
                    'label' => 'Enable Data Sync (Consent)',
                    'type' => 'checkbox',
                    'description' => 'I consent to send WooCommerce order and customer data to the external Python API. Required for the plugin to work.',
                    'default' => '0',
                ],
                [
                    'id' => 'api_url',
                    'label' => 'Python API URL',
                    'default' => 'https://api.beralabs.it/calculate-profit',
                ],
                [
                    'id' => 'api_key',
                    'label' => 'Python API Key',
                    'default' => 'LaMiaChiaveSuperSegreta123',
                    'type' => 'password',
                ],
                [
                    'id' => 'report_email',
                    'label' => 'Report Email',
                    'default' => get_option('admin_email'),
                ],
                [
                    'id' => 'report_frequency',
                    'label' => 'Periodic Report Frequency',
                    'type' => 'select',
                    'options' => [
                        'disabled' => 'Disabled',
                        'daily' => 'Daily',
                        'weekly' => 'Weekly',
                        'monthly' => 'Monthly',
                    ],
                    'default' => 'disabled',
                ],
                [
                    'id' => 'enable_loss_alerts',
                    'label' => 'Enable loss alerts',
                    'type' => 'checkbox',
                    'default' => '1',
                ],
                [
                    'id' => 'enable_breakeven_alerts',
                    'label' => 'Enable breakeven point alerts',
                    'type' => 'checkbox',
                    'default' => '1',
                ]
            ];
            // Variable Costs Fields
            $fields_var = [
                [
                    'id' => 'packaging_cost',
                    'label' => 'Packaging Cost (€)',
                    'default' => '0.80',
                ],
                [
                    'id' => 'default_shipping',
                    'label' => 'Default Shipping Cost (€)',
                    'default' => '5.00',
                ],
                [
                    'id' => 'paypal_fixed',
                    'label' => 'PayPal Fixed Fee (€)',
                    'default' => '0.35',
                ],
                [
                    'id' => 'stripe_fixed',
                    'label' => 'Stripe Fixed Fee (€)',
                    'default' => '0.25',
                ],
                [
                    'id' => 'cod_fixed',
                    'label' => 'COD Cost (€)',
                    'default' => '3.00',
                ]
            ];
            // Fixed Costs Fields (Monthly)
            $fields_fixed = [
                [
                    'id' => 'fixed_hosting',
                    'label' => 'Hosting / Servers (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_saas',
                    'label' => 'SaaS Platforms (€)',
                    'description' => 'E.g., Shopify, CRM, ERP, Email',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_marketing',
                    'label' => 'Ad Agency / Retainers (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_salaries',
                    'label' => 'Employees / Salaries (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_rent',
                    'label' => 'Office / Warehouse Rent (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_insurance',
                    'label' => 'Insurance (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_accounting',
                    'label' => 'Accounting / Legal Fees (€)',
                    'default' => '0.00',
                ],
                [
                    'id' => 'fixed_other',
                    'label' => 'Other Fixed Costs (€)',
                    'default' => '0.00',
                ]
            ];
            foreach ($fields_main as $field) {
                add_settings_field(
                    'profwabr_' . $field['id'],
                    $field['label'],
                    'profwabr_settings_field_render',
                    'profit-warden-settings',
                    'profwabr_plugin_main',
                    array_merge($field, [
                        'type' => $field['type'] ?? 'text',
                    ])
                );
            }
            foreach ($fields_var as $field) {
                add_settings_field(
                    'profwabr_' . $field['id'],
                    $field['label'],
                    'profwabr_settings_field_render',
                    'profit-warden-costs',
                    'profwabr_plugin_costs_var',
                    array_merge($field, [
                        'type' => $field['type'] ?? 'text',
                    ])
                );
            }
            foreach ($fields_fixed as $field) {
                add_settings_field(
                    'profwabr_' . $field['id'],
                    $field['label'],
                    'profwabr_settings_field_render',
                    'profit-warden-costs',
                    'profwabr_plugin_costs_fixed',
                    array_merge($field, [
                        'type' => $field['type'] ?? 'text',
                    ])
                );
            }
        }

        function profwabr_sanitize_settings($input)
        {
            $existing = get_option('profwabr_settings', []);
            $new_input = $existing;
            $source = (isset($input['profwabr_form_source']) ? $input['profwabr_form_source'] : '');
            if ($source === 'settings_page') {
                $new_input['enable_api_sync'] = (!empty($input['enable_api_sync']) ? '1' : '0');
                $new_input['api_url'] = esc_url_raw($input['api_url'] ?? '');
                $new_input['api_key'] = sanitize_text_field($input['api_key'] ?? '');
                $new_input['report_email'] = sanitize_email($input['report_email'] ?? '');
                $allowed_freqs = [
                    'disabled',
                    'daily',
                    'weekly',
                    'monthly'
                ];
                $req_freq = sanitize_text_field($input['report_frequency'] ?? 'disabled');
                $new_input['report_frequency'] = (in_array($req_freq, $allowed_freqs, true) ? $req_freq : 'disabled');
                $new_input['enable_loss_alerts'] = (!empty($input['enable_loss_alerts']) ? '1' : '0');
                $new_input['enable_breakeven_alerts'] = (!empty($input['enable_breakeven_alerts']) ? '1' : '0');
            } elseif ($source === 'costs_page') {
                $cost_fields = [
                    'packaging_cost',
                    'default_shipping',
                    'paypal_fixed',
                    'stripe_fixed',
                    'cod_fixed',
                    'fixed_hosting',
                    'fixed_saas',
                    'fixed_marketing',
                    'fixed_salaries',
                    'fixed_rent',
                    'fixed_insurance',
                    'fixed_accounting',
                    'fixed_other'
                ];
                foreach ($cost_fields as $cf) {
                    $val = floatval($input[$cf] ?? 0.0);
                    $new_input[$cf] = number_format(
                        $val,
                        2,
                        '.',
                        ''
                    );
                }
            } else {
                // Fallback for simple single saves
                foreach ($input as $k => $v) {
                    if ($k !== 'profwabr_form_source') {
                        if (strpos($k, 'enable_') === 0 || strpos($k, 'is_') === 0) {
                            $new_input[$k] = (!empty($v) ? '1' : '0');
                        } elseif (strpos($k, 'cost') !== false || strpos($k, '_fixed') !== false) {
                            $new_input[$k] = number_format(
                                floatval($v),
                                2,
                                '.',
                                ''
                            );
                        } else {
                            $new_input[$k] = sanitize_text_field($v);
                        }
                    }
                }
            }
            return $new_input;
        }

        function profwabr_get_settings()
        {
            $defaults = [
                'enable_api_sync' => '0',
                'api_url' => 'https://api.beralabs.it/calculate-profit',
                'api_key' => 'LaMiaChiaveSuperSegreta123',
                'packaging_cost' => '0.80',
                'default_shipping' => '5.00',
                'paypal_fixed' => '0.35',
                'stripe_fixed' => '0.25',
                'cod_fixed' => '3.00',
                'report_email' => get_option('admin_email'),
                'report_frequency' => 'disabled',
                'enable_loss_alerts' => '1',
                'enable_breakeven_alerts' => '1',
                'fixed_hosting' => '0.00',
                'fixed_saas' => '0.00',
                'fixed_marketing' => '0.00',
                'fixed_salaries' => '0.00',
                'fixed_rent' => '0.00',
                'fixed_insurance' => '0.00',
                'fixed_accounting' => '0.00',
                'fixed_other' => '0.00',
            ];
            return wp_parse_args(get_option('profwabr_settings', []), $defaults);
        }

        // -----------------------------------------------------------------------
        // CONFIGURATION CHECK - funzione centrale
        // Restituisce array di check: ['label','status'=>ok|warning|error,'detail','critical'=>bool]
        // -----------------------------------------------------------------------
        function profwabr_run_config_check()
        {
            $opts = profwabr_get_settings();
            $results = [];
            // 0. Sync Consent
            $enable_api_sync = (isset($opts['enable_api_sync']) ? $opts['enable_api_sync'] : '0');
            if ($enable_api_sync !== '1') {
                $results[] = [
                    'label' => 'Data Sync Consent',
                    'status' => 'error',
                    'detail' => 'Consenso alla trasmissione dati non fornito (Opt-in). Il plugin non invierà alcun dato.',
                    'critical' => true,
                ];
            }
            // 1. API URL
            $api_url = (isset($opts['api_url']) ? $opts['api_url'] : '');
            if (empty($api_url)) {
                $results[] = [
                    'label' => 'Python API URL',
                    'status' => 'error',
                    'detail' => 'Non configurato.',
                    'critical' => true,
                ];
            } elseif (filter_var($api_url, FILTER_VALIDATE_URL) === false) {
                $results[] = [
                    'label' => 'Python API URL',
                    'status' => 'error',
                    'detail' => 'URL non valido: ' . esc_html($api_url),
                    'critical' => true,
                ];
            } else {
                $results[] = [
                    'label' => 'Python API URL',
                    'status' => 'ok',
                    'detail' => esc_html($api_url),
                    'critical' => true,
                ];
            }
            // 2. API Key
            $api_key = (isset($opts['api_key']) ? $opts['api_key'] : '');
            if (empty($api_key)) {
                $results[] = [
                    'label' => 'API Key',
                    'status' => 'warning',
                    'detail' => 'Non configurata &mdash; API esposta senza autenticazione.',
                    'critical' => false,
                ];
            } elseif (strlen($api_key) < 16) {
                $results[] = [
                    'label' => 'API Key',
                    'status' => 'warning',
                    'detail' => 'Chiave troppo corta (&lt;16 car.) &mdash; considera una chiave pi&ugrave; sicura.',
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'API Key',
                    'status' => 'ok',
                    'detail' => '&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;' . substr($api_key, -4),
                    'critical' => false,
                ];
            }
            // 3. Packaging Cost
            $pack_raw = (isset($opts['packaging_cost']) ? $opts['packaging_cost'] : null);
            if ($pack_raw === null || $pack_raw === '') {
                $results[] = [
                    'label' => 'Packaging Cost',
                    'status' => 'error',
                    'detail' => 'Non configurato.',
                    'critical' => true,
                ];
            } elseif ((float) $pack_raw == 0) {
                $results[] = [
                    'label' => 'Packaging Cost',
                    'status' => 'warning',
                    'detail' => '0.00 &euro; &mdash; verifica se il packaging &egrave; davvero gratuito.',
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'Packaging Cost',
                    'status' => 'ok',
                    'detail' => number_format((float) $pack_raw, 2) . ' &euro;',
                    'critical' => true,
                ];
            }
            // 4. Default Shipping Cost (fallback)
            $ship_raw = (isset($opts['default_shipping']) ? $opts['default_shipping'] : null);
            if ($ship_raw === null || $ship_raw === '') {
                $results[] = [
                    'label' => 'Default Shipping Cost',
                    'status' => 'error',
                    'detail' => 'Non configurato.',
                    'critical' => true,
                ];
            } elseif ((float) $ship_raw == 0) {
                $results[] = [
                    'label' => 'Default Shipping Cost',
                    'status' => 'warning',
                    'detail' => '0.00 &euro; &mdash; usato come fallback se il metodo non ha costo reale.',
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'Default Shipping Cost',
                    'status' => 'ok',
                    'detail' => number_format((float) $ship_raw, 2) . ' &euro; (fallback)',
                    'critical' => true,
                ];
            }
            // 5. Gateway Fees
            foreach ([
                'paypal_fixed' => 'PayPal Fixed Fee',
                'stripe_fixed' => 'Stripe Fixed Fee',
                'cod_fixed' => 'COD Cost',
            ] as $key => $lbl) {
                $gw_val = (isset($opts[$key]) ? $opts[$key] : null);
                if ($gw_val === null || $gw_val === '') {
                    $results[] = [
                        'label' => $lbl,
                        'status' => 'warning',
                        'detail' => 'Non configurato (inserisci 0.00 se il metodo non &egrave; attivo).',
                        'critical' => false,
                    ];
                } else {
                    $results[] = [
                        'label' => $lbl,
                        'status' => 'ok',
                        'detail' => number_format((float) $gw_val, 2) . ' &euro;',
                        'critical' => false,
                    ];
                }
            }
            // 6. Report Email
            $email = (isset($opts['report_email']) ? $opts['report_email'] : '');
            if (empty($email)) {
                $results[] = [
                    'label' => 'Report Email',
                    'status' => 'warning',
                    'detail' => 'Non configurata &mdash; report e alert non verranno inviati.',
                    'critical' => false,
                ];
            } elseif (!is_email($email)) {
                $results[] = [
                    'label' => 'Report Email',
                    'status' => 'error',
                    'detail' => 'Indirizzo non valido: ' . esc_html($email),
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'Report Email',
                    'status' => 'ok',
                    'detail' => esc_html($email),
                    'critical' => false,
                ];
            }
            // 7. Metodi di spedizione con costo reale (profwabr_real_cost)
            $shipping_zones = WC_Shipping_Zones::get_zones();
            $methods_total = 0;
            $methods_missing = [];
            $zone_0 = new WC_Shipping_Zone(0);
            $all_zone_methods = $zone_0->get_shipping_methods(true);
            foreach ($shipping_zones as $zd) {
                $zone = new WC_Shipping_Zone($zd['id']);
                $all_zone_methods = array_merge($all_zone_methods, $zone->get_shipping_methods(true));
            }
            foreach ($all_zone_methods as $method) {
                if (!in_array($method->id, ['flat_rate', 'free_shipping'])) {
                    continue;
                }
                $methods_total++;
                $inst = get_option('woocommerce_' . $method->id . '_' . $method->get_instance_id() . '_settings');
                $rc = (isset($inst['profwabr_real_cost']) ? $inst['profwabr_real_cost'] : '');
                if ($rc === '' || $rc === '0') {
                    $methods_missing[] = esc_html($method->get_title()) . ' (ID:' . $method->get_instance_id() . ')';
                }
            }
            if ($methods_total === 0) {
                $results[] = [
                    'label' => 'Metodi spedizione (Actual Cost)',
                    'status' => 'warning',
                    'detail' => 'Nessun metodo flat_rate/free_shipping trovato nelle zone di spedizione.',
                    'critical' => false,
                ];
            } elseif (!empty($methods_missing)) {
                $results[] = [
                    'label' => 'Metodi spedizione (Actual Cost)',
                    'status' => 'warning',
                    'detail' => '"Actual Cost" mancante in: ' . implode(', ', $methods_missing),
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'Metodi spedizione (Actual Cost)',
                    'status' => 'ok',
                    'detail' => $methods_total . ' metodo/i con costo reale configurato.',
                    'critical' => false,
                ];
            }
            // 8. Prodotti senza Purchase Cost
            $prods_missing = get_posts([
                'post_type' => 'product',
                'posts_per_page' => -1,
                'post_status' => 'publish',
                'fields' => 'ids',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Necessary to detect missing configurations without complex joins
                'meta_query' => [
                    'relation' => 'OR',
                    [
                        'key' => '_purchase_cost',
                        'compare' => 'NOT EXISTS',
                    ],
                    [
                        'key' => '_purchase_cost',
                        'value' => '',
                        'compare' => '=',
                    ],
                    [
                        'key' => '_purchase_cost',
                        'value' => '0',
                        'compare' => '=',
                    ],
                ],
            ]);
            $total_prods = (int) wp_count_posts('product')->publish;
            $missing_count = count($prods_missing);
            if ($missing_count === 0) {
                $results[] = [
                    'label' => 'Prodotti con Purchase Cost',
                    'status' => 'ok',
                    'detail' => 'Tutti i ' . $total_prods . ' prodotti hanno il costo d\'acquisto.',
                    'critical' => false,
                ];
            } elseif ($missing_count < $total_prods) {
                $results[] = [
                    'label' => 'Prodotti con Purchase Cost',
                    'status' => 'warning',
                    'detail' => $missing_count . ' su ' . $total_prods . ' prodotti senza costo d\'acquisto.',
                    'critical' => false,
                ];
            } else {
                $results[] = [
                    'label' => 'Prodotti con Purchase Cost',
                    'status' => 'error',
                    'detail' => 'Nessun prodotto ha il costo d\'acquisto &mdash; i profitti saranno errati.',
                    'critical' => true,
                ];
            }
            // 9. Raggiungibilita server Python
            $enable_api_sync = (isset($opts['enable_api_sync']) ? $opts['enable_api_sync'] : '0');
            if (!empty($api_url) && $enable_api_sync === '1') {
                $ping_url = str_replace('/calculate-profit', '/docs', $api_url);
                $response = wp_remote_get($ping_url, [
                    'timeout' => 5,
                    'sslverify' => false,
                ]);
                if (is_wp_error($response)) {
                    $results[] = [
                        'label' => 'Server Python',
                        'status' => 'error',
                        'detail' => 'Non raggiungibile: ' . $response->get_error_message(),
                        'critical' => true,
                    ];
                } else {
                    $code = wp_remote_retrieve_response_code($response);
                    if ($code === 200) {
                        $results[] = [
                            'label' => 'Server Python',
                            'status' => 'ok',
                            'detail' => 'Online (HTTP 200)',
                            'critical' => true,
                        ];
                    } else {
                        $results[] = [
                            'label' => 'Server Python',
                            'status' => 'warning',
                            'detail' => 'Risposta HTTP ' . $code . ' &mdash; server attivo ma /docs non accessibile (normale in prod).',
                            'critical' => false,
                        ];
                    }
                }
            } else {
                $results[] = [
                    'label' => 'Server Python',
                    'status' => 'error',
                    'detail' => 'Impossibile controllare: API URL mancante.',
                    'critical' => true,
                ];
            }
            return $results;
        }

        // Admin notice automatico su pagine ordini e impostazioni
        add_action('admin_notices', 'profwabr_admin_config_notices');
        function profwabr_admin_config_notices()
        {
            if (!current_user_can('manage_options')) {
                return;
            }
            $screen = get_current_screen();
            if (!$screen) {
                return;
            }
            if (
                !in_array($screen->id, [
                    'woocommerce_page_wc-orders',
                    'edit-shop_order',
                    'shop_order',
                    'toplevel_page_profit-warden',
                    'profit-warden_page_profit-warden-settings'
                ])
            ) {
                return;
            }
            $results = profwabr_run_config_check();
            $errors = array_values(array_filter($results, function ($r) {
                return $r['status'] === 'error' && $r['critical'];
            }));
            $warnings = array_values(array_filter($results, function ($r) {
                return $r['status'] === 'warning';
            }));
            if (!empty($errors)) {
                $items = '';
                foreach ($errors as $r) {
                    $items .= '<li><strong>' . esc_html($r['label']) . '</strong>: ' . $r['detail'] . '</li>';
                }
                echo '<div class="notice notice-error"><p><strong>🛡️ Profit Warden &mdash; Errori critici di configurazione:</strong></p>' . '<ul style="margin-left:20px;list-style:disc">' . wp_kses_post($items) . '</ul>' . '<p><a href="' . esc_url(admin_url('options-general.php?page=profit-warden')) . '">&rarr; Vai alle impostazioni Profit Warden</a></p></div>';
            } elseif (!empty($warnings)) {
                echo '<div class="notice notice-warning is-dismissible"><p>🛡️ <strong>Profit Warden</strong>: ' . count($warnings) . ' parametro/i da verificare. ' . '<a href="' . esc_url(admin_url('admin.php?page=profit-warden-settings#profwabr-config-check')) . '">Controlla la configurazione &rarr;</a></p></div>';
            }
        }

        function profwabr_settings_field_render($args)
        {
            $options = profwabr_get_settings();
            $val = (isset($options[$args['id']]) ? $options[$args['id']] : $args['default']);
            if ($args['type'] === 'checkbox') {
                echo "<input type='checkbox' name='profwabr_settings[" . esc_attr($args['id']) . "]' value='1' " . checked('1', $val, false) . ">";
            } elseif ($args['type'] === 'select') {
                $is_disabled = false;
                echo "<select name='profwabr_settings[" . esc_attr($args['id']) . "]' id='profwabr_" . esc_attr($args['id']) . "' " . disabled($is_disabled, true, false) . ">";
                foreach ($args['options'] as $key => $label) {
                    echo "<option value='" . esc_attr($key) . "' " . selected($val, $key, false) . ">" . esc_html($label) . "</option>";
                }
                echo "</select>";
                echo "<p class='description'>Choose the frequency to receive automatic reports via email.</p>";
            } else {
                $input_type = ($args['type'] === 'password' ? 'password' : 'text');
                echo "<input type='" . esc_attr($input_type) . "' name='profwabr_settings[" . esc_attr($args['id']) . "]' value='" . esc_attr($val) . "' style='width: 300px;'>";
                if (!empty($args['description'])) {
                    echo "<p class='description'>" . esc_html($args['description']) . "</p>";
                }
            }
        }

        /* CSS e JS per la pagina impostazioni e dashboard */
        add_action('admin_enqueue_scripts', 'profwabr_admin_scripts');
        function profwabr_admin_scripts($hook)
        {
            if (strpos($hook, 'profit-warden') !== false) {
                wp_enqueue_style(
                    'profwabr-admin-css',
                    plugins_url('assets/css/profwabr-admin.css', __FILE__),
                    array(),
                    '3.1.6'
                );
                wp_register_script(
                    'chart-js',
                    plugins_url('assets/js/chart.min.js', __FILE__),
                    array(),
                    '4.4.0',
                    true
                );
                wp_enqueue_script(
                    'profwabr-admin-js',
                    plugins_url('assets/js/profwabr-admin.js', __FILE__),
                    array('jquery', 'chart-js'),
                    '3.1.6',
                    true
                );
                wp_localize_script('profwabr-admin-js', 'profwabrAdminData', array(
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'reportNonce' => wp_create_nonce('profwabr_report_nonce'),
                ));
                wp_enqueue_script('chart-js');
            }
        }

        /* Frontend tracking script */
        add_action('wp_enqueue_scripts', 'profwabr_frontend_scripts');
        function profwabr_frontend_scripts()
        {
            $opts = profwabr_get_settings();
            if (isset($opts['enable_api_sync']) && $opts['enable_api_sync'] === '1') {
                wp_enqueue_script(
                    'profwabr-tracking',
                    plugins_url('assets/js/profwabr-tracking.js', __FILE__),
                    array(),
                    '1.0.0',
                    true
                );
            }
        }

        /* Salva cookie tracking su nuovo ordine */
        add_action(
            'woocommerce_checkout_create_order',
            'profwabr_save_tracking_cookies_to_order',
            10,
            2
        );
        function profwabr_save_tracking_cookies_to_order($order, $data)
        {
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                return;
            }
            $params = [
                'utm_source',
                'utm_medium',
                'utm_campaign',
                'fbclid',
                'gclid'
            ];
            foreach ($params as $param) {
                $cookie_name = 'profwabr_track_' . $param;
                $old_cookie_name = 'pw_track_' . $param;
                if (isset($_COOKIE[$cookie_name])) {
                    $order->update_meta_data('_profwabr_track_' . $param, sanitize_text_field(wp_unslash($_COOKIE[$cookie_name])));
                } elseif (isset($_COOKIE[$old_cookie_name])) {
                    $order->update_meta_data('_profwabr_track_' . $param, sanitize_text_field(wp_unslash($_COOKIE[$old_cookie_name])));
                } elseif (isset($_GET[$param])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only UTM/ad tracking params from URL, no state modified
                    $order->update_meta_data('_profwabr_track_' . $param, sanitize_text_field(wp_unslash($_GET[$param]))); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                }
            }
        }

        /* Supporto per Checkout a Blocchi (Store API - default su nuovi WooCommerce) */
        add_action(
            'woocommerce_store_api_checkout_update_order_from_request',
            'profwabr_save_tracking_cookies_store_api',
            10,
            2
        );
        function profwabr_save_tracking_cookies_store_api($order, $request)
        {
            profwabr_save_tracking_cookies_to_order($order, []);
        }

        // -----------------------------------------------------------------------
        // SETUP WIZARD — mostrata subito dopo l'attivazione del plugin
        // -----------------------------------------------------------------------
        function profwabr_setup_page()
        {
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('Non hai i permessi per accedere a questa pagina.', 'profit-warden'));
            }
            wp_register_style(
                'profwabr-setup-css',
                plugins_url('assets/css/profwabr-setup.css', __FILE__),
                array(),
                '3.1.6'
            );
            // Enqueue the setup stylesheet.
            wp_enqueue_style('profwabr-setup-css');
            // Gestione del submit del form
            if (isset($_POST['profwabr_setup_nonce']) && wp_verify_nonce(sanitize_key(wp_unslash($_POST['profwabr_setup_nonce'])), 'profwabr_setup_action')) {
                $settings = get_option('profwabr_settings', []);
                
                // Report Email
                $settings['report_email'] = (isset($_POST['report_email']) ? sanitize_email(wp_unslash($_POST['report_email'])) : '');
                
                // Variable Costs
                $var_fields = ['packaging_cost', 'default_shipping', 'paypal_fixed', 'stripe_fixed', 'cod_fixed'];
                foreach ($var_fields as $field) {
                    if (isset($_POST[$field])) {
                        $settings[$field] = number_format(floatval($_POST[$field]), 2, '.', '');
                    }
                }
                
                // Fixed Costs
                $fixed_fields = ['fixed_hosting', 'fixed_saas', 'fixed_marketing', 'fixed_salaries', 'fixed_rent', 'fixed_insurance', 'fixed_accounting', 'fixed_other'];
                foreach ($fixed_fields as $field) {
                    if (isset($_POST[$field])) {
                        $settings[$field] = number_format(floatval($_POST[$field]), 2, '.', '');
                    }
                }
                
                // Consent Sync
                $settings['enable_api_sync'] = (isset($_POST['enable_api_sync']) ? '1' : '0');
                
                // Pre-fill API URL per evitare blocchi nei vecchi check
                $settings['api_url'] = 'https://api.beralabs.it/calculate-profit';
                
                update_option('profwabr_settings', $settings);
                echo '<script>window.location.href="' . esc_url(admin_url('admin.php?page=profit-warden&profwabr_setup=1')) . '";</script>';
                exit;
            }
            $opts = profwabr_get_settings();
            ?>
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset="utf-8">
                        <title>Profit Warden — Setup</title>
                        <?php wp_print_styles('profwabr-setup-css'); ?>
                    </head>
                    <body>
                    <div class="setup-wrap">
                        <div class="setup-header">
                            <div class="setup-logo">
                                <div class="setup-logo-icon">🛡️</div>
                                <span class="setup-logo-name">Profit Warden</span>
                            </div>
                            <h1>Welcome! Let's configure your store.</h1>
                            <p>To accurately calculate your profit and margin locally, Profit Warden needs to know your costs and where to send your reports.</p>
                        </div>

                        <form method="post" action="">
                            <?php wp_nonce_field('profwabr_setup_action', 'profwabr_setup_nonce'); ?>

                            <!-- STEP 1 — Consent -->
                            <div class="setup-card">
                                <div class="setup-card-title">
                                    🔒 Data Transmission Consent
                                    <span class="badge">Required</span>
                                </div>
                                <p class="setup-card-sub">
                                    This plugin connects your WooCommerce store to an external Python-based analysis service.
                                    The following order data will be transmitted to the API you configure.
                                    <strong style="color:#f0f6fc;">No data will be sent without your explicit consent.</strong>
                                </p>

                                <ul class="data-list">
                                    <li><span class="icon">📦</span> Order ID &amp; Status</li>
                                    <li><span class="icon">🏷️</span> Product names, SKUs &amp; quantities</li>
                                    <li><span class="icon">💶</span> Item prices &amp; VAT amounts</li>
                                    <li><span class="icon">🚚</span> Shipping method &amp; cost</li>
                                    <li><span class="icon">💳</span> Payment method</li>
                                    <li><span class="icon">📧</span> Customer name &amp; email</li>
                                    <li><span class="icon">🏷️</span> Discount codes applied</li>
                                    <li><span class="icon">📊</span> UTM / marketing parameters</li>
                                </ul>

                                <label class="consent-box" for="enable_api_sync">
                                    <input type="checkbox" name="enable_api_sync" id="enable_api_sync" value="1"
                                        <?php checked('1', $opts['enable_api_sync'] ?? '0'); ?>>
                                    <div>
                                        <label for="enable_api_sync">
                                            <strong>I consent to transmit order data to the external Profit Warden API</strong>
                                            I understand that the data listed above will be sent securely to the API URL.
                                            I can revoke this consent at any time from the plugin settings page.
                                        </label>
                                    </div>
                                </label>
                            </div>

                            <!-- STEP 2 — General Info -->
                            <div class="setup-card">
                                <div class="setup-card-title">📧 Communication Settings</div>
                                <p class="setup-card-sub">Where should we send your periodic profit reports and alerts?</p>
                                <div class="field-group">
                                    <label class="field-label" for="report_email">Report Email Address</label>
                                    <input class="field-input" style="width: 100%; box-sizing: border-box;" type="email" id="report_email" name="report_email" value="<?php echo esc_attr($opts['report_email'] ?? get_option('admin_email')); ?>" required>
                                </div>
                            </div>

                            <!-- STEP 2 — Variable Costs -->
                            <div class="setup-card">
                                <div class="setup-card-title">📦 Variable Costs (Per Order)</div>
                                <p class="setup-card-sub">These costs are applied to every order processed through your store.</p>
                                
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                    <div class="field-group">
                                        <label class="field-label" for="packaging_cost">Packaging Cost (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="packaging_cost" name="packaging_cost" value="<?php echo esc_attr($opts['packaging_cost'] ?? '0.80'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="default_shipping">Default Shipping Cost (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="default_shipping" name="default_shipping" value="<?php echo esc_attr($opts['default_shipping'] ?? '5.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="paypal_fixed">PayPal Fixed Fee (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="paypal_fixed" name="paypal_fixed" value="<?php echo esc_attr($opts['paypal_fixed'] ?? '0.35'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="stripe_fixed">Stripe Fixed Fee (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="stripe_fixed" name="stripe_fixed" value="<?php echo esc_attr($opts['stripe_fixed'] ?? '0.25'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="cod_fixed">COD Cost (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="cod_fixed" name="cod_fixed" value="<?php echo esc_attr($opts['cod_fixed'] ?? '3.00'); ?>">
                                    </div>
                                </div>
                            </div>

                            <!-- STEP 3 — Fixed Costs -->
                            <div class="setup-card">
                                <div class="setup-card-title">🏢 Fixed Monthly Costs</div>
                                <p class="setup-card-sub">Your monthly operational expenses, used to calculate Break-even Point and Daily Burn Rate.</p>
                                
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_hosting">Hosting/Servers (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_hosting" name="fixed_hosting" value="<?php echo esc_attr($opts['fixed_hosting'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_saas">SaaS Platforms (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_saas" name="fixed_saas" value="<?php echo esc_attr($opts['fixed_saas'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_marketing">Ad Agency/Retainers (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_marketing" name="fixed_marketing" value="<?php echo esc_attr($opts['fixed_marketing'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_salaries">Employees/Salaries (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_salaries" name="fixed_salaries" value="<?php echo esc_attr($opts['fixed_salaries'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_rent">Office/Warehouse Rent (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_rent" name="fixed_rent" value="<?php echo esc_attr($opts['fixed_rent'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_insurance">Insurance (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_insurance" name="fixed_insurance" value="<?php echo esc_attr($opts['fixed_insurance'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_accounting">Accounting/Legal (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_accounting" name="fixed_accounting" value="<?php echo esc_attr($opts['fixed_accounting'] ?? '0.00'); ?>">
                                    </div>
                                    <div class="field-group">
                                        <label class="field-label" for="fixed_other">Other Fixed Costs (€)</label>
                                        <input class="field-input" style="width: 100%; box-sizing: border-box;" type="text" id="fixed_other" name="fixed_other" value="<?php echo esc_attr($opts['fixed_other'] ?? '0.00'); ?>">
                                    </div>
                                </div>
                            </div>

                            <div class="setup-footer">
                                <a class="skip-link" href="<?php echo esc_url(admin_url('admin.php?page=profit-warden')); ?>">
                                    Skip for now →
                                </a>
                                <button type="submit" class="btn-primary">
                                    Save Configuration &amp; Start ✦
                                </button>
                            </div>
                        </form>

                        <p class="setup-note">
                            You can review and change all settings at any time from
                            <a href="<?php echo esc_url(admin_url('admin.php?page=profit-warden-settings')); ?>">Profit Warden → Settings</a>.
                        </p>
                    </div>
                    </body>
                    </html>
                <?php
        }

        function profwabr_dashboard_page()
        {
            ?>
                    <div class="wrap" id="profwabr-dashboard-app">
                        <div class="profwabr-dashboard-header">
                            <h1>Profit Warden Overview</h1>
                            <p>Financial performance overview for the last 30 days.</p>
                        </div>

                        <div class="profwabr-refresh-row">
                            <select id="profwabr-range-selector">
                                <option value="1">Today</option>
                                <option value="7">Last 7 Days</option>
                                <option value="30" selected>Last 30 Days</option>
                                <option value="365">Last Year</option>
                            </select>
                            <button id="profwabr-refresh-dashboard">🔄 Refresh Data</button>
                        </div>

                        <div class="profwabr-stats-grid" id="profwabr-metrics-container">
                            <div class="profwabr-stat-card profwabr-card-revenue">
                                <div class="profwabr-stat-label">Total Revenue</div>
                                <div class="profwabr-stat-value" id="val-revenue">-- €</div>
                            </div>
                            <div class="profwabr-stat-card profwabr-card-profit">
                                <div class="profwabr-stat-label">Net Profit</div>
                                <div class="profwabr-stat-value" id="val-profit">-- €</div>
                            </div>
                            <div class="profwabr-stat-card profwabr-card-margin">
                                <div class="profwabr-stat-label">Avg Margin</div>
                                <div class="profwabr-stat-value" id="val-margin">-- %</div>
                            </div>
                            <div class="profwabr-stat-card" style="border-top: 3px solid #6b7280;">
                                <div class="profwabr-stat-label">Ad Spend</div>
                                <div class="profwabr-stat-value" id="val-adspend" title="Total Meta/Google Ads cost in this period">-- €</div>
                            </div>
                            <div class="profwabr-stat-card profwabr-card-profit">
                                <div class="profwabr-stat-label">Real Net Profit</div>
                                <div class="profwabr-stat-value" id="val-realprofit" title="Net profit after deducting Ad Spend">-- €</div>
                            </div>
                            <div class="profwabr-stat-card" style="border-top: 3px solid #8b5cf6;">
                                <div class="profwabr-stat-label">ROAS</div>
                                <div class="profwabr-stat-value" id="val-roas" title="Return On Ad Spend (Revenue ÷ Ad Spend)">--</div>
                            </div>
                            <div class="profwabr-stat-card profwabr-card-orders">
                                <div class="profwabr-stat-label">Total Orders</div>
                                <div class="profwabr-stat-value" id="val-orders">--</div>
                            </div>
                            <div class="profwabr-stat-card" style="border-top: 3px solid #f5a623;">
                                <div class="profwabr-stat-label">Daily Burn Rate</div>
                                <div class="profwabr-stat-value" id="val-dbr" title="Monthly fixed costs divided by 30 days">-- €</div>
                            </div>
                            <div class="profwabr-stat-card" style="border-top: 3px solid #ff4d4f;">
                                <div class="profwabr-stat-label">Breakeven Point</div>
                                <div class="profwabr-stat-value" id="val-bep" title="Revenue needed to cover fixed costs based on avg margin">-- €</div>
                            </div>
                        </div>

                        <div class="profwabr-middle-grid">
                            <div class="profwabr-chart-container">
                                <canvas id="profwabr-performance-chart" style="width: 100%; height: 100%;"></canvas>
                            </div>
                
                            <div class="profwabr-feed-card">
                                <div class="profwabr-feed-header">Order Intelligence Feed</div>
                                <ul class="profwabr-feed-list" id="profwabr-recent-feed">
                                    <li class="profwabr-feed-item">Loading...</li>
                                </ul>
                            </div>
                        </div>

                        <div class="profwabr-rankings-grid">
                            <div class="profwabr-ranking-card">
                                <div class="profwabr-ranking-title"><span>📦</span> Top Selling Products</div>
                                <div class="profwabr-table-container" id="list-products">
                                    Loading...
                                </div>
                            </div>
                            <div class="profwabr-ranking-card">
                                <div class="profwabr-ranking-title"><span>🏆</span> Top Customers</div>
                                <div class="profwabr-table-container" id="list-customers">
                                    Loading...
                                </div>
                            </div>
                        </div>
                    </div>
                <?php
        }

        function profwabr_costs_page()
        {
            ?>
                    <div class="wrap">
                        <h1>Profit Warden - Costs</h1>
                        <p>Manage your variable (per order) and <br/>fixed (monthly) costs here. Note: Fixed costs are used exclusively for Breakeven Point and Daily Burn Rate calculations.</p>
                        <form action='options.php' method='post'>
                            <input type="hidden" name="profwabr_settings[profwabr_form_source]" value="costs_page" />
                            <?php
                            try {
                                settings_fields('profwabrPlugin');
                                do_settings_sections('profit-warden-costs');
                                submit_button();
                            } catch (\Throwable $e) {
                                echo '<div style="background:#fff; border-left:4px solid red; padding:15px; margin-top:20px;">';
                                echo '<h3>Caught Error!</h3>';
                                echo '<strong>Message:</strong> ' . esc_html($e->getMessage()) . '<br>';
                                echo '<strong>File:</strong> ' . esc_html($e->getFile()) . ' on line ' . esc_html($e->getLine()) . '<br>';
                                echo '<strong>Trace:</strong><pre>' . esc_html($e->getTraceAsString()) . '</pre>';
                                echo '</div>';
                            }
                            ?>
                        </form>
                    </div>
                <?php
        }

        function profwabr_options_page()
        {
            ?>
                    <div class="wrap">
                        <h1>Profit Warden - Settings</h1>
                        <form action='options.php' method='post'>
                            <input type="hidden" name="profwabr_settings[profwabr_form_source]" value="settings_page" />
                            <?php
                            try {
                                settings_fields('profwabrPlugin');
                                do_settings_sections('profit-warden-settings');
                                submit_button();
                            } catch (\Throwable $e) {
                                echo '<div style="background:#fff; border-left:4px solid red; padding:15px; margin-top:20px;">';
                                echo '<h3>Caught Error!</h3>';
                                echo '<strong>Message:</strong> ' . esc_html($e->getMessage()) . '<br>';
                                echo '<strong>File:</strong> ' . esc_html($e->getFile()) . ' on line ' . esc_html($e->getLine()) . '<br>';
                                echo '<strong>Trace:</strong><pre>' . esc_html($e->getTraceAsString()) . '</pre>';
                                echo '</div>';
                            }
                            ?>
                
                            <hr>
                            <h2>Database Tools</h2>
                            <p>Click below to receive a CSV via email with all orders stored in the Python database.</p>
                            <button type="button" id="profwabr-send-report-btn" class="button button-secondary">📧 Send Full Report</button>
                            <span id="profwabr-report-status" style="margin-left: 10px; font-weight: bold;"></span>
                
                            <p style="margin-top: 15px;">Check if the Python server SMTP configuration is working correctly:</p>
                            <button type="button" id="profwabr-test-smtp-btn" class="button button-secondary">📨 Test Email Configuration</button>
                            <span id="profwabr-smtp-status" style="margin-left: 10px; font-weight: bold;"></span>
                        </form>

                        <hr id="profwabr-config-check">
                        <h2>⚙️ Configuration Check</h2>
                        <p>Verifica immediata dello stato dei parametri e della connessione al server.</p>
            
                        <div id="profwabr-config-results">
                            <?php
                            profwabr_render_config_table();
                            ?>
                        </div>

                        <p style="margin-top: 20px;">
                            <button type="button" id="profwabr-refresh-check-btn" class="button button-secondary">🔄 Refresh Health Check</button>
                        </p>
                    </div>
                <?php
        }

        // end profwabr_options_page
        // =========================================================
        // ADS INTEGRATION PAGE
        // =========================================================
        function profwabr_ads_page()
        {
            $settings = get_option('profwabr_settings', []);
            if (empty($settings['enable_api_sync']) || $settings['enable_api_sync'] !== '1') {
                echo '<div class="wrap"><h1>Ads Integration</h1>';
                echo '<div class="notice notice-error"><p><strong>Data Sync Consent Required:</strong> Please go to the Profit Warden Settings page and enable Data Sync before using this feature.</p></div></div>';
                return;
            }
            $api_url = $settings['api_url'] ?? 'https://api.beralabs.it/calculate-profit';
            $api_url_base = rtrim(preg_replace('/\\/[^\\/]+$/', '', $api_url), '/');
            $api_key = $settings['api_key'] ?? '';
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $callback_url = $api_url_base . '/meta-oauth-callback';
            $return_url = admin_url('admin.php?page=profit-warden&tab=ads_integration&meta_connected=1');
            $oauth_start = $api_url_base . '/meta-oauth-start?site_id=' . urlencode($site_id) . '&redirect_uri=' . urlencode($callback_url) . '&api_key=' . urlencode($api_key) . '&return_url=' . urlencode($return_url);
            $meta_account_id = get_option('profwabr_meta_ad_account_id', '');
            // Dynamically check Meta connection status with FastAPI
            $meta_connected = false;
            if ($api_key) {
                $check_resp = wp_remote_get($api_url_base . '/check-meta?site_id=' . urlencode($site_id), [
                    'headers' => [
                        'X-API-Key' => $api_key,
                    ],
                    'timeout' => 5,
                ]);
                if (!is_wp_error($check_resp) && wp_remote_retrieve_response_code($check_resp) === 200) {
                    $body = json_decode(wp_remote_retrieve_body($check_resp), true);
                    if (!empty($body['connected'])) {
                        $meta_connected = true;
                        update_option('profwabr_meta_token_saved', true);
                    } else {
                        update_option('profwabr_meta_token_saved', false);
                    }
                } else {
                    // Fallback to local option if API is unreachable
                    $meta_connected = get_option('profwabr_meta_token_saved', false);
                }
            }
            // Handle Ad Account ID save
            if (isset($_POST['profwabr_meta_ad_account_id']) && check_admin_referer('profwabr_save_meta_account', 'profwabr_meta_nonce')) {
                $account_id = sanitize_text_field(wp_unslash($_POST['profwabr_meta_ad_account_id']));
                update_option('profwabr_meta_ad_account_id', $account_id);
                wp_remote_post($api_url_base . '/save-integrations', [
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'X-API-Key' => $api_key,
                    ],
                    'body' => wp_json_encode([
                        'site_id' => $site_id,
                        'meta_ad_account_id' => $account_id,
                    ]),
                    'timeout' => 10,
                ]);
                $meta_account_id = $account_id;
                echo '<div class="notice notice-success is-dismissible"><p>&#x2705; Ad Account ID saved!</p></div>';
            }
            // OAuth feedback via querystring
            if (isset($_GET['meta_connected']) && $_GET['meta_connected'] === '1') {
                update_option('profwabr_meta_token_saved', true);
                $meta_connected = true;
                echo '<div class="notice notice-success is-dismissible"><p>&#x2705; Meta Ads connected successfully! The access token has been saved.</p></div>';
            } elseif (isset($_GET['meta_error'])) {
                echo '<div class="notice notice-error is-dismissible"><p>&#x274C; Meta OAuth error: ' . esc_html(urldecode(sanitize_text_field(wp_unslash($_GET['meta_error'])))) . '</p></div>';
            }
            ?>
                    <div class="wrap">
                        <h1>&#x1F4CA; Profit Warden &mdash; Ads Integration</h1>

                        <div style="background:#fff; border:1px solid #ccd0d4; padding:24px; margin-top:20px; border-radius:4px; max-width:680px;">
                            <h2 style="margin-top:0;">&#x1F7E6; Meta Ads</h2>
                            <p>Connect Meta Ads to automatically pull daily campaign costs and calculate real ROAS.</p>

                            <?php
                            if ($meta_connected) {
                                ?>
                                    <div style="background:#eaffea; border-left:4px solid #46b450; padding:10px 15px; margin-bottom:18px;">
                                        &#x2705; <strong>Meta Ads connected.</strong> Access token is active.
                                        &nbsp;<a href="<?php
                                        echo esc_url($oauth_start);
                                        ?>" style="font-size:13px;">Re-authorize</a>
                                    </div>
                            <?php
                            } else {
                                ?>
                                    <div style="background:#fff8e1; border-left:4px solid #ffb900; padding:10px 15px; margin-bottom:18px;">
                                        &#x26A0;&#xFE0F; Not connected yet.
                                    </div>
                            <?php
                            }
                            ?>

                            <p><strong>Step 1</strong> &mdash; Enter the Meta <strong>Ad Account ID</strong>
                               <small style="color:#666;">(format: <code>act_123456789</code> or just the number)</small>:</p>
                            <form method="post" action="">
                                <?php
                                wp_nonce_field('profwabr_save_meta_account', 'profwabr_meta_nonce');
                                ?>
                                <input type="text"
                                       name="profwabr_meta_ad_account_id"
                                       value="<?php
                                       echo esc_attr($meta_account_id);
                                       ?>"
                                       placeholder="act_123456789"
                                       style="width:320px;" />
                                <?php
                                submit_button(
                                    '&#x1F4BE; Save Account ID',
                                    'secondary',
                                    'submit',
                                    false
                                );
                                ?>
                            </form>

                            <p style="margin-top:22px;"><strong>Step 2</strong> &mdash; Authorize Profit Warden to read your campaigns:</p>
                            <a href="<?php
                            echo esc_url($oauth_start);
                            ?>"
                               class="button button-primary"
                               style="font-size:14px; height:36px; line-height:36px; padding:0 18px;">
                                &#x1F517; Connect Meta Ads Account
                            </a>
                            <p style="color:#666; font-size:12px; margin-top:8px;">
                                You will be redirected to Meta to grant read access to your ad campaigns. After authorization you'll return here automatically.
                            </p>
                        </div>

                        <div style="background:#f8f8f8; border:1px solid #ccd0d4; padding:24px; margin-top:20px; border-radius:4px; max-width:680px; opacity:0.65;">
                            <h2 style="margin-top:0;">&#x1F7E5; Google Ads <span style="font-size:13px; font-weight:normal; color:#888;">(Coming Soon)</span></h2>
                            <p>Google Ads integration is planned for a future release.</p>
                        </div>

                        <div id="profwabr-dashboard-app" class="profwabr-ads-dashboard-app" style="margin-top: 30px;">
                            <div class="profwabr-dashboard-header">
                                <h2>📊 Ads Performance Dashboard</h2>
                                <p>Track your campaign performance and real ROAS across all connected platforms.</p>
                            </div>
                
                            <div class="profwabr-refresh-row">
                                <select id="profwabr-ads-range-selector">
                                    <option value="7">Last 7 Days</option>
                                    <option value="30" selected>Last 30 Days</option>
                                    <option value="90">Last 90 Days</option>
                                    <option value="365">Last Year</option>
                                </select>
                                <button id="profwabr-refresh-ads-dashboard">🔄 Refresh Ads Stats</button>
                            </div>

                            <div class="profwabr-stats-grid" id="profwabr-ads-metrics">
                                <div class="profwabr-stat-card"><div class="profwabr-stat-label">Total Spend</div><div class="profwabr-stat-value" id="ads-val-spend">-- €</div></div>
                                <div class="profwabr-stat-card"><div class="profwabr-stat-label">Att. Orders</div><div class="profwabr-stat-value" id="ads-val-orders">--</div></div>
                                <div class="profwabr-stat-card"><div class="profwabr-stat-label">Att. Revenue</div><div class="profwabr-stat-value" id="ads-val-revenue">-- €</div></div>
                                <div class="profwabr-stat-card"><div class="profwabr-stat-label">Global ROAS</div><div class="profwabr-stat-value" id="ads-val-roas">--</div></div>
                            </div>

                            <div class="profwabr-rankings-grid" style="grid-template-columns: 1fr;">
                                <div class="profwabr-ranking-card">
                                    <div class="profwabr-ranking-title"><span>📢</span> Campaigns Summary</div>
                                    <div class="profwabr-table-container" id="list-ad-campaigns">
                                        <p style="color: var(--profwabr-text-muted);">Loading campaign data...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php
        }

        // end profwabr_ads_page
        // Helper per renderizzare la tabella dei check
        function profwabr_render_config_table()
        {
            $results = profwabr_run_config_check();
            echo '<table class="profwabr-config-table">
                <thead>
                    <tr>
                        <th>Parametro</th>
                        <th>Stato</th>
                        <th>Dettaglio</th>
                    </tr>
                </thead>
                <tbody>';
            foreach ($results as $r) {
                $badge_class = "profwabr-status-" . $r['status'];
                echo '<tr>
                    <td><strong>' . esc_html($r['label']) . '</strong></td>
                    <td><span class="profwabr-status-badge ' . esc_attr($badge_class) . '">' . esc_html($r['status']) . '</span></td>
                    <td>' . wp_kses_post($r['detail']) . '</td>
                  </tr>';
            }
            echo '</tbody></table>';
        }

        // Handler AJAX per il refresh del check
        add_action('wp_ajax_profwabr_ajax_config_check', 'profwabr_ajax_config_check_handler');
        function profwabr_ajax_config_check_handler()
        {
            check_ajax_referer('profwabr_report_nonce');
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Permesso negato');
            }
            ob_start();
            profwabr_render_config_table();
            $html = ob_get_clean();
            wp_send_json_success($html);
        }

        // --- LOGICA PER REPORT PERIODICI (CRON) ---
        // 1. Aggiunge intervalli di tempo personalizzati per WP-Cron
        add_filter('cron_schedules', 'profwabr_add_cron_schedules');
        function profwabr_add_cron_schedules($schedules)
        {
            if (!isset($schedules['weekly'])) {
                $schedules['weekly'] = [
                    'interval' => 604800,
                    'display' => esc_html__('Once Weekly', 'profit-warden'),
                ];
            }
            if (!isset($schedules['monthly'])) {
                $schedules['monthly'] = [
                    'interval' => 2592000,
                    'display' => esc_html__('Once a month', 'profit-warden'),
                ];
            }
            return $schedules;
        }

        // 2. Funzioni per attivazione/disattivazione e aggiornamento
        register_activation_hook(__FILE__, 'profwabr_plugin_activation');
        function profwabr_plugin_activation()
        {
            profwabr_schedule_cron_from_settings();
            // Imposta il flag per il redirect al setup wizard dopo l'attivazione
            set_transient('profwabr_activation_redirect', true, 30);
        }

        register_deactivation_hook(__FILE__, 'profwabr_plugin_deactivation');
        function profwabr_plugin_deactivation()
        {
            $timestamp = wp_next_scheduled('profwabr_periodic_report_event');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'profwabr_periodic_report_event');
            }
        }

        add_action(
            'update_option_profwabr_settings',
            'profwabr_reschedule_cron_on_settings_update',
            10,
            2
        );
        function profwabr_reschedule_cron_on_settings_update($old_value, $new_value)
        {
            profwabr_schedule_cron_from_settings();
        }

        // 3. Funzione centralizzata per (ri)programmare il cron
        function profwabr_schedule_cron_from_settings()
        {
            $opts = profwabr_get_settings();
            $frequency = (isset($opts['report_frequency']) ? $opts['report_frequency'] : 'disabled');
            $timestamp = wp_next_scheduled('profwabr_periodic_report_event');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'profwabr_periodic_report_event');
            }
            if ($frequency !== 'disabled') {
                wp_schedule_event(strtotime('tomorrow midnight'), $frequency, 'profwabr_periodic_report_event');
            }
        }

        // 4. La funzione che viene eseguita dal cron
        add_action('profwabr_periodic_report_event', 'profwabr_execute_periodic_report');
        function profwabr_execute_periodic_report()
        {
            $opts = profwabr_get_settings();

            // Check opt-in consent before proceeding
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                return;
            }

            $frequency = (isset($opts['report_frequency']) ? $opts['report_frequency'] : 'disabled');
            if ($frequency === 'disabled') {
                return;
            }
            $end_date = wp_date('Y-m-d', strtotime('yesterday'));
            if ($frequency === 'daily') {
                $start_date = $end_date;
            } elseif ($frequency === 'weekly') {
                $start_date = wp_date('Y-m-d', strtotime('-6 days', strtotime($end_date)));
            } elseif ($frequency === 'monthly') {
                $start_date = wp_date('Y-m-d', strtotime('-1 month +1 day', strtotime($end_date)));
            } else {
                return;
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            $report_url = str_replace('/calculate-profit', '/send-report', $api_url);
            $email = (!empty($opts['report_email']) ? $opts['report_email'] : get_option('admin_email'));
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $payload = [
                'email' => $email,
                'site_id' => $site_id,
                'start_date' => $start_date,
                'end_date' => $end_date,
            ];
            $response = wp_remote_post($report_url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'X-API-Key' => $api_key,
                ],
                'body' => json_encode($payload),
                'timeout' => 30,
            ]);
            if (defined('WP_DEBUG') && WP_DEBUG) {
                if (is_wp_error($response)) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                    error_log('Profit Warden Cron Error: ' . $response->get_error_message());
                } elseif (wp_remote_retrieve_response_code($response) !== 200) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                    error_log('Profit Warden Cron API Error: Code ' . wp_remote_retrieve_response_code($response));
                }
            }
        }

        // </fs_premium_only>
        // AJAX Handler per invio report
        add_action('wp_ajax_profwabr_send_report', 'profwabr_handle_send_report');
        function profwabr_handle_send_report()
        {
            check_ajax_referer('profwabr_report_nonce');
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Permission denied');
            }
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                wp_send_json_error('Data Sync Consent is not enabled. Please enable it in Settings.');
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            // Costruiamo l'URL per il report sostituendo l'endpoint finale
            $report_url = str_replace('/calculate-profit', '/send-report', $api_url);
            $email = (!empty($opts['report_email']) ? $opts['report_email'] : get_option('admin_email'));
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $response = wp_remote_post($report_url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'X-API-Key' => $api_key,
                ],
                'body' => json_encode([
                    'email' => $email,
                    'site_id' => $site_id,
                ]),
                'timeout' => 15,
            ]);
            if (is_wp_error($response)) {
                wp_send_json_error('Connection error: ' . $response->get_error_message());
            }
            $code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if ($code == 200) {
                wp_send_json_success($body['message'] ?? 'Report request sent successfully!');
            } else {
                wp_send_json_error('API Error: ' . ($body['detail'] ?? 'Code ' . $code));
            }
        }

        // AJAX Handler per TEST SMTP
        add_action('wp_ajax_profwabr_test_smtp', 'profwabr_handle_test_smtp');
        function profwabr_handle_test_smtp()
        {
            check_ajax_referer('profwabr_report_nonce');
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Permission denied');
            }
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                wp_send_json_error('Data Sync Consent is not enabled. Please enable it in Settings.');
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            $test_url = str_replace('/calculate-profit', '/test-smtp', $api_url);
            $email = (!empty($opts['report_email']) ? $opts['report_email'] : get_option('admin_email'));
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $response = wp_remote_post($test_url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'X-API-Key' => $api_key,
                ],
                'body' => json_encode([
                    'email' => $email,
                    'site_id' => $site_id,
                ]),
                'timeout' => 10,
            ]);
            if (is_wp_error($response)) {
                wp_send_json_error('Connection error: ' . $response->get_error_message());
            }
            $code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if ($code == 200) {
                wp_send_json_success('Test OK: ' . ($body['message'] ?? 'Email sent'));
            } else {
                wp_send_json_error('Error: ' . ($body['detail'] ?? 'Code ' . $code));
            }
        }

        // AJAX Handler per riepilogo Ads
        add_action('wp_ajax_profwabr_get_ad_summary', 'profwabr_get_ad_summary_handler');
        function profwabr_get_ad_summary_handler()
        {
            check_ajax_referer('profwabr_report_nonce');
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Permission denied');
            }
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                wp_send_json_error('Data Sync Consent is not enabled.');
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $days = (isset($_POST['days']) ? (int) $_POST['days'] : 30);
            // Costruiamo l'URL per l'endpoint ad-summary
            $api_url_base = rtrim(preg_replace('/\\/[^\\/]+$/', '', $api_url), '/');
            $ad_summary_url = add_query_arg([
                'site_id' => $site_id,
                'days' => $days,
            ], $api_url_base . '/ad-summary');
            $response = wp_remote_get($ad_summary_url, [
                'headers' => [
                    'X-API-Key' => $api_key,
                ],
                'timeout' => 15,
            ]);
            if (is_wp_error($response)) {
                wp_send_json_error('Connection error: ' . $response->get_error_message());
            }
            $code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if ($code == 200) {
                wp_send_json_success($body);
            } else {
                wp_send_json_error('API Error: ' . ($body['detail'] ?? 'Code ' . $code));
            }
        }

        // AJAX Handler per dati Dashboard
        add_action('wp_ajax_profwabr_get_dashboard_data', 'profwabr_get_dashboard_data_handler');
        function profwabr_get_dashboard_data_handler()
        {
            check_ajax_referer('profwabr_report_nonce');
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Permission denied');
            }
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                wp_send_json_error('API Sync consent is missing. Please enable it in Settings.');
                return;
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $days = (isset($_POST['days']) ? (int) $_POST['days'] : 30);
            // Costruiamo l'URL per la dashboard
            $dashboard_url = str_replace('/calculate-profit', '/dashboard-data', $api_url);
            // Aggiungiamo i parametri query
            $dashboard_url = add_query_arg([
                'site_id' => $site_id,
                'days' => $days,
            ], $dashboard_url);
            $response = wp_remote_get($dashboard_url, [
                'headers' => [
                    'X-API-Key' => $api_key,
                ],
                'timeout' => 15,
            ]);
            if (is_wp_error($response)) {
                wp_send_json_error('Connection error: ' . $response->get_error_message());
            }
            $code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if ($code == 200) {
                $fixed_total = 0.0;
                $fixed_fields = [
                    'fixed_hosting',
                    'fixed_saas',
                    'fixed_marketing',
                    'fixed_salaries',
                    'fixed_rent',
                    'fixed_insurance',
                    'fixed_accounting',
                    'fixed_other'
                ];
                foreach ($fixed_fields as $f) {
                    if (isset($opts[$f])) {
                        $fixed_total += (float) $opts[$f];
                    }
                }
                $body['fixed_costs_monthly'] = $fixed_total;
                wp_send_json_success($body);
            } else {
                wp_send_json_error('API Error: ' . ($body['detail'] ?? 'Code ' . $code));
            }
        }

        // 1. CAMPI PERSONALIZZATI (Rimangono uguali)
        // Aggiunge il campo "Costo Vivo" ai metodi di spedizione
        function profwabr_add_cost_field_to_shipping_methods($form_fields)
        {
            $form_fields['profwabr_real_cost'] = array(
                'title' => 'Actual Cost (€)',
                'type' => 'text',
                'description' => 'Actual cost for the store.',
                'default' => '0.00',
                'placeholder' => 'Ex: 6.50',
            );
            return $form_fields;
        }

        add_filter('woocommerce_shipping_instance_form_fields_flat_rate', 'profwabr_add_cost_field_to_shipping_methods');
        add_filter('woocommerce_shipping_instance_form_fields_free_shipping', 'profwabr_add_cost_field_to_shipping_methods');
        // Aggiunge il campo "Costo Acquisto" nella scheda prodotto
        function profwabr_add_purchase_cost_field()
        {
            echo '<div class="options_group">';
            wp_nonce_field('profwabr_save_product_meta', 'profwabr_nonce');
            // Security Nonce
            woocommerce_wp_text_input(array(
                'id' => '_purchase_cost',
                'label' => 'Purchase Cost (€)',
                'type' => 'number',
                'custom_attributes' => array(
                    'step' => '0.01',
                ),
            ));
            echo '</div>';
        }

        add_action('woocommerce_product_options_general_product_data', 'profwabr_add_purchase_cost_field');
        // Salva il campo "Costo Acquisto" con controlli di sicurezza
        function profwabr_save_purchase_cost_field($post_id)
        {
            // Verifica il nonce, l'autosave e i permessi
            if (!isset($_POST['profwabr_nonce']) || !wp_verify_nonce(sanitize_key($_POST['profwabr_nonce']), 'profwabr_save_product_meta') || defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || !current_user_can('edit_product', $post_id)) {
                return;
            }
            if (isset($_POST['_purchase_cost'])) {
                update_post_meta($post_id, '_purchase_cost', sanitize_text_field(wp_unslash($_POST['_purchase_cost'])));
            }
        }

        add_action('woocommerce_process_product_meta', 'profwabr_save_purchase_cost_field');
        // 2. LOGICA DI RECUPERO DATI (Funzione centrale)
        // $refund_data: array opzionale con [ 'amount' => float, 'type' => string, 'note' => string ]
        function profwabr_call_python_analysis($order, $refund_data = null)
        {
            // Recupera le impostazioni salvate (o usa i default)
            $opts = profwabr_get_settings();
            if (empty($opts['enable_api_sync']) || $opts['enable_api_sync'] !== '1') {
                return false;
            }
            $api_url = (!empty($opts['api_url']) ? $opts['api_url'] : 'https://api.beralabs.it/calculate-profit');
            $api_key = (!empty($opts['api_key']) ? $opts['api_key'] : '');
            $site_id = preg_replace('/^https?:\\/\\//i', '', get_site_url());
            $cost_packaging = (isset($opts['packaging_cost']) ? (float) $opts['packaging_cost'] : 0.8);
            $cost_ship_def = (isset($opts['default_shipping']) ? (float) $opts['default_shipping'] : 5.0);
            $fee_paypal = (isset($opts['paypal_fixed']) ? (float) $opts['paypal_fixed'] : 0.35);
            $fee_stripe = (isset($opts['stripe_fixed']) ? (float) $opts['stripe_fixed'] : 0.25);
            $fee_cod = (isset($opts['cod_fixed']) ? (float) $opts['cod_fixed'] : 3.0);
            // FIX: Default a '1' se non settato, per garantire che gli alert siano attivi dopo l'update
            $enable_alerts = (isset($opts['enable_loss_alerts']) ? $opts['enable_loss_alerts'] : '1');
            $enable_breakeven_alerts = (isset($opts['enable_breakeven_alerts']) ? $opts['enable_breakeven_alerts'] : '1');
            $report_email = (!empty($opts['report_email']) ? $opts['report_email'] : get_option('admin_email'));
            $fixed_total = 0.0;
            $fixed_fields = [
                'fixed_hosting',
                'fixed_saas',
                'fixed_marketing',
                'fixed_salaries',
                'fixed_rent',
                'fixed_insurance',
                'fixed_accounting',
                'fixed_other'
            ];
            foreach ($fixed_fields as $f) {
                if (isset($opts[$f])) {
                    $fixed_total += (float) $opts[$f];
                }
            }
            $items = [];
            foreach ($order->get_items() as $item) {
                $p_id = $item->get_product_id();
                $qty = max(1, (int) $item->get_quantity());
                // FIX: Recupero la percentuale IVA reale (es. 22)
                $tax_rate = 0.0;
                $item_taxes = $item->get_taxes();
                // Recupera le tasse applicate a questo item
                foreach ($item_taxes as $rate_id => $amount) {
                    $rate_data = WC_Tax::_get_tax_rate($rate_id);
                    if (isset($rate_data['tax_rate'])) {
                        $tax_rate += (float) $rate_data['tax_rate'];
                    }
                }
                // Calcolo importo IVA unitario post-sconto
                $vat_amount = (float) $item->get_total_tax() / $qty;
                // Prezzo netto post-sconto (tiene conto dei codici sconto applicati)
                $price_net = (float) $item->get_total() / $qty;
                // Fallback: Se l'importo è 0 ma c'è un'aliquota (es. 22%), calcoliamo l'IVA manualmente
                if ($vat_amount <= 0.001 && $tax_rate > 0) {
                    $vat_amount = $price_net * ($tax_rate / 100);
                }
                // FIX: Recupero costo acquisto con fallback al prodotto padre per le varianti
                $purchase_cost = (float) get_post_meta($p_id, '_purchase_cost', true);
                if ($purchase_cost <= 0 && $item->get_variation_id() > 0) {
                    // Se è una variante e non ha costo, controlliamo il padre
                    $parent_id = $item->get_product()->get_parent_id();
                    $purchase_cost = (float) get_post_meta($parent_id, '_purchase_cost', true);
                }
                $items[] = [
                    'sku' => ($item->get_product() ? $item->get_product()->get_sku() : 'ID-' . $p_id),
                    'product_id' => (string) $p_id,
                    'product_name' => $item->get_name(),
                    'qty' => $qty,
                    'price_net' => $price_net,
                    'vat' => $vat_amount,
                    'vat_percentage' => $tax_rate,
                    'purchase_cost' => ($purchase_cost ?: 0),
                ];
            }
            // Recupero Costo Spedizione Reale
            $shipping_real_cost = 0.0;
            foreach ($order->get_shipping_methods() as $item) {
                $instance_id = $item->get_instance_id();
                $method_id = $item->get_method_id();
                $option_key = ($instance_id ? "woocommerce_{$method_id}_{$instance_id}_settings" : "woocommerce_{$method_id}_settings");
                $settings = get_option($option_key);
                $shipping_real_cost += (isset($settings['profwabr_real_cost']) && $settings['profwabr_real_cost'] !== '' ? (float) $settings['profwabr_real_cost'] : $cost_ship_def);
            }
            $method = $order->get_payment_method();
            $total = $order->get_total();
            // Recupero parametri di tracciamento marketing
            $tracking = [
                'utm_source' => $order->get_meta('_profwabr_track_utm_source', true),
                'utm_medium' => $order->get_meta('_profwabr_track_utm_medium', true),
                'utm_campaign' => $order->get_meta('_profwabr_track_utm_campaign', true),
                'fbclid' => $order->get_meta('_profwabr_track_fbclid', true),
                'gclid' => $order->get_meta('_profwabr_track_gclid', true),
            ];
            // Calcolo Fee migliorato (supporta varianti comuni di ID gateway)
            $fee = 0.0;
            if (strpos($method, 'paypal') !== false) {
                $fee = $total * 0.034 + $fee_paypal;
            } elseif (strpos($method, 'stripe') !== false || strpos($method, 'credit_card') !== false) {
                $fee = $total * 0.014 + $fee_stripe;
            } elseif ($method === 'cod') {
                $fee = $fee_cod;
            }
            $payload = [
                'site_id' => $site_id,
                'order_id' => (string) $order->get_id(),
                'created_at' => ($order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : current_time('mysql', true)),
                'order_status' => $order->get_status(),
                'customer' => [
                    'email' => $order->get_billing_email(),
                    'first_name' => $order->get_billing_first_name(),
                    'last_name' => $order->get_billing_last_name(),
                ],
                'items' => $items,
                'shipping' => [
                    'customer_paid' => (float) $order->get_shipping_total(),
                    'actual_cost' => $shipping_real_cost,
                    'packaging_fixed' => $cost_packaging,
                    'vat' => (float) $order->get_shipping_tax(),
                ],
                'payment' => [
                    'method' => $method,
                    'gateway_fee_est' => (float) $fee,
                ],
                'discount_total' => (float) $order->get_total_discount(),
                'promo_codes' => implode(', ', $order->get_coupon_codes()),
                'tracking' => $tracking,
            ];
            if ($enable_alerts === '1' || $enable_breakeven_alerts === '1') {
                $payload['alert_email'] = $report_email;
            }
            $payload['breakeven_alert_enabled'] = $enable_breakeven_alerts === '1';
            $payload['fixed_costs_monthly'] = $fixed_total;
            // --- AGGIUNGI DATI RIMBORSO MANUALE (se presenti) ---
            if ($refund_data && isset($refund_data['amount']) && $refund_data['amount'] > 0) {
                $payload['refund_amount'] = (float) $refund_data['amount'];
                $payload['refund_type'] = $refund_data['type'] ?? 'partial';
                $payload['refund_note'] = $refund_data['note'] ?? '';
            }
            // Invio a Python (senza bloccare il checkout se fallisce)
            $res = wp_remote_post($api_url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'X-API-Key' => $api_key,
                ],
                'body' => json_encode($payload),
                'timeout' => 5,
                'blocking' => true,
            ]);
            if (is_wp_error($res)) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                    error_log('PW Error: ' . $res->get_error_message());
                }
                return false;
            }
            // Controllo codice di risposta HTTP (es. 200 OK)
            $code = wp_remote_retrieve_response_code($res);
            if ($code !== 200) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                    error_log('PW API Error Code: ' . $code . ' Body: ' . wp_remote_retrieve_body($res));
                }
                return false;
            }
            $body = wp_remote_retrieve_body($res);
            return json_decode($body, true);
        }

        // 3. VISUALIZZAZIONE BACKEND (Admin)
        function profwabr_display_profit_analysis_box($order)
        {
            // Performance: Cerca prima i dati salvati nei metadati dell'ordine
            $data = $order->get_meta('_profwabr_profit_analysis_data');
            // Se non ci sono dati salvati (o se vogliamo forzare un ricalcolo), chiama l'API
            if (empty($data)) {
                $data = profwabr_call_python_analysis($order);
                if ($data && isset($data['summary'])) {
                    update_post_meta($order->get_id(), '_profwabr_profit_analysis_data', $data);
                }
            }
            // Rilevamento rimborsi sull'ordine per mostrare dati aggiornati nel box
            $total_refunded = (float) $order->get_total_refunded();
            $order_total = (float) $order->get_total();
            $has_refund = $total_refunded > 0;
            $refund_type = ($total_refunded >= $order_total ? 'full' : 'partial');
            echo '<div id="profwabr-box" style="margin-top:20px; padding:15px; background:#fdfdfd; border:1px solid #ddd; border-left:4px solid #007cba;">';
            echo '<h4>🛡️ Profit Warden Analysis</h4>';
            if ($data && isset($data['summary'])) {
                $status = $data['summary']['status'];
                if ($has_refund) {
                    $col = '#856404';
                    // Giallo/arancio per rimborsi
                    $refund_label = ($refund_type === 'full' ? '⚫ RIMBORSATO (TOTALE)' : '🟠 RIMBORSO PARZIALE');
                    echo "<strong style='color:" . esc_attr($col) . "; font-size:1.2em;'>" . esc_html($refund_label) . "</strong><br>";
                    echo "<span style='color:#6c757d; font-size:0.85em;'>⚠️ Rimborso rilevato: <strong>" . esc_html(number_format($total_refunded, 2)) . " €</strong> - Il profitto mostrato potrebbe non riflettere il rimborso. <a href='#' onclick='window.location.reload();'>Ricalcola</a></span><br>";
                } else {
                    $col = (strpos($status, 'PERDITA') !== false ? '#d63638' : '#00a32a');
                    echo "<strong style='color:" . esc_attr($col) . "; font-size:1.2em;'>" . esc_html($status) . "</strong><br>";
                }
                echo "Net Profit: <strong>" . esc_html($data['summary']['net_profit']) . "</strong> | Margin: <strong>" . esc_html($data['summary']['margin_percentage']) . "</strong>";
                $logistics = (isset($data['breakdown']['logistics_impact']) ? $data['breakdown']['logistics_impact'] : 'N/A');
                echo "<p style='font-size:0.8em; color:#888; margin-top:10px;'>Actual logistics: " . esc_html($logistics) . "€</p>";
            } else {
                echo '<p>⚠️ Data not available. The analysis server might be unreachable or costs are not configured.</p>';
            }
            echo '</div>';
            ?>
                <?php
        }

        add_action('woocommerce_admin_order_data_after_order_details', 'profwabr_display_profit_analysis_box');
        // 4. GRILLETTO PER IL FRONTEND (CHECKOUT) E PER I RESI MANUALI
        // --- HOOK PER RIMBORSO MANUALE (creato dall'admin WP) ---
        // Scatta su qualsiasi rimborso creato dal backend WooCommerce, anche se
        // lo stato dell'ordine non cambia (rimborso parziale su ordine 'processing').
        add_action(
            'woocommerce_order_refunded',
            'profwabr_handle_manual_refund',
            10,
            2
        );
        function profwabr_handle_manual_refund($order_id, $refund_id)
        {
            $order = wc_get_order($order_id);
            $refund = wc_get_order($refund_id);
            // WC_Order_Refund object
            if (!$order || !$refund) {
                return;
            }
            // Calcola importo totale rimborsato su questo ordine (può essere cumulativo)
            $total_refunded = (float) $order->get_total_refunded();
            $order_total = (float) $order->get_total();
            // Determina se il rimborso è totale o parziale
            $refund_type = ($total_refunded >= $order_total ? 'full' : 'partial');
            // Recupera il motivo del rimborso (inserito dall'admin nel campo "Motivo")
            $refund_note = (method_exists($refund, 'get_reason') ? $refund->get_reason() : '');
            $refund_data = [
                'amount' => $total_refunded,
                'type' => $refund_type,
                'note' => $refund_note,
            ];
            // Invalida la cache del box analisi per forzare il refresh visivo
            $order->delete_meta_data('_profwabr_profit_analysis_data');
            $order->save_meta_data();
            // Invia subito i dati aggiornati con il rimborso al backend Python
            // (non schedula in background per garantire l'aggiornamento immediato)
            $data = profwabr_call_python_analysis($order, $refund_data);
            if ($data && isset($data['summary'])) {
                $order->update_meta_data('_profwabr_profit_analysis_data', $data);
                $order->save_meta_data();
            }
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log(sprintf(
                    'Profit Warden: Rimborso %s rilevato su ordine #%d. Importo: %.2f€, Tipo: %s',
                    $refund_id,
                    $order_id,
                    $total_refunded,
                    $refund_type
                ));
            }
        }

        // --- HOOK PER CAMBIO STATUS ORDINE (Checkout e resi via status) ---
        // Usiamo hooks legati allo stato dell'ordine per garantire che i dati siano salvati e stabili.
        function profwabr_trigger_on_checkout($order_id)
        {
            // Schedula l'analisi in background per non bloccare il checkout.
            if (function_exists('as_schedule_single_action')) {
                as_schedule_single_action(time(), 'profwabr_run_background_analysis', array(
                    'order_id' => $order_id,
                ));
            }
        }

        // Scatta quando l'ordine passa a "In lavorazione" (pagamento ok o contrassegno)
        add_action(
            'woocommerce_order_status_processing',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        // Scatta quando l'ordine passa a "In attesa" (es. bonifico bancario)
        add_action(
            'woocommerce_order_status_on-hold',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        // Scatta al completamento
        add_action(
            'woocommerce_order_status_completed',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        // Scatta per resi via cambio stato e annullamenti
        add_action(
            'woocommerce_order_status_refunded',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        add_action(
            'woocommerce_order_status_cancelled',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        add_action(
            'woocommerce_order_status_failed',
            'profwabr_trigger_on_checkout',
            10,
            1
        );
        // Scatta quando un ordine viene aggiornato o salvato (backend admin)
        add_action(
            'woocommerce_update_order',
            'profwabr_trigger_on_update',
            10,
            2
        );
        function profwabr_trigger_on_update($order_id, $order)
        {
            if (function_exists('as_schedule_single_action') && function_exists('as_next_scheduled_action')) {
                // Evita di schedulare chiamate multiple ravvicinate
                if (
                    false === as_next_scheduled_action('profwabr_run_background_analysis', array(
                        'order_id' => $order_id,
                    ))
                ) {
                    as_schedule_single_action(time(), 'profwabr_run_background_analysis', array(
                        'order_id' => $order_id,
                    ));
                }
            }
        }

        // Funzione eseguita in background da Action Scheduler
        add_action(
            'profwabr_run_background_analysis',
            'profwabr_execute_background_analysis',
            10,
            1
        );
        function profwabr_execute_background_analysis($order_id)
        {
            $order = wc_get_order($order_id);
            if ($order) {
                // Recupera rimborso esistente sull'ordine (per sincronizzare anche in background)
                $total_refunded = (float) $order->get_total_refunded();
                $refund_data = null;
                if ($total_refunded > 0) {
                    $order_total = (float) $order->get_total();
                    $refund_data = [
                        'amount' => $total_refunded,
                        'type' => ($total_refunded >= $order_total ? 'full' : 'partial'),
                        'note' => '',
                    ];
                }
                $data = profwabr_call_python_analysis($order, $refund_data);
                if ($data && isset($data['summary'])) {
                    $order->update_meta_data('_profwabr_profit_analysis_data', $data);
                    $order->save_meta_data();
                }
            }
        }

        // Svuota la cache di Profit Warden e ricalcola quando si modificano gli articoli dal backend
        add_action(
            'woocommerce_saved_order_items',
            'profwabr_clear_analysis_cache',
            10,
            2
        );
        function profwabr_clear_analysis_cache($order_id, $items)
        {
            $order = wc_get_order($order_id);
            if ($order) {
                $order->delete_meta_data('_profwabr_profit_analysis_data');
                $order->save_meta_data();
                if (function_exists('as_schedule_single_action') && function_exists('as_next_scheduled_action')) {
                    if (
                        false === as_next_scheduled_action('profwabr_run_background_analysis', array(
                            'order_id' => $order_id,
                        ))
                    ) {
                        as_schedule_single_action(time(), 'profwabr_run_background_analysis', array(
                            'order_id' => $order_id,
                        ));
                    }
                }
            }
        }

    }
}