<?php
if (!defined('ABSPATH')) exit;

class W5E_Settings
{
    private static $pricing_styles_printed = false;
    private static $did_save = false;

    public static function init()
    {
        add_action('admin_enqueue_scripts', [__CLASS__, 'assets']);
        add_action('wp_ajax_w5e_fetch_couriers', [__CLASS__, 'ajax_fetch_couriers']);
        add_action('wp_ajax_w5e_fetch_warehouses', [__CLASS__, 'ajax_fetch_warehouses']);
        add_filter('woocommerce_get_sections_shipping', [__CLASS__, 'register_section']);
        add_filter('woocommerce_get_settings_shipping', [__CLASS__, 'register_settings'], 10, 2);
        add_action('woocommerce_update_options_shipping_w5e', [__CLASS__, 'save_settings']);
        add_action('woocommerce_update_options_shipping', [__CLASS__, 'maybe_save_settings_fallback'], 9);
        add_action('woocommerce_admin_field_w5e_courier_table', [__CLASS__, 'render_courier_table_field']);
        add_action('woocommerce_admin_field_w5e_warehouses', [__CLASS__, 'render_warehouses_field']);
        add_action('woocommerce_admin_field_w5e_pricing_matrix', [__CLASS__, 'render_pricing_matrix_field']);

        if (get_option('w5e_pricing_matrix', null) === null) {
            add_option('w5e_pricing_matrix', self::get_default_pricing_matrix(), false);
        }
    }

    public static function assets($hook)
    {
        if ($hook !== 'woocommerce_page_wc-settings') return;
        $tab     = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : '';
        if ($tab !== 'shipping') {
            return;
        }
        $admin_ver = file_exists(W5E_PATH . 'assets/admin.js') ? filemtime(W5E_PATH . 'assets/admin.js') : W5E_VER;
        wp_enqueue_script('w5e-admin', W5E_URL . 'assets/admin.js', ['jquery'], $admin_ver, true);
        wp_localize_script('w5e-admin', 'W5E', [
            'ajax' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('w5e_fetch'),
            'i18n' => [
                'methodTitle' => __('5E Shipping', 'woo-5e'),
                'fetching'     => __('Working…', 'woo-5e'),
                'success'      => __('Done: %d couriers cached. Save the settings page to refresh the table.', 'woo-5e'),
                'successWarehouses' => __('Done: %d warehouses cached. Save the settings page to refresh the list.', 'woo-5e'),
                'errorPrefix'  => __('Error:', 'woo-5e'),
                'unknownError' => __('Unknown', 'woo-5e'),
                'requestError' => __('Request failed.', 'woo-5e'),
            ],
        ]);
    }

    public static function register_section($sections)
    {
        $sections['w5e'] = __('5E Shipping', 'woo-5e');
        return $sections;
    }

    public static function register_settings($settings, $current_section)
    {
        if ($current_section !== 'w5e') {
            return $settings;
        }

        self::ensure_shipping_method_linked();
        return self::get_settings_fields();
    }

