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

/**
 * Add Integration tab link to the WCMV settings screen.
 */
add_action('stakmv_auctions_settings_tabs', function ($current_tab) {
    if (!current_user_can('manage_woocommerce')) {
        return;
    }

    $active = $current_tab === 'integration' ? 'nav-tab-active' : '';
    printf(
        '<a href="?page=stakmv-auctions&tab=integration" class="nav-tab %s">Shipping</a>',
        esc_attr($active)
    );
}, 15);

/**
 * Render Integration tab (free): live shipping rate provider setup.
 */
add_action('stakmv_auctions_render_tab_integration', function () {
    if (!current_user_can('manage_woocommerce')) {
        echo '<p>Insufficient permissions.</p>';
        return;
    }

    if (isset($_POST['save_integration'])) {
        check_admin_referer('stakmv_save_integration', 'stakmv_save_integration_nonce');

        $provider = sanitize_key(wp_unslash($_POST['stakmv_live_shipping_multi_provider'] ?? 'easypost'));
        if (!in_array($provider, array('easypost', 'shippo'), true)) {
            $provider = 'easypost';
        }

        $api_mode = sanitize_key(wp_unslash($_POST['stakmv_live_shipping_api_mode'] ?? 'test'));
        if (!in_array($api_mode, array('test', 'live'), true)) {
            $api_mode = 'test';
        }

        $carrier_options = array('USPS', 'UPS', 'FedEx', 'DHL');
        $allowed_carriers = array();
        if (isset($_POST['stakmv_live_shipping_allowed_carriers']) && is_array($_POST['stakmv_live_shipping_allowed_carriers'])) {
            $raw = array_map('sanitize_text_field', wp_unslash($_POST['stakmv_live_shipping_allowed_carriers']));
            foreach ($raw as $carrier) {
                if (in_array($carrier, $carrier_options, true)) {
                    $allowed_carriers[] = $carrier;
                }
            }
            $allowed_carriers = array_values(array_unique($allowed_carriers));
        }

        $cache_minutes = (int) sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_cache_minutes'] ?? 10));
        if ($cache_minutes < 1) {
            $cache_minutes = 1;
        }
        if ($cache_minutes > 1440) {
            $cache_minutes = 1440;
        }

        $fallback_mode = sanitize_key(wp_unslash($_POST['stakmv_live_shipping_fallback_mode'] ?? 'hide'));
        if (!in_array($fallback_mode, array('hide', 'flat'), true)) {
            $fallback_mode = 'hide';
        }

        stakmv_update_option('live_shipping_enabled', isset($_POST['stakmv_live_shipping_enabled']) ? 'yes' : 'no');
        // Multi-carrier only.
        stakmv_update_option('live_shipping_mode', 'multi');
        stakmv_update_option('live_shipping_multi_provider', $provider);
        stakmv_update_option('live_shipping_api_mode', $api_mode);
        stakmv_update_option('live_shipping_easypost_key_test', sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_easypost_key_test'] ?? '')));
        stakmv_update_option('live_shipping_easypost_key_live', sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_easypost_key_live'] ?? '')));
        stakmv_update_option('live_shipping_shippo_key_test', sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_shippo_key_test'] ?? '')));
        stakmv_update_option('live_shipping_shippo_key_live', sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_shippo_key_live'] ?? '')));
        stakmv_update_option('live_shipping_allowed_carriers', $allowed_carriers);
        stakmv_update_option('live_shipping_cache_minutes', $cache_minutes);
        stakmv_update_option('live_shipping_fallback_mode', $fallback_mode);
        stakmv_update_option('live_shipping_fallback_cost', wc_format_decimal(sanitize_text_field(wp_unslash($_POST['stakmv_live_shipping_fallback_cost'] ?? '0'))));
        stakmv_update_option('live_shipping_debug', isset($_POST['stakmv_live_shipping_debug']) ? 'yes' : 'no');

        echo '<div class="updated"><p>Integration settings saved.</p></div>';
    }

    $enabled          = stakmv_get_option('live_shipping_enabled', 'no');
    $provider         = stakmv_get_option('live_shipping_multi_provider', 'easypost');
    $api_mode         = stakmv_get_option('live_shipping_api_mode', 'test');
    $easypost_test    = (string) stakmv_get_option('live_shipping_easypost_key_test', '');
    $easypost_live    = (string) stakmv_get_option('live_shipping_easypost_key_live', '');
    $shippo_test      = (string) stakmv_get_option('live_shipping_shippo_key_test', '');
    $shippo_live      = (string) stakmv_get_option('live_shipping_shippo_key_live', '');
    $carrier_options = array('USPS', 'UPS', 'FedEx', 'DHL');
    $allowed_carriers = stakmv_get_option('live_shipping_allowed_carriers', $carrier_options);
    if (!is_array($allowed_carriers)) {
        $allowed_carriers = $carrier_options;
    }
    $cache_minutes = (int) stakmv_get_option('live_shipping_cache_minutes', 10);
    if ($cache_minutes < 1) {
        $cache_minutes = 10;
    }
    $fallback_mode = stakmv_get_option('live_shipping_fallback_mode', 'hide');
    $fallback_cost = stakmv_get_option('live_shipping_fallback_cost', '0');
    $debug_enabled = stakmv_get_option('live_shipping_debug', 'no');
    ?>

    <h2>Shipping Integrations</h2>
    <p>Configure live shipping rates for cart/checkout. Tracking can be added by extensions.</p>

    <form method="post">
        <?php wp_nonce_field('stakmv_save_integration', 'stakmv_save_integration_nonce'); ?>
        <table class="form-table">
            <tr>
                <th scope="row">Enable Live Shipping Rates</th>
                <td>
                    <label>
                        <input type="checkbox" name="stakmv_live_shipping_enabled" <?php checked($enabled, 'yes'); ?>>
                        Fetch real-time rates for listings during cart/checkout.
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row">Provider</th>
                <td>
                    <select name="stakmv_live_shipping_multi_provider" id="wcmv-live-shipping-provider">
                        <option value="easypost" <?php selected($provider, 'easypost'); ?>>EasyPost</option>
                        <option value="shippo" <?php selected($provider, 'shippo'); ?>>Shippo</option>
                    </select>
                    <p class="description">Choose a multi-carrier provider for live shipping rates.</p>
                </td>
            </tr>

            <tr>
                <th scope="row">API Environment</th>
                <td>
                    <select name="stakmv_live_shipping_api_mode" id="wcmv-live-shipping-api-mode">
                        <option value="test" <?php selected($api_mode, 'test'); ?>>Test</option>
                        <option value="live" <?php selected($api_mode, 'live'); ?>>Live</option>
                    </select>
                </td>
            </tr>

            <tr class="wcmv-provider-row wcmv-provider-easypost wcmv-env-test">
                <th scope="row">EasyPost Test Key</th>
                <td><input type="password" class="regular-text" name="stakmv_live_shipping_easypost_key_test" value="<?php echo esc_attr($easypost_test); ?>"></td>
            </tr>

            <tr class="wcmv-provider-row wcmv-provider-easypost wcmv-env-live">
                <th scope="row">EasyPost Live Key</th>
                <td><input type="password" class="regular-text" name="stakmv_live_shipping_easypost_key_live" value="<?php echo esc_attr($easypost_live); ?>"></td>
            </tr>

            <tr class="wcmv-provider-row wcmv-provider-shippo wcmv-env-test">
                <th scope="row">Shippo Test Key</th>
                <td><input type="password" class="regular-text" name="stakmv_live_shipping_shippo_key_test" value="<?php echo esc_attr($shippo_test); ?>"></td>
            </tr>

            <tr class="wcmv-provider-row wcmv-provider-shippo wcmv-env-live">
                <th scope="row">Shippo Live Key</th>
                <td><input type="password" class="regular-text" name="stakmv_live_shipping_shippo_key_live" value="<?php echo esc_attr($shippo_live); ?>"></td>
            </tr>

            <tr>
                <th scope="row">Allowed Carriers</th>
                <td>
                    <label><input type="checkbox" name="stakmv_live_shipping_allowed_carriers[]" value="USPS" <?php checked(in_array('USPS', $allowed_carriers, true)); ?>> USPS</label><br>
                    <label><input type="checkbox" name="stakmv_live_shipping_allowed_carriers[]" value="UPS" <?php checked(in_array('UPS', $allowed_carriers, true)); ?>> UPS</label><br>
                    <label><input type="checkbox" name="stakmv_live_shipping_allowed_carriers[]" value="FedEx" <?php checked(in_array('FedEx', $allowed_carriers, true)); ?>> FedEx</label><br>
                    <label><input type="checkbox" name="stakmv_live_shipping_allowed_carriers[]" value="DHL" <?php checked(in_array('DHL', $allowed_carriers, true)); ?>> DHL</label>
                </td>
            </tr>

            <tr>
                <th scope="row">Rate Cache (minutes)</th>
                <td><input type="number" min="1" max="1440" name="stakmv_live_shipping_cache_minutes" value="<?php echo esc_attr($cache_minutes); ?>"></td>
            </tr>

            <tr>
                <th scope="row">Fallback When API Fails</th>
                <td>
                    <select name="stakmv_live_shipping_fallback_mode">
                        <option value="hide" <?php selected($fallback_mode, 'hide'); ?>>Hide live rates</option>
                        <option value="flat" <?php selected($fallback_mode, 'flat'); ?>>Use fallback flat rate</option>
                    </select>
                    <p>
                        <input type="number" step="0.01" min="0" name="stakmv_live_shipping_fallback_cost" value="<?php echo esc_attr($fallback_cost); ?>">
                        <span class="description">Fallback flat cost</span>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">Debug Logging</th>
                <td>
                    <label>
                        <input type="checkbox" name="stakmv_live_shipping_debug" <?php checked($debug_enabled, 'yes'); ?>>
                        Write shipping integration logs to WooCommerce logs.
                    </label>
                </td>
            </tr>
        </table>

        <p>
            <button type="submit" name="save_integration" class="button-primary">Save Changes</button>
        </p>
    </form>
    <?php
});