    public static function ajax_fetch_couriers()
    {
        check_ajax_referer('w5e_fetch', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => __('Not allowed.', 'woo-5e')]);
        }

        $id  = get_option('w5e_id', '');
        $key = get_option('w5e_api_key', '');
        if (!$id || !$key) {
            wp_send_json_error(['message' => __('Enter 5E ID and API Key before fetching.', 'woo-5e')]);
        }

        try {
            $api  = new W5E_API();
            $list = $api->get_company_couriers_by_credentials($id, $key);

            $cache = [];
            if (is_array($list)) {
                foreach ($list as $item) {
                    $pid  = isset($item['PartnerID']) ? intval($item['PartnerID']) : 0;
                    $name = isset($item['CourierName']) ? (string)$item['CourierName'] : '';
                    if ($pid && $name) {
                        if (!empty($item['Production'])) {
                            $cache[] = ['PartnerID' => $pid, 'CourierName' => $name, 'Env' => 'Production'];
                        }
                        if (!empty($item['Test'])) {
                            $cache[] = ['PartnerID' => $pid, 'CourierName' => $name, 'Env' => 'Test'];
                        }
                    }
                }
            }
            update_option('w5e_couriers_cache', $cache, false);
            wp_send_json_success(['count' => count($cache)]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }
    }

    public static function ajax_fetch_warehouses()
    {
        check_ajax_referer('w5e_fetch', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => __('Not allowed.', 'woo-5e')]);
        }

        $id  = get_option('w5e_id', '');
        $key = get_option('w5e_api_key', '');
        if (!$id || !$key) {
            wp_send_json_error(['message' => __('Enter 5E ID and API Key before fetching.', 'woo-5e')]);
        }

        try {
            $api  = new W5E_API();
            $list = $api->get_warehouses_by_client_credentials($id, $key);

            $cache = [];
            if (is_array($list)) {
                foreach ($list as $item) {
                    if (!is_array($item)) {
                        continue;
                    }

                    $warehouseId = isset($item['WarehouseID']) ? sanitize_text_field($item['WarehouseID']) : '';
                    if ($warehouseId === '') {
                        continue;
                    }

                    $clientWarehouseId = isset($item['ClientWarehouseID']) ? sanitize_text_field($item['ClientWarehouseID']) : '';
                    $street            = isset($item['WarehouseAddress']) ? sanitize_text_field($item['WarehouseAddress']) : '';
                    $houseNumberRaw    = $item['WarehouseHouseNumber'] ?? '';
                    $houseNumber       = $houseNumberRaw !== null ? sanitize_text_field((string)$houseNumberRaw) : '';
                    $address           = trim($street . ($houseNumber !== '' ? ' ' . $houseNumber : ''));

                    $cache[] = [
                        'WarehouseID'          => $warehouseId,
                        'ClientWarehouseID'    => $clientWarehouseId !== '' ? $clientWarehouseId : $warehouseId,
                        'CompanyID'            => isset($item['CompanyID']) ? absint($item['CompanyID']) : 0,
                        'WarehouseStatus'      => !empty($item['WarehouseStatus']),
                        'WarehouseBankAccount' => isset($item['WarehouseBankAccount']) ? sanitize_text_field($item['WarehouseBankAccount']) : '',
                        'WarehouseName'        => isset($item['WarehouseName']) ? sanitize_text_field($item['WarehouseName']) : '',
                        'WarehouseTown'        => isset($item['WarehouseTown']) ? sanitize_text_field($item['WarehouseTown']) : (isset($item['WarehouseMunicipality']) ? sanitize_text_field($item['WarehouseMunicipality']) : ''),
                        'WarehouseAddress'     => $address,
                        'IsDefault'            => !empty($item['IsDefault']),
                    ];
                }
            }

            update_option('w5e_warehouses_cache', $cache, false);
            wp_send_json_success(['count' => count($cache)]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }
    }

    public static function save_settings()
    {
        if (self::$did_save) {
            return;
        }
        self::$did_save = true;

        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        if (!class_exists('WC_Admin_Settings')) {
            return;
        }

        $enabled_raw = $_POST['w5e_enabled_partners'] ?? [];
        if (is_array($enabled_raw)) {
            $enabled_raw = wp_unslash($enabled_raw);
        } else {
            $enabled_raw = [];
        }

        $default_key = isset($_POST['w5e_default_partner']) ? sanitize_text_field((string)wp_unslash($_POST['w5e_default_partner'])) : '';
        $pricing_raw = $_POST['w5e_pricing_matrix'] ?? [];
        if (is_array($pricing_raw)) {
            $pricing_raw = wp_unslash($pricing_raw);
        } else {
            $pricing_raw = [];
        }

        if ($default_key !== '' && !isset($enabled_raw[$default_key])) {
            $enabled_raw[$default_key] = ['enabled' => 'on'];
        }

        $defaultWarehouseRaw = $_POST['w5e_default_warehouse_id'] ?? [];
        if (is_array($defaultWarehouseRaw)) {
            $defaultWarehouseRaw = wp_unslash($defaultWarehouseRaw);
        }

        $shipmentContentRaw = isset($_POST['w5e_shipment_content']) ? sanitize_text_field((string) wp_unslash($_POST['w5e_shipment_content'])) : '';
        if ($shipmentContentRaw === '') {
            WC_Admin_Settings::add_error(__('Shipment Content is required.', 'woo-5e'));
            $_POST['w5e_shipment_content'] = 'content';
        }

        WC_Admin_Settings::save_fields(self::get_settings_fields());

        $normalized = [];
        foreach ($enabled_raw as $key => $vals) {
            $parts = explode('|', $key);
            if (count($parts) !== 2) continue;
            $pid = intval($parts[0]);
            $env = sanitize_text_field($parts[1]);
            $normalized[$key] = [
                'partner_id' => $pid,
                'env'        => $env,
                'default'    => 0,
            ];
        }

        $hasDefault = false;
        if (!empty($default_key) && isset($normalized[$default_key])) {
            $normalized[$default_key]['default'] = 1;
            $hasDefault = true;
        } elseif (!empty($default_key) && !isset($normalized[$default_key])) {
            WC_Admin_Settings::add_message(__('Selected default courier was disabled, so the default has been reset.', 'woo-5e'));
        }

        if (!$hasDefault && !empty($normalized)) {
            $keys = array_keys($normalized);
            $firstKey = reset($keys);
            if ($firstKey !== null) {
                $normalized[$firstKey]['default'] = 1;
            }
        }

        update_option('w5e_enabled_partners', $normalized, false);
        update_option('w5e_pricing_matrix', self::sanitize_pricing_matrix($pricing_raw), false);

        if (class_exists('WC_Admin_Settings')) {
            WC_Admin_Settings::add_message(sprintf(__('5E couriers saved: %d enabled.', 'woo-5e'), count($normalized)));
        }

        $defaultWarehouseId  = '';
        if (is_array($defaultWarehouseRaw)) {
            $defaultWarehouseRaw = array_values(array_filter(array_map('sanitize_text_field', $defaultWarehouseRaw)));
            $defaultWarehouseId  = isset($defaultWarehouseRaw[0]) ? (string)$defaultWarehouseRaw[0] : '';
        } else {
            $defaultWarehouseId = sanitize_text_field((string)$defaultWarehouseRaw);
        }
        if ($defaultWarehouseId !== '') {
            update_option('w5e_default_warehouse_id', $defaultWarehouseId, false);
        }

        // Enforce hidden/static settings.
        update_option('w5e_flat_price', '0', false);
        update_option('w5e_order_forwarding_enabled', 'yes', false);
        update_option('w5e_client_user_id', 'USER-1', false);
        update_option('w5e_created_user_id', 1, false);
        update_option('w5e_recipient_pre_notification', 0, false);
        update_option('w5e_return_doc', 'no', false);
        update_option('w5e_del_payment_by', 2, false);
        update_option('w5e_shipment_type', 1, false);
        update_option('w5e_delivery_type', 1, false);

        self::ensure_shipping_method_linked();
    }

    public static function maybe_save_settings_fallback()
    {
        if (self::$did_save) {
            return;
        }
        $section = isset($_GET['section']) ? sanitize_key((string)$_GET['section']) : '';
        if ($section !== 'w5e') {
            return;
        }
        self::save_settings();
    }

    public static function render_courier_table_field($field)
    {
        $enabled = get_option('w5e_enabled_partners', []);
        $cache   = get_option('w5e_couriers_cache', []);
        $title   = isset($field['title']) ? esc_html($field['title']) : '';
        $desc    = isset($field['desc']) ? wp_kses_post($field['desc']) : '';
?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label><?php echo $title; ?></label>
            </th>
            <td class="forminp">
                <?php if ($desc) : ?>
                    <p><?php echo $desc; ?></p>
                <?php endif; ?>
                <p>
                    <button type="button" class="button button-secondary" id="w5e-fetch-btn"><?php esc_html_e('Fetch couriers from 5E', 'woo-5e'); ?></button>
                    <span id="w5e-fetch-status" style="margin-left:8px;"></span>
                </p>
                <?php if (!empty($cache) && is_array($cache)) : ?>
                    <table class="widefat striped">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Enable', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Partner ID', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Courier name', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Environment', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Default', 'woo-5e'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            foreach ($cache as $row) {
                                $partnerId = intval($row['PartnerID']);
                                $name      = sanitize_text_field($row['CourierName']);
                                $envLabel  = sanitize_text_field($row['Env']);
                                $key       = $partnerId . '|' . $envLabel;
                                $isEnabled = isset($enabled[$key]);
                                $isDefault = $isEnabled && !empty($enabled[$key]['default']);
                                echo '<tr>';
                                echo '<td><input type="checkbox" class="w5e-courier-enable" name="w5e_enabled_partners[' . esc_attr($key) . '][enabled]" ' . checked($isEnabled, true, false) . ' /></td>';
                                echo '<td>' . esc_html($partnerId) . '</td>';
                                echo '<td>' . esc_html($name) . '</td>';
                                echo '<td>' . esc_html($envLabel) . '</td>';
                                echo '<td><input type="radio" class="w5e-courier-default" name="w5e_default_partner" value="' . esc_attr($key) . '" ' . checked($isDefault, true, false) . ' /></td>';
                                echo '</tr>';
                            }
                            ?>
                        </tbody>
                    </table>
                    <p><small><?php esc_html_e('After fetching couriers, click “Save changes” to persist your selections.', 'woo-5e'); ?></small></p>
                <?php else : ?>
                    <p><?php esc_html_e('Cache is empty. Click “Fetch couriers from 5E”.', 'woo-5e'); ?></p>
                <?php endif; ?>
            </td>
        </tr>
<?php
    }

    public static function render_warehouses_field($field)
    {
        $cache = get_option('w5e_warehouses_cache', []);
        $selectedDefault = sanitize_text_field((string)get_option('w5e_default_warehouse_id', ''));
        $title = isset($field['title']) ? esc_html($field['title']) : '';
        $desc  = isset($field['desc']) ? wp_kses_post($field['desc']) : '';
?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label><?php echo $title; ?></label>
            </th>
            <td class="forminp">
                <?php if ($desc) : ?>
                    <p><?php echo $desc; ?></p>
                <?php endif; ?>
                <p>
                    <button type="button" class="button button-secondary" id="w5e-fetch-warehouses-btn"><?php esc_html_e('Fetch warehouses from 5E', 'woo-5e'); ?></button>
                    <span id="w5e-fetch-warehouses-status" style="margin-left:8px;"></span>
                </p>

                <?php if (!empty($cache) && is_array($cache)) : ?>
                    <table class="widefat striped" style="max-width: 820px;">
                        <thead>
                            <tr>
                                <th style="width: 90px;"><?php esc_html_e('Default', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Client warehouse ID', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Name', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Town', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Address', 'woo-5e'); ?></th>
                                <th><?php esc_html_e('Active', 'woo-5e'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cache as $row) :
                                if (!is_array($row)) continue;
                                $clientWid = isset($row['ClientWarehouseID']) ? sanitize_text_field($row['ClientWarehouseID']) : '';
                                $wid = isset($row['WarehouseID']) ? sanitize_text_field($row['WarehouseID']) : '';
                                if ($clientWid === '' && $wid === '') continue;
                                $name = isset($row['WarehouseName']) ? sanitize_text_field($row['WarehouseName']) : '';
                                $town = isset($row['WarehouseTown']) ? sanitize_text_field($row['WarehouseTown']) : '';
                                $addr = isset($row['WarehouseAddress']) ? sanitize_text_field($row['WarehouseAddress']) : '';
                                $isDefault = !empty($row['IsDefault']);
                                $active = !empty($row['WarehouseStatus']);
                                $checked = ($selectedDefault !== '' && $clientWid === $selectedDefault) || ($selectedDefault === '' && $isDefault);
                            ?>
                                <tr>
                                    <td>
                                        <input
                                            type="checkbox"
                                            class="w5e-warehouse-default"
                                            name="w5e_default_warehouse_id[]"
                                            value="<?php echo esc_attr($clientWid !== '' ? $clientWid : $wid); ?>"
                                            <?php checked($checked, true); ?>
                                        />
                                    </td>
                                    <td><?php echo esc_html($clientWid !== '' ? $clientWid : $wid); ?></td>
                                    <td><?php echo esc_html($name); ?></td>
                                    <td><?php echo esc_html($town); ?></td>
                                    <td><?php echo esc_html($addr); ?></td>
                                    <td><?php echo $active ? '&#10003;' : ''; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <p><small><?php esc_html_e('Check exactly one warehouse as default, then click “Save changes”. The selected warehouse ID will be used for order export.', 'woo-5e'); ?></small></p>
                <?php else : ?>
                    <p><?php esc_html_e('Cache is empty. Click “Fetch warehouses from 5E”.', 'woo-5e'); ?></p>
                <?php endif; ?>
            </td>
        </tr>
<?php
    }

    public static function render_pricing_matrix_field($field)
    {
        $title  = isset($field['title']) ? esc_html($field['title']) : '';
        $desc   = isset($field['desc']) ? wp_kses_post($field['desc']) : '';
        $matrix = get_option('w5e_pricing_matrix', []);

        if (empty($matrix) || !is_array($matrix)) {
            $matrix = self::get_default_pricing_matrix();
        }

        self::maybe_print_pricing_styles();

?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label><?php echo $title; ?></label>
            </th>
            <td class="forminp">
                <?php if ($desc) : ?>
                    <p><?php echo $desc; ?></p>
                <?php endif; ?>
                <p>
                    <button
                        type="button"
                        class="button button-secondary"
                        id="w5e-toggle-pricing-matrix"
                        aria-expanded="false"
                        aria-controls="w5e-pricing-matrix"
                        data-show="<?php esc_attr_e('Show pricing matrix', 'woo-5e'); ?>"
                        data-hide="<?php esc_attr_e('Hide pricing matrix', 'woo-5e'); ?>"
                    >
                        <?php esc_html_e('Show pricing matrix', 'woo-5e'); ?>
                    </button>
                </p>
                <div id="w5e-pricing-matrix" class="w5e-pricing-matrix" style="display:none;">
                    <p class="description" style="margin-top:0;">
                        <?php esc_html_e('Click to edit courier pricing rows. Defaults stay as-is while hidden.', 'woo-5e'); ?>
                    </p>
                    <?php
                    $index = 0;
                    foreach ($matrix as $slug => $group) {
                        self::render_pricing_group($index++, $slug, $group);
                    }
                    ?>
                    <p>
                        <button type="button" class="button" id="w5e-add-pricing-group"><?php esc_html_e('Add courier pricing', 'woo-5e'); ?></button>
                    </p>
                </div>
                <script type="text/html" id="w5e-pricing-group-template">
                    <?php self::render_pricing_group('__INDEX__', '', self::get_empty_pricing_group(), true); ?>
                </script>
                <script type="text/html" id="w5e-pricing-row-template">
                    <?php self::render_pricing_row('__INDEX__', '__ROW__', [], true); ?>
                </script>
            </td>
        </tr>
<?php
    }

    private static function maybe_print_pricing_styles()
    {
        if (self::$pricing_styles_printed) {
            return;
        }
        self::$pricing_styles_printed = true;
?>
        <style>
            .w5e-pricing-matrix {
                margin-top: 10px;
            }
            .w5e-pricing-group {
                border: 1px solid #dcdcde;
                padding: 12px;
                margin-bottom: 20px;
                background: #fff;
            }
            .w5e-pricing-group__header {
                display: flex;
                gap: 20px;
                align-items: flex-end;
                flex-wrap: wrap;
                border-bottom: 1px solid #eee;
                margin-bottom: 10px;
                padding-bottom: 10px;
            }
            .w5e-pricing-group__header input {
                min-width: 220px;
            }
            .w5e-pricing-table-wrap {
                margin-top: 15px;
            }
            .w5e-pricing-table-wrap table input {
                width: 100%;
            }
        </style>
<?php
    }

    private static function render_pricing_group($index, $slug, $group, $is_template = false)
    {
        $label    = isset($group['label']) ? $group['label'] : '';
        $standard = isset($group['standard']) && is_array($group['standard']) ? $group['standard'] : [];
        $attr     = $is_template ? '__INDEX__' : $index;
?>
        <div class="w5e-pricing-group" data-index="<?php echo esc_attr($attr); ?>">
            <div class="w5e-pricing-group__header">
                <p>
                    <label>
                        <?php esc_html_e('Courier label', 'woo-5e'); ?><br />
                        <input type="text" name="w5e_pricing_matrix[<?php echo esc_attr($attr); ?>][label]" value="<?php echo esc_attr($label); ?>" placeholder="<?php esc_attr_e('e.g. BEX', 'woo-5e'); ?>" />
                    </label>
                </p>
                <p>
                    <label>
                        <?php esc_html_e('Slug/identifier', 'woo-5e'); ?><br />
                        <input type="text" name="w5e_pricing_matrix[<?php echo esc_attr($attr); ?>][slug]" value="<?php echo esc_attr($slug); ?>" placeholder="<?php esc_attr_e('auto-filled from label', 'woo-5e'); ?>" />
                    </label>
                </p>
                <button type="button" class="button-link-delete w5e-remove-group"><?php esc_html_e('Remove courier', 'woo-5e'); ?></button>
            </div>
            <div class="w5e-pricing-table-wrap">
                <h4><?php esc_html_e('Standard shipments', 'woo-5e'); ?></h4>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Description', 'woo-5e'); ?></th>
                            <th><?php esc_html_e('Min kg', 'woo-5e'); ?></th>
                            <th><?php esc_html_e('Max kg', 'woo-5e'); ?></th>
                            <th><?php esc_html_e('Price', 'woo-5e'); ?></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody class="w5e-standard-rows">
                        <?php
                        if ($standard) {
                            foreach ($standard as $rowIndex => $row) {
                                self::render_pricing_row($attr, $rowIndex, $row);
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p><button type="button" class="button w5e-add-row" data-type="standard"><?php esc_html_e('Add row', 'woo-5e'); ?></button></p>
            </div>
        </div>
<?php
    }

    private static function render_pricing_row($groupIndex, $rowIndex, $row, $is_template = false)
    {
        $row   = is_array($row) ? $row : [];
        $desc  = isset($row['label']) ? $row['label'] : '';
        $price = isset($row['price']) ? $row['price'] : (isset($row['gross']) ? $row['gross'] : '');
        $min   = isset($row['min']) ? $row['min'] : '';
        $max   = isset($row['max']) ? $row['max'] : '';

        $group = $is_template ? $groupIndex : $groupIndex;
        $rowId = $is_template ? $rowIndex : $rowIndex;

        echo '<tr>';
        echo '<td><input type="text" name="w5e_pricing_matrix[' . esc_attr($group) . '][standard][' . esc_attr($rowId) . '][label]" value="' . esc_attr($desc) . '" /></td>';
        echo '<td><input type="number" step="0.01" name="w5e_pricing_matrix[' . esc_attr($group) . '][standard][' . esc_attr($rowId) . '][min]" value="' . esc_attr($min) . '" /></td>';
        echo '<td><input type="number" step="0.01" name="w5e_pricing_matrix[' . esc_attr($group) . '][standard][' . esc_attr($rowId) . '][max]" value="' . esc_attr($max) . '" /></td>';
        echo '<td><input type="number" step="0.01" name="w5e_pricing_matrix[' . esc_attr($group) . '][standard][' . esc_attr($rowId) . '][price]" value="' . esc_attr($price) . '" /></td>';
        echo '<td><button type="button" class="button-link-delete w5e-remove-row">' . esc_html__('Remove', 'woo-5e') . '</button></td>';
        echo '</tr>';
    }

    private static function get_empty_pricing_group()
    {
        return [
            'label'    => '',
            'slug'     => '',
            'standard' => [],
        ];
    }

    private static function sanitize_pricing_matrix($input)
    {
        if (!is_array($input)) {
            return [];
        }

        $result = [];
        foreach ($input as $group) {
            if (!is_array($group)) {
                continue;
            }

            $label = sanitize_text_field($group['label'] ?? '');
            $slug  = sanitize_title($group['slug'] ?? $label);
            if (!$slug) {
                continue;
            }

            $result[$slug] = [
                'label'    => $label ?: $slug,
                'standard' => self::sanitize_pricing_rows($group['standard'] ?? []),
            ];
        }

        return $result;
    }

    private static function sanitize_pricing_rows($rows)
    {
        $clean = [];
        if (!is_array($rows)) {
            return $clean;
        }

        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }

            $label = sanitize_text_field($row['label'] ?? '');
            if ($label === '') {
                continue;
            }

            $entry = [
                'label' => $label,
                'price' => self::sanitize_decimal($row['price'] ?? ($row['gross'] ?? $row['net'] ?? '')),
            ];

            $entry['min'] = self::sanitize_decimal($row['min'] ?? '0');
            $entry['max'] = self::sanitize_decimal($row['max'] ?? '');

            $clean[] = $entry;
        }

        return $clean;
    }

    private static function sanitize_decimal($value)
    {
        if (!is_scalar($value)) {
            return '';
        }

        $value = str_replace(',', '.', (string)$value);
        $value = preg_replace('/[^0-9\.-]/', '', $value);
        return $value;
    }

    public static function get_default_pricing_matrix()
    {
        return [
            'bex' => [
                'label' => 'BEX',
                'standard' => [
                    ['label' => 'Paket od 0,35 do 0,50 kg', 'min' => '0.35', 'max' => '0.50', 'price' => '360'],
                    ['label' => 'Paket od 0,50 do 1 kg', 'min' => '0.50', 'max' => '1', 'price' => '400'],
                    ['label' => 'Paket od 1 do 2 kg', 'min' => '1', 'max' => '2', 'price' => '480'],
                    ['label' => 'Paket od 2 do 5 kg', 'min' => '2', 'max' => '5', 'price' => '588'],
                    ['label' => 'Paket od 5 do 10 kg', 'min' => '5', 'max' => '10', 'price' => '776'],
                    ['label' => 'Paket od 10 do 15 kg', 'min' => '10', 'max' => '15', 'price' => '988'],
                    ['label' => 'Paket od 15 do 20 kg', 'min' => '15', 'max' => '20', 'price' => '1109'],
                    ['label' => 'Paket od 20 do 30 kg', 'min' => '20', 'max' => '30', 'price' => '1276'],
                    ['label' => 'Paket od 30 do 50 kg', 'min' => '30', 'max' => '50', 'price' => '1876'],
                ],
            ],
        ];
    }

    private static function ensure_shipping_method_linked()
    {
        if (!function_exists('WC') || !class_exists('WC_Shipping_Zones')) {
            return;
        }

        WC()->shipping();

        $enabled = get_option('w5e_enabled_partners', []);
        if (!is_array($enabled) || empty($enabled)) {
            self::remove_shipping_method_from_all_zones('w5e');
            return;
        }

        $zones    = WC_Shipping_Zones::get_zones();
        $zone_ids = array_map('absint', array_keys($zones));
        $zone_ids[] = 0;

        foreach ($zone_ids as $zone_id) {
            $zone    = new WC_Shipping_Zone($zone_id);
            $methods = $zone->get_shipping_methods(true);
            $exists  = false;

            foreach ($methods as $method) {
                if ($method && $method->id === 'w5e') {
                    $exists = true;
                    break;
                }
            }

            if ($exists) {
                continue;
            }

            $zone->add_shipping_method('w5e');
        }
    }

    private static function remove_shipping_method_from_all_zones($methodId)
    {
        $methodId = sanitize_key((string)$methodId);
        if ($methodId === '') {
            return;
        }

        $zones    = WC_Shipping_Zones::get_zones();
        $zone_ids = array_map('absint', array_keys($zones));
        $zone_ids[] = 0;

        foreach ($zone_ids as $zone_id) {
            $zone    = new WC_Shipping_Zone($zone_id);
            $methods = $zone->get_shipping_methods(true);
            foreach ($methods as $method) {
                if (!$method || empty($method->id)) {
                    continue;
                }
                if ($method->id !== $methodId) {
                    continue;
                }

                $instanceId = isset($method->instance_id) ? absint($method->instance_id) : 0;
                if (!$instanceId) {
                    continue;
                }
                if (method_exists($zone, 'delete_shipping_method')) {
                    $zone->delete_shipping_method($instanceId);
                }
            }
        }
    }

    private static function get_settings_fields()
    {
        return [
            [
                'title' => __('5E Shipping', 'woo-5e'),
                'desc'  => __('Configure 5E credentials and courier visibility within the WooCommerce shipping settings.', 'woo-5e'),
                'type'  => 'title',
                'id'    => 'w5e_settings_section',
            ],
            [
                'title' => __('Important notice', 'woo-5e'),
                'type'  => 'title',
                'id'    => 'w5e_weight_notice_title',
                'desc'  => sprintf(
                    '<div class="notice notice-warning inline" style="margin:8px 0 0 0;"><p>%s</p></div>',
                    esc_html__('Please make sure every product has a weight set. Couriers require this information.', 'woo-5e')
                ),
            ],
            [
                'title'   => __('5E ID', 'woo-5e'),
                'id'      => 'w5e_id',
                'type'    => 'text',
                'default' => '',
                'desc'    => __('Potraziti podatke unutar 5E Dashboarda - pitati administatora', 'woo-5e'),
            ],
            [
                'title'   => __('API Auth Key', 'woo-5e'),
                'id'      => 'w5e_api_key',
                'type'    => 'password',
                'default' => '',
                'desc'    => __('Potraziti podatke unutar 5E Dashboarda - pitati administatora', 'woo-5e'),
            ],
            [
                'title'   => __('Who pays delivery', 'woo-5e'),
                'id'      => 'w5e_del_payment_by',
                'type'    => 'select',
                'default' => 2,
                'options' => [
                    1 => __('Sender', 'woo-5e'),
                    2 => __('Recipient', 'woo-5e'),
                    3 => __('Customer (bank)', 'woo-5e'),
                ],
            ],
            [
                'title'   => __('Environment', 'woo-5e'),
                'id'      => 'w5e_env',
                'type'    => 'select',
                'default' => 'staging',
                'options' => [
                    'staging'    => __('Staging', 'woo-5e'),
                    'production' => __('Production', 'woo-5e'),
                ],
            ],
            [
                'title'       => __('Staging order API URL', 'woo-5e'),
                'id'          => 'w5e_orders_base_url_staging',
                'type'        => 'text',
                'default'     => '',
                'desc'        => __('Used only when Environment is set to Staging. Leave empty to use the default staging host.', 'woo-5e'),
            ],
            [
                'title'       => __('Production order API URL', 'woo-5e'),
                'id'          => 'w5e_orders_base_url_production',
                'type'        => 'text',
                'default'     => '',
                'desc'        => __('Used only when Environment is set to Production. Leave empty to use the default production host.', 'woo-5e'),
            ],
            [
                'title'   => __('Use address directory', 'woo-5e'),
                'id'      => 'w5e_use_address_directory',
                'type'    => 'checkbox',
                'default' => 'no',
                'desc'    => __('Enable city/street dropdown search on the checkout using our address directory. Works only with default WooCommerce fields (billing/shipping city, address, postcode).', 'woo-5e'),
            ],
            [
                'title'   => __('Who pays buy-out', 'woo-5e'),
                'id'      => 'w5e_buyout_payer',
                'type'    => 'select',
                'default' => 'recipient',
                'options' => [
                    'recipient'  => __('Recipient (cash on delivery)', 'woo-5e'),
                    'buyer_bank' => __('Buyer bank account (prepaid, no COD)', 'woo-5e'),
                ],
                'desc'    => __('Choose whether COD is collected from the recipient or treated as prepaid (no COD).', 'woo-5e'),
            ],
            [
                'title'             => __('Flat price (v1)', 'woo-5e'),
                'id'                => 'w5e_flat_price',
                'type'              => 'number',
                'default'           => '0',
                'css'               => 'display:none;',
                'custom_attributes' => [
                    'step' => '0.01',
                ],
            ],
            [
                'title' => __('Order forwarding (5E)', 'woo-5e'),
                'desc'  => __('Automatically push WooCommerce orders to 5E/Last Mile once payment is successful.', 'woo-5e'),
                'type'  => 'title',
                'id'    => 'w5e_order_forwarding_section',
            ],
            [
                'title'   => __('Import mode', 'woo-5e'),
                'id'      => 'w5e_import_mode',
                'type'    => 'select',
                'default' => 'auto',
                'options' => [
                    'auto'   => __('Auto import (send on status change)', 'woo-5e'),
                    'manual' => __('Manual import (choose warehouse per order)', 'woo-5e'),
                ],
                'desc'    => __('Auto: orders are sent to 5E automatically when they reach selected statuses. Manual: orders are not sent automatically; choose a warehouse on the order edit screen and send manually.', 'woo-5e'),
            ],
            [
                'title'   => __('Enable order forwarding', 'woo-5e'),
                'id'      => 'w5e_order_forwarding_enabled',
                'type'    => 'checkbox',
                'default' => 'yes',
                'css'     => 'display:none;',
                'desc'    => __('Send orders to the 5E API when they reach Processing/Completed.', 'woo-5e'),
            ],
            [
                'title'   => __('Trigger on statuses', 'woo-5e'),
                'id'      => 'w5e_order_export_statuses',
                'type'    => 'multiselect',
                'default' => ['processing', 'completed'],
                'options' => self::get_order_status_choices(),
                'class'   => 'wc-enhanced-select',
                'css'     => 'min-width: 250px;',
                'desc'    => __('Orders are exported the first time they enter one of the selected statuses.', 'woo-5e'),
            ],
            [
                'title' => __('Warehouses (cached)', 'woo-5e'),
                'type'  => 'w5e_warehouses',
                'id'    => 'w5e_warehouses',
                'desc'  => __('Fetch and cache warehouses available for your 5E credentials. Select one as default and save changes.', 'woo-5e'),
            ],
            [
                'title'   => __('Client user ID', 'woo-5e'),
                'id'      => 'w5e_client_user_id',
                'type'    => 'text',
                'default' => 'USER-1',
                'css'     => 'display:none;',
                'desc'    => __('Optional: maps to ClientUserID (magacioner). Leave empty if unused.', 'woo-5e'),
            ],
            [
                'title'             => __('Created/edited by user ID', 'woo-5e'),
                'id'                => 'w5e_created_user_id',
                'type'              => 'number',
                'default'           => 1,
                'css'               => 'display:none;',
                'custom_attributes' => ['min' => 1],
                'desc'              => __('Numeric ID required by the Last Mile API (CreatedEditedByUser).', 'woo-5e'),
            ],
            [
                'title'   => __('Buy-out bank account', 'woo-5e'),
                'id'      => 'w5e_buyout_account',
                'type'    => 'text',
                'default' => '',
                'desc'    => __('IBAN / account number used for COD settlements.', 'woo-5e'),
            ],
            [
                'title'   => __('Delivery type', 'woo-5e'),
                'id'      => 'w5e_delivery_type',
                'type'    => 'select',
                'default' => 1,
                'options' => [
                    1 => __('Standard', 'woo-5e'),
                    2 => __('Express', 'woo-5e'),
                    3 => __('Special', 'woo-5e'),
                ],
            ],
            [
                'title'   => __('Shipment type', 'woo-5e'),
                'id'      => 'w5e_shipment_type',
                'type'    => 'select',
                'default' => 1,
                'options' => [
                    1 => __('Regular', 'woo-5e'),
                    2 => __('Express', 'woo-5e'),
                    3 => __('Special', 'woo-5e'),
                ],
            ],
            [
                'title'   => __('Recipient pre-notification', 'woo-5e'),
                'id'      => 'w5e_recipient_pre_notification',
                'type'    => 'select',
                'default' => 0,
                'css'     => 'display:none;',
                'options' => [
                    0  => __('No notification', 'woo-5e'),
                    1  => __('1 minute before', 'woo-5e'),
                    5  => __('5 minutes before', 'woo-5e'),
                    15 => __('15 minutes before', 'woo-5e'),
                    30 => __('30 minutes before', 'woo-5e'),
                    45 => __('45 minutes before', 'woo-5e'),
                    60 => __('60 minutes before', 'woo-5e'),
                ],
            ],
            [
                'title'   => __('Shipment Content', 'woo-5e'),
                'id'      => 'w5e_shipment_content',
                'type'    => 'text',
                'default' => 'content',
                'custom_attributes' => [
                    'required' => 'required',
                ],
                'desc'    => __('Enter a short description of the shipment contents.', 'woo-5e'),
            ],
            [
                'title'   => __('Auto approve shipments', 'woo-5e'),
                'id'      => 'w5e_auto_approve',
                'type'    => 'checkbox',
                'default' => 'no',
                'desc'    => __('If enabled, orders are auto-approved on Last Mile (AutoApprove=true).', 'woo-5e'),
            ],
            [
                'title'   => __('Return document required', 'woo-5e'),
                'id'      => 'w5e_return_doc',
                'type'    => 'checkbox',
                'default' => 'no',
                'css'     => 'display:none;',
                'desc'    => __('Whether ReturnDoc flag should be set to true.', 'woo-5e'),
            ],
            [
                'type' => 'sectionend',
                'id'   => 'w5e_order_forwarding_section',
            ],
            [
                'title' => __('Couriers (cached)', 'woo-5e'),
                'type'  => 'w5e_courier_table',
                'id'    => 'w5e_courier_table',
                'desc'  => __('Enable couriers/environments and pick which one should be selected by default.', 'woo-5e'),
            ],
            [
                'title' => __('Pricing matrix', 'woo-5e'),
                'desc'  => __('Define courier-specific cost tables. These values are used when calculating rates instead of the fallback flat amount.', 'woo-5e'),
                'type'  => 'title',
                'id'    => 'w5e_pricing_matrix_title',
            ],
            [
                'title' => __('Courier pricing matrix', 'woo-5e'),
                'type'  => 'w5e_pricing_matrix',
                'id'    => 'w5e_pricing_matrix',
                'desc'  => __('Add a table per courier with weight ranges and prices (RSD). Leave empty to fall back to the default BEX reference.', 'woo-5e'),
            ],
            [
                'type' => 'sectionend',
                'id'   => 'w5e_pricing_matrix_title',
            ],
            [
                'type' => 'sectionend',
                'id'   => 'w5e_settings_section',
            ],
        ];
    }

    private static function get_order_status_choices()
    {
        $choices = [];
        if (function_exists('wc_get_order_statuses')) {
            foreach (wc_get_order_statuses() as $key => $label) {
                $choices[str_replace('wc-', '', $key)] = $label;
            }
        }

        if (empty($choices)) {
            $choices = [
                'processing' => __('Processing', 'woocommerce'),
                'completed'  => __('Completed', 'woocommerce'),
            ];
        }

        return $choices;
    }
}
