<?php
/**
 * Copyright (c) 2025 Teleship Limited. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package Teleship
 */

/**
 * Plugin Name: Teleship Global Shipping
 * Plugin URI: https://teleship.com/connect
 * Description: Seamlessly integrate Teleship shipping platform with your WooCommerce store.
 * Version: 1.0.16
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Author: Teleship Limited.
 * Author URI: https://teleship.com
 * Text Domain: teleship-global-shipping
 * Domain Path: /languages
 * WC requires at least: 6.0
 * WC tested up to: 8.4
 * License: GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package Teleship
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Define Teleship logging function
function teleship_log($message) {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('[Teleship] ' . $message); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional debug logging gated by WP_DEBUG
    }
}

// Define plugin version
define('TELESHIP_VERSION', '2.0.0');

// Environment configuration — single source of truth
// Override in wp-config.php:
//   define('TELESHIP_ENV', 'development');           // Switch environment
//   define('TELESHIP_API_URL', 'https://custom.url'); // Direct URL override
//   define('TELESHIP_OAUTH_CLIENT_ID', 'my_app');     // Direct client ID override
if (!defined('TELESHIP_ENV')) {
    define('TELESHIP_ENV', 'production');
}

// Environment configuration map
define('TELESHIP_ENV_CONFIG', array(
    'development' => array(
        'api'             => 'https://dev.teleship.com:3000',
        'app'             => 'https://dev.teleship.com:3004',
        'oauth_client_id' => 'app_woocommerce',
    ),
    'staging' => array(
        'api'             => 'https://sandbox.teleship.com',
        'app'             => 'https://app.sandbox.teleship.com',
        'oauth_client_id' => 'app_woocommerce',
    ),
    'production' => array(
        'api'             => 'https://api.teleship.com',
        'app'             => 'https://app.teleship.com',
        'oauth_client_id' => 'app_woocommerce',
    ),
));

// Resolve OAuth client ID from environment config (overridable via wp-config.php)
if (!defined('TELESHIP_OAUTH_CLIENT_ID')) {
    $teleship_env_config = TELESHIP_ENV_CONFIG;
    $teleship_env = TELESHIP_ENV;
    $teleship_client_id = isset($teleship_env_config[$teleship_env]['oauth_client_id']) ? $teleship_env_config[$teleship_env]['oauth_client_id'] : 'app_woocommerce';
    define('TELESHIP_OAUTH_CLIENT_ID', $teleship_client_id);
    unset($teleship_env_config, $teleship_env, $teleship_client_id);
}

// Register Teleship settings
add_action('admin_init', function() {
    // Add privacy policy content
    if (function_exists('wp_add_privacy_policy_content')) {
        wp_add_privacy_policy_content(
            'Teleship Global Shipping',
            '
            <h3>' . esc_html__('What data does Teleship collect?', 'teleship-global-shipping') . '</h3>
            <p>' . esc_html__('This plugin connects to Teleship services to provide shipping functionality. The following data is shared with Teleship:', 'teleship-global-shipping') . '</p>
            <ul>
                <li>' . esc_html__('Store URL and domain name', 'teleship-global-shipping') . '</li>
                <li>' . esc_html__('WordPress user ID (for authentication purposes)', 'teleship-global-shipping') . '</li>
                <li>' . esc_html__('Order data (when processing shipments)', 'teleship-global-shipping') . '</li>
            </ul>
            <p>' . esc_html__('This data is necessary for the proper functioning of shipping services. Teleship may store this data on their servers to provide and improve their services.', 'teleship-global-shipping') . '</p>
            <h3>' . esc_html__('How long is data retained?', 'teleship-global-shipping') . '</h3>
            <p>' . esc_html__('Order data is retained by Teleship according to their data retention policy. You can contact Teleship directly to request data removal.', 'teleship-global-shipping') . '</p>
            <h3>' . esc_html__('Where can I find more information?', 'teleship-global-shipping') . '</h3>
            <p>' . esc_html__('For more information about how Teleship handles your data, please see their Privacy Policy at:', 'teleship-global-shipping') . ' <a href="https://teleship.com/privacy" target="_blank">https://teleship.com/privacy</a></p>
            '
        );
    }
});

// Helper function to get the current API URL based on environment setting
function teleship_get_api_url() {
    // Direct override via wp-config.php constant
    if (defined('TELESHIP_API_URL')) {
        return TELESHIP_API_URL;
    }

    // Environment variable override
    if (getenv('TELESHIP_API_URL')) {
        return getenv('TELESHIP_API_URL');
    }

    // Resolve from TELESHIP_ENV
    $urls = TELESHIP_ENV_CONFIG;
    $env = defined('TELESHIP_ENV') ? TELESHIP_ENV : 'production';
    return isset($urls[$env]['api']) ? $urls[$env]['api'] : $urls['production']['api'];
}

// Helper function to get the current APP URL based on environment setting
function teleship_get_app_url() {
    // Direct override via wp-config.php constant
    if (defined('TELESHIP_APP_URL')) {
        return TELESHIP_APP_URL;
    }

    // Environment variable override
    if (getenv('TELESHIP_APP_URL')) {
        return getenv('TELESHIP_APP_URL');
    }

    // Resolve from TELESHIP_ENV
    $urls = TELESHIP_ENV_CONFIG;
    $env = defined('TELESHIP_ENV') ? TELESHIP_ENV : 'production';
    return isset($urls[$env]['app']) ? $urls[$env]['app'] : $urls['production']['app'];
}

// Helper function to get the portal URL (same as app URL)
function teleship_get_portal_url() {
    return teleship_get_app_url();
}

// Register logging action
add_action('teleship_log', 'teleship_log');

// Register data export and erasure callbacks
add_filter('wp_privacy_personal_data_exporters', 'teleship_register_data_exporter');
add_filter('wp_privacy_personal_data_erasers', 'teleship_register_data_eraser');

/**
 * Register Teleship data exporter
 *
 * @param array $exporters Current exporters.
 * @return array Modified exporters.
 */
function teleship_register_data_exporter($exporters) {
    $exporters['teleship'] = array(
        'exporter_friendly_name' => esc_html__('Teleship Shipping Data', 'teleship-global-shipping'),
        'callback'               => 'teleship_data_exporter',
    );
    return $exporters;
}

/**
 * Register Teleship data eraser
 *
 * @param array $erasers Current erasers.
 * @return array Modified erasers.
 */
function teleship_register_data_eraser($erasers) {
    $erasers['teleship'] = array(
        'eraser_friendly_name' => esc_html__('Teleship Shipping Data', 'teleship-global-shipping'),
        'callback'             => 'teleship_data_eraser',
    );
    return $erasers;
}

/**
 * Exports data for a specific user
 *
 * @param string $email_address User email address.
 * @param int    $page Export page.
 * @return array Export data.
 */
function teleship_data_exporter($email_address, $page = 1) {
    $user = get_user_by('email', $email_address);
    if (!$user) {
        return array(
            'data' => array(),
            'done' => true,
        );
    }

    $data = array();
    $user_id = $user->ID;

    // Get Teleship-related data for this user
    // This is just a placeholder - you would implement logic to fetch actual data
    // associated with this user from your plugin's storage

    return array(
        'data' => $data,
        'done' => true,
    );
}

/**
 * Erases data for a specific user
 *
 * @param string $email_address User email address.
 * @param int    $page Erasure page.
 * @return array Erasure result.
 */
function teleship_data_eraser($email_address, $page = 1) {
    $user = get_user_by('email', $email_address);
    if (!$user) {
        return array(
            'items_removed'  => false,
            'items_retained' => false,
            'messages'       => array(),
            'done'           => true,
        );
    }

    $user_id = $user->ID;
    $items_removed = false;
    $items_retained = false;
    $messages = array();

    // Remove Teleship-related data for this user
    // This is just a placeholder - you would implement logic to erase actual data
    // associated with this user from your plugin's storage

    // Note that some data might need to be retained for legal or business purposes
    if (!$items_removed) {
        $messages[] = esc_html__('No Teleship shipping data was found for this user.', 'teleship-global-shipping');
    }

    return array(
        'items_removed'  => $items_removed,
        'items_retained' => $items_retained,
        'messages'       => $messages,
        'done'           => true,
    );
}

// Ensure WooCommerce is active
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using core WordPress filter
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')), true)) {
    return;
}

// Load CloudFlare-friendly HTTP client
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-http-client.php';

// Load OAuth manager for secure authentication with Teleship API
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-oauth.php';

// Load Webhook manager for automatic webhook registration
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-webhook-manager.php';

// Load Connection handler for Connect/Disconnect flow
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-connection.php';

// Load shared utilities (country codes, fulfillment calculator, order normalizer)
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-country-codes.php';
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-fulfillment-calculator.php';
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-order-normalizer.php';

// Load Order sync handler for pushing orders to Teleship
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-order-sync.php';

// Load REST API controller for embedded portal integration
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-rest-api.php';

// Load product sync handler for automatic sync with Teleship
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-product-sync.php';

// Load sync scheduler for non-blocking background sync via Action Scheduler
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-sync-scheduler.php';

// Load webhook receiver for classification updates from Teleship
require_once plugin_dir_path(__FILE__) . 'includes/class-teleship-webhook-receiver.php';

// Declare HPOS compatibility
add_action('before_woocommerce_init', function() {
    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
    }
});

// Register activation hook
register_activation_hook(__FILE__, function() {
    // Check PHP version
    if (version_compare(PHP_VERSION, '7.4', '<')) {
        deactivate_plugins(plugin_basename(__FILE__));
        wp_die('Teleship requires PHP 7.4 or higher.');
    }

    // Check WooCommerce
    if (!is_plugin_active('woocommerce/woocommerce.php')) {
        deactivate_plugins(plugin_basename(__FILE__));
        wp_die('Teleship requires WooCommerce to be installed and active.');
    }

    // Create order mapping table
    Teleship_Order_Sync::create_mapping_table();
});

// Register deactivation hook for cleanup, disconnect, and API notification
register_deactivation_hook(__FILE__, function() {
    // IMPORTANT: Send uninstall API call BEFORE disconnect (disconnect clears local credentials)
    $store_url = get_site_url();
    $domain = wp_parse_url($store_url, PHP_URL_HOST);
    $api_url = teleship_get_api_url();

    // Build query parameters — API looks up integration by store_url/domain
    $query_params = array(
        'store_url' => $store_url,
        'domain' => $domain,
        'source' => 'plugin_deactivation',
        'platform' => 'woocommerce',
        'action' => 'uninstall',
    );

    $request_url = add_query_arg($query_params, $api_url . '/api/platforms/' . TELESHIP_OAUTH_CLIENT_ID . '/uninstall');

    // Send uninstall request (blocking so API cleanup completes before we clear local data)
    Teleship_HTTP_Client::post(
        $request_url,
        array(),
        array(
            'timeout'  => 15,
            'blocking' => true,
        )
    );

    // Now run the full local disconnect flow (unregister webhook, delete WC API keys, clear OAuth)
    if (function_exists('teleship_connection')) {
        teleship_connection()->disconnect();
    }
});

// Register uninstall hook (this is called when the plugin is deleted)
register_uninstall_hook(__FILE__, 'teleship_cleanup_on_uninstall');

/**
 * Clean up all plugin data when uninstalled
 */
function teleship_cleanup_on_uninstall() {
    // Remove all plugin options
    delete_option('teleship_environment');
    delete_option('teleship_custom_api_url');
    delete_option('teleship_custom_app_url');
    delete_option('teleship_user_consent');
    delete_option('teleship_installation_id');
    delete_option('teleship_account_id');
    delete_option('teleship_account_data');

    // Remove OAuth options (v2.0+)
    delete_option('teleship_client_id');
    delete_option('teleship_client_secret');
    delete_option('teleship_access_token');
    delete_option('teleship_refresh_token');
    delete_option('teleship_token_expires_at');
    delete_option('teleship_bearer_token');
    delete_option('teleship_bearer_token_expires_at');
    delete_option('teleship_connected_at');
    delete_option('teleship_webhook_id');
    delete_option('teleship_webhook_secret');

    // Remove any additional database entries created by the plugin
    global $wpdb;
    // Drop the order mapping table
    Teleship_Order_Sync::drop_mapping_table();

    // Delete any transients
    delete_transient('teleship_auth_transient');
    delete_transient('teleship_session_valid');

    // Delete user meta created by this plugin
    // Instead of direct query, get all users and delete meta properly
    // Note: For a large site with many users, this would be done in batches
    // but for uninstall routine, this approach is acceptable
    $user_ids = get_users(array('fields' => 'ids', 'number' => 1000));
    foreach ($user_ids as $user_id) {
        // Delete specific meta keys we know our plugin creates
        delete_user_meta($user_id, 'teleship_user_preferences');
        delete_user_meta($user_id, 'teleship_last_session');
        // Add any other specific meta keys used by the plugin
    }

    // Notify Teleship API about complete uninstallation
    $store_url = get_site_url();
    $domain = wp_parse_url($store_url, PHP_URL_HOST);

    // Build the API URL
    $api_url = teleship_get_api_url(); // Use the configured API URL
    $request_url = add_query_arg(
        array(
            'store_url' => $store_url,
            'domain' => $domain,
            'source' => 'plugin_uninstall',
            'platform' => 'woocommerce',
            'action' => 'permanent_uninstall'
        ),
        $api_url . '/api/platforms/' . TELESHIP_OAUTH_CLIENT_ID . '/uninstall'
    );

    // Notify Teleship about plugin uninstallation
    Teleship_HTTP_Client::post(
        $request_url,
        array(), // Empty data object
        array(
            'timeout'  => 45,
            'blocking' => false,
        )
    );
}

// Add admin menu
add_action('admin_menu', function() {
    add_menu_page(
        'Teleship',
        'Teleship',
        'manage_options',
        'teleship-app',
        'teleship_render_page',
        plugin_dir_url(__FILE__) . 'assets/images/favicon-16x16.png',
        56
    );

    add_submenu_page(
        'teleship-app',
        'International Orders',
        'International Orders',
        'manage_options',
        'teleship-app',
        'teleship_render_page'
    );

    add_submenu_page(
        'teleship-app',
        'Shipments',
        'Shipments',
        'manage_options',
        'teleship-shipments',
        'teleship_render_page'
    );

    add_submenu_page(
        'teleship-app',
        'Products',
        'Products',
        'manage_options',
        'teleship-hs-classifier',
        'teleship_render_page'
    );

    add_submenu_page(
        'teleship-app',
        'Settings',
        'Settings',
        'manage_options',
        'teleship-settings',
        'teleship_render_page'
    );
});

// Register and enqueue admin styles
add_action('admin_enqueue_scripts', function($hook) {
    $screen = get_current_screen();
    // Check if we're on any teleship page
    if (!$screen || strpos($screen->base, 'teleship') === false) {
        return;
    }

    // Register and enqueue the admin stylesheet
    wp_register_style(
        'teleship-admin-styles',
        plugins_url('assets/css/teleship-admin.css', __FILE__),
        array(),
        TELESHIP_VERSION
    );
    wp_enqueue_style('teleship-admin-styles');
});

// Process consent form submission
add_action('admin_init', function() {
    // Verify both POST variables are set
    if (!isset($_POST['teleship_give_consent']) || !isset($_POST['teleship_consent_nonce'])) {
        return;
    }

    // Verify nonce
    if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['teleship_consent_nonce'])), 'teleship_consent')) {
        return;
    }

    // Save consent to option
    update_option('teleship_user_consent', true);

    // Redirect to remove form submission from URL and refresh page
    if (isset($_GET['page'])) {
        $current_page = sanitize_text_field(wp_unslash($_GET['page']));
        wp_safe_redirect(admin_url('admin.php?page=' . $current_page));
        exit;
    } else {
        wp_safe_redirect(admin_url('admin.php?page=teleship-app'));
        exit;
    }
});

// Add consent screen function
function teleship_display_consent_screen() {
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Teleship Integration Setup', 'teleship-global-shipping'); ?></h1>
        <div class="notice notice-info">
            <p><?php esc_html_e('This plugin connects to Teleship services to provide shipping functionality.', 'teleship-global-shipping'); ?></p>
            <p><?php esc_html_e('The following data will be shared with Teleship:', 'teleship-global-shipping'); ?></p>
            <ul>
                <li><?php esc_html_e('Store URL and domain name', 'teleship-global-shipping'); ?></li>
                <li><?php esc_html_e('WordPress user ID (for authentication purposes)', 'teleship-global-shipping'); ?></li>
                <li><?php esc_html_e('Order data (when processing shipments)', 'teleship-global-shipping'); ?></li>
            </ul>
            <p><?php esc_html_e('By continuing, you agree to share this data with Teleship according to their Terms of Service.', 'teleship-global-shipping'); ?></p>
            <p><a href="https://teleship.com/termsofservice" target="_blank"><?php esc_html_e('View Teleship Terms of Service', 'teleship-global-shipping'); ?></a></p>
            <form method="post" action="">
                <?php wp_nonce_field('teleship_consent', 'teleship_consent_nonce'); ?>
                <button type="submit" name="teleship_give_consent" class="button button-primary"><?php esc_html_e('I Agree & Continue', 'teleship-global-shipping'); ?></button>
            </form>
        </div>
    </div>
    <?php
}

// Render page function
function teleship_render_page() {
    // Default page if none specified
    $page = 'app';

    // Sanitize and verify nonce if provided
    $nonce = null;
    if (!empty($_REQUEST['nonce'])) {
        $nonce = sanitize_text_field(wp_unslash($_REQUEST['nonce']));
    }

    // Process any $_GET or $_REQUEST data only if a valid nonce is provided
    // Special exception for the first load from admin menu which doesn't have a nonce
    $is_verified = !empty($nonce) && wp_verify_nonce($nonce, 'teleship_nonce');

    // Check if user is logged in
    if (!is_user_logged_in()) {
        auth_redirect();
        return;
    }

    // Only process page parameter if verification passed or it's the first load (admin menu click)
    // NOTE: This parameter is only used for determining which iframe content to show
    // and doesn't affect any sensitive operations, making this approach acceptable
    if (isset($_REQUEST['page'])) {
        // Check if nonce is verified OR if this is an initial admin menu access
        $is_admin_menu_access = false;
        if (isset($_SERVER['HTTP_REFERER'])) {
            // Sanitize HTTP_REFERER properly
            $http_referer = esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER']));
            $is_admin_menu_access = strpos($http_referer, 'wp-admin') !== false;
        }

        if ($is_verified || $is_admin_menu_access) {
            $page_param = sanitize_text_field(wp_unslash($_REQUEST['page']));
            $page = str_replace('teleship-', '', $page_param);
        }
    }

    // Gate all pages behind connection check — show setup page when disconnected
    if (!teleship_is_connected()) {
        teleship_render_setup_page();
        return;
    }

    // Connected: all pages render the iframe
    // Create safe parameters for the iframe URL
    $params = array(
        'store_url'   => get_site_url(),
        'platform'    => TELESHIP_OAUTH_CLIENT_ID,
        'page'        => $page,
        'headless'    => 'true',
        'transparent' => 'true',
        'account_id'  => teleship_oauth()->get_account_id(),
    );

    // Safely process whitelisted query parameters with proper verification
    $current_get = array();

    // SECURITY NOTE: These parameters are only used to determine iframe content URL
    // and do not affect any sensitive operations or expose private data
    // We also strictly limit which parameters are accepted
    $allowed_params = array('tab', 'section', 'order_id');

    // Verify nonce explicitly for plugin checker
    $nonce_verified = !empty($nonce) && wp_verify_nonce($nonce, 'teleship_nonce');

    // Process only safe parameters with explicit nonce verification
    if (isset($_GET) && is_array($_GET) && $nonce_verified) {
        foreach ($allowed_params as $param) {
            if (isset($_GET[$param])) {
                $current_get[$param] = sanitize_text_field(wp_unslash($_GET[$param]));
            }
        }
    }

    $query_params = array_merge($current_get, $params);

    // Get APP URL from helper function
    $app_url = teleship_get_app_url();
    $path = '/integrations/woocommerce';

    // Only append specific page path for non-default pages
    if ($page !== 'app') {
        $path .= '/' . $page;
    }

    $url = $app_url . $path . '?' . http_build_query($query_params);

    echo '<div class="teleship-container">';
    echo '<iframe id="teleship-iframe" src="' . esc_url($url) . '" frameborder="0" allowtransparency="true"></iframe>';
    echo '</div>';
    // Forward visibility changes to the iframe since cross-origin iframes
    // don't receive visibilitychange events from the parent tab.
    echo '<script>
    document.addEventListener("visibilitychange", function() {
        if (document.visibilityState === "visible") {
            var iframe = document.getElementById("teleship-iframe");
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({ type: "teleship:visibility", visible: true }, "*");
            }
        }
    });
    </script>';
}

/**
 * Render the setup page for disconnected state
 *
 * Shows a WooCommerce-styled onboarding wizard that guides users
 * through connecting their store to Teleship.
 */
function teleship_render_setup_page() {
    $wc_key_exists = (bool) get_option('teleship_wc_api_key_id');
    $connect_url = function_exists('teleship_connection') ? teleship_connection()->get_connect_url() : '#';
    ?>
    <div class="wrap">
        <div class="teleship-setup-page">
            <div class="teleship-setup-header">
                <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'assets/images/teleship-logo.svg'); ?>" alt="Teleship" class="teleship-setup-logo">
                <h1><?php esc_html_e('Connect Your Store', 'teleship-global-shipping'); ?></h1>
                <p class="teleship-setup-subtitle"><?php esc_html_e('Set up Teleship to enable global shipping, HS code classification, and real-time carrier rates for your WooCommerce store.', 'teleship-global-shipping'); ?></p>
            </div>

            <div class="teleship-setup-steps">
                <div class="teleship-step teleship-step--complete">
                    <div class="teleship-step__icon">
                        <span class="dashicons dashicons-yes-alt"></span>
                    </div>
                    <div class="teleship-step__content">
                        <h3><?php esc_html_e('WooCommerce Authorization', 'teleship-global-shipping'); ?></h3>
                        <p><?php esc_html_e('API keys will be generated automatically when you connect.', 'teleship-global-shipping'); ?></p>
                    </div>
                </div>

                <div class="teleship-step teleship-step--active">
                    <div class="teleship-step__icon">
                        <span class="teleship-step__number">2</span>
                    </div>
                    <div class="teleship-step__content">
                        <h3><?php esc_html_e('Connect to Teleship', 'teleship-global-shipping'); ?></h3>
                        <p><?php esc_html_e('Sign in or create your Teleship account to link your store. You\'ll be redirected back here automatically.', 'teleship-global-shipping'); ?></p>
                        <a href="<?php echo esc_url($connect_url); ?>" class="button button-primary button-hero teleship-setup-connect-btn">
                            <?php esc_html_e('Connect to Teleship', 'teleship-global-shipping'); ?>
                        </a>
                    </div>
                </div>
            </div>

            <div class="teleship-setup-footer">
                <p>
                    <?php
                    printf(
                        /* translators: %1$s is the opening anchor tag, %2$s is the closing anchor tag */
                        esc_html__('By connecting, you agree to the Teleship %1$sTerms of Service%2$s. Your store URL, user ID, and order data will be shared with Teleship to provide shipping services.', 'teleship-global-shipping'),
                        '<a href="https://teleship.com/termsofservice" target="_blank" rel="noopener">',
                        '</a>'
                    );
                    ?>
                </p>
                <p>
                    <a href="https://teleship.com/privacy" target="_blank" rel="noopener"><?php esc_html_e('Privacy Policy', 'teleship-global-shipping'); ?></a>
                </p>
            </div>
        </div>
    </div>
    <?php
    // Auto-set consent when user views the setup page (replaces old consent screen)
    if (!get_option('teleship_user_consent', false)) {
        update_option('teleship_user_consent', true);
    }
}

/**
 * Render the connected settings page
 *
 * Shows connection status, test/disconnect actions, and sync options
 * in a clean, WooCommerce-themed layout.
 */
function teleship_render_connected_settings() {
    $oauth = teleship_oauth();
    $status = $oauth->get_connection_status();
    $webhook_registered = teleship_webhook_manager()->is_registered();
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Teleship Settings', 'teleship-global-shipping'); ?></h1>

        <div class="teleship-settings-card teleship-settings-card--status">
            <h2>
                <span class="dashicons dashicons-yes-alt" style="color: #46b450; margin-right: 4px;"></span>
                <?php esc_html_e('Connected to Teleship', 'teleship-global-shipping'); ?>
            </h2>

            <table class="teleship-settings-table">
                <tr>
                    <th><?php esc_html_e('Account ID', 'teleship-global-shipping'); ?></th>
                    <td><code><?php echo esc_html($status['account_id']); ?></code></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Connected', 'teleship-global-shipping'); ?></th>
                    <td><?php echo esc_html($status['connected_at']); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Webhook', 'teleship-global-shipping'); ?></th>
                    <td>
                        <?php if ($webhook_registered) : ?>
                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span>
                            <?php esc_html_e('Registered', 'teleship-global-shipping'); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span>
                            <?php esc_html_e('Not registered', 'teleship-global-shipping'); ?>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>

            <div class="teleship-settings-actions">
                <button type="button" class="button" id="teleship-test-connection">
                    <?php esc_html_e('Test Connection', 'teleship-global-shipping'); ?>
                </button>
            </div>
        </div>

        <div class="teleship-sync-section">
            <h2><?php esc_html_e('Data Synchronization', 'teleship-global-shipping'); ?></h2>

            <div class="teleship-sync-grid">
                <div class="teleship-settings-card">
                    <h3><?php esc_html_e('Product Sync', 'teleship-global-shipping'); ?></h3>
                    <p><?php esc_html_e('Push all products to Teleship for HS code classification.', 'teleship-global-shipping'); ?></p>
                    <button type="button" class="button" id="teleship-sync-products">
                        <?php esc_html_e('Sync All Products', 'teleship-global-shipping'); ?>
                    </button>
                </div>

                <div class="teleship-settings-card">
                    <h3><?php esc_html_e('Order Sync', 'teleship-global-shipping'); ?></h3>
                    <p><?php esc_html_e('Push all orders with "Processing" status to Teleship.', 'teleship-global-shipping'); ?></p>
                    <button type="button" class="button" id="teleship-sync-orders">
                        <?php esc_html_e('Sync Processing Orders', 'teleship-global-shipping'); ?>
                    </button>
                </div>
            </div>

            <div id="teleship-sync-status" style="display: none;"></div>
        </div>
    </div>

    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Test connection handler
        $('#teleship-test-connection').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true).text('<?php esc_attr_e('Testing...', 'teleship-global-shipping'); ?>');

            $.post(ajaxurl, {
                action: 'teleship_test_connection',
                nonce: '<?php echo esc_js(wp_create_nonce('teleship_admin_nonce')); ?>'
            }, function(response) {
                if (response.success) {
                    alert('<?php esc_attr_e('Connection successful!', 'teleship-global-shipping'); ?>');
                } else {
                    alert('<?php esc_attr_e('Connection failed:', 'teleship-global-shipping'); ?>' + ' ' + response.data.message);
                }
            }).always(function() {
                $btn.prop('disabled', false).text('<?php esc_attr_e('Test Connection', 'teleship-global-shipping'); ?>');
            });
        });

        // Sync handlers
        function runSync(action) {
            var $status = $('#teleship-sync-status');
            var $btn = $(this);
            var originalText = $btn.text();

            $btn.prop('disabled', true).text('<?php esc_attr_e('Syncing...', 'teleship-global-shipping'); ?>');
            $status.show().html('<p><?php esc_attr_e('Synchronization in progress...', 'teleship-global-shipping'); ?></p>');

            $.post(ajaxurl, {
                action: action,
                nonce: '<?php echo esc_js(wp_create_nonce('teleship_admin_nonce')); ?>'
            }, function(response) {
                if (response.success) {
                    $status.html('<p class="teleship-sync-success"><span class="dashicons dashicons-yes-alt"></span> ' + response.data.message + '</p>');
                } else {
                    $status.html('<p class="teleship-sync-error"><span class="dashicons dashicons-dismiss"></span> ' + response.data.message + '</p>');
                }
            }).fail(function() {
                $status.html('<p class="teleship-sync-error"><span class="dashicons dashicons-dismiss"></span> <?php esc_attr_e('Sync failed. Please try again.', 'teleship-global-shipping'); ?></p>');
            }).always(function() {
                $btn.prop('disabled', false).text(originalText);
            });
        }

        $('#teleship-sync-products').on('click', function() {
            runSync.call(this, 'teleship_sync_products');
        });

        $('#teleship-sync-orders').on('click', function() {
            runSync.call(this, 'teleship_sync_orders');
        });
    });
    </script>
    <?php
}

// Handle authentication callback
function teleship_handle_auth_callback() {
    // Check for required parameters
    if (!isset($_GET['teleship_auth'])) {
        return;
    }

    // Verify nonce
    if (!isset($_GET['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'teleship_auth_callback')) {
        wp_die(esc_html__('Security check failed.', 'teleship-global-shipping'), esc_html__('Error', 'teleship-global-shipping'), array('response' => 403));
        return;
    }

    // Log the successful authentication
    if (defined('WP_DEBUG') && WP_DEBUG) {
        do_action('teleship_log', 'Teleship authentication successful');
    }

    // Redirect to the settings page
    wp_safe_redirect(admin_url('admin.php?page=teleship-settings&teleship_auth_success=1'));
    exit;
}
add_action('admin_init', 'teleship_handle_auth_callback');

// Display account status in the settings page
function teleship_display_account_status() {
    // Only run for admin users with proper capabilities
    if (!is_admin() || !current_user_can('manage_options')) {
        return;
    }

    // Check if we're on the settings page
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce not required for displaying read-only success message
    if (!isset($_GET['page'])) {
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce not required for displaying read-only success message
    $page = sanitize_text_field(wp_unslash($_GET['page']));

    if ($page !== 'teleship-settings') {
        return;
    }

    // Check if we have a successful authentication message to display
    // This is safe because we're only displaying a non-sensitive success message
    // The actual authentication happened in teleship_handle_auth_callback with proper nonce verification
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display of success message
    if (isset($_GET['teleship_auth_success'])) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display of success message
        $auth_success = sanitize_text_field(wp_unslash($_GET['teleship_auth_success']));

        if ($auth_success === '1') {
            add_action('admin_notices', function() {
                /* translators: Success message shown after successful Teleship account connection */
                echo '<div class="notice notice-success is-dismissible"><p>' .
                    esc_html__('Teleship connected successfully! Live shipping rates are now available.', 'teleship-global-shipping') .
                    '</p></div>';
            });
        }
    }
}
add_action('admin_init', 'teleship_display_account_status');

/**
 * Initialize Teleship shipping method
 */
function teleship_init_shipping_method() {
    require_once plugin_dir_path(__FILE__) . 'includes/class-wc-teleship-shipping-method.php';
}
add_action('woocommerce_shipping_init', 'teleship_init_shipping_method');

/**
 * Add Teleship shipping method to WooCommerce
 */
function teleship_add_shipping_method($methods) {
    $methods['teleship_shipping'] = 'WC_Teleship_Shipping_Method';
    return $methods;
}
add_filter('woocommerce_shipping_methods', 'teleship_add_shipping_method');

// Helper function to determine if Teleship is connected (with session validation)
function teleship_is_connected() {
    return teleship_validate_session();
}

/**
 * Validate Teleship session with transient caching
 *
 * Checks if the stored Teleship credentials are still valid.
 * Caches the result in a WordPress transient for 5 minutes.
 *
 * @return bool True if session is valid
 */
function teleship_validate_session() {
    // Simply check if local OAuth credentials exist
    // Never make API calls here — if credentials are saved, the user is "connected"
    // Disconnection only happens explicitly via plugin deactivation
    if (!function_exists('teleship_oauth')) {
        return false;
    }

    return teleship_oauth()->is_connected();
}


// Add custom styling and formatting for Teleship shipping rates
add_filter('woocommerce_cart_shipping_method_full_label', 'teleship_enhance_shipping_method_label', 10, 2);

/**
 * Enhance the display of Teleship shipping methods in cart and checkout
 *
 * @param string $label The original shipping method label
 * @param object $method The shipping method object
 * @return string Enhanced HTML for the shipping method
 */
function teleship_enhance_shipping_method_label($label, $method) {
    // Only apply to Teleship shipping methods
    if (strpos($method->id, 'teleship_shipping') === false) {
        return $label;
    }

    // Get meta data
    $meta = $method->get_meta_data();

    // Start building the enhanced label
    $enhanced_label = '<div class="teleship-shipping-option">';

    // Service name with delivery estimate
    $service_name = isset($meta['teleship_service_name']) ? $meta['teleship_service_name'] : '';
    $min_date = isset($meta['teleship_min_delivery_date']) ? new DateTime($meta['teleship_min_delivery_date']) : null;
    $max_date = isset($meta['teleship_max_delivery_date']) ? new DateTime($meta['teleship_max_delivery_date']) : null;

    // Use teleship_service_name from meta_data (preserves full name including "Duties prepaid")
    // Fall back to parsing the label if meta is not available
    if (empty($service_name)) {
        $original_label = $method->get_label();
        if (preg_match('/^(.*?)(\s*\(.*\))$/', $original_label, $matches)) {
            $service_name = $matches[1];
        } else {
            $service_name = $original_label;
        }
    }
    $enhanced_label .= '<div class="teleship-service-name">' . esc_html($service_name);

    $enhanced_label .= '</div>';

    // Add delivery estimate if available
    if ($min_date && $max_date) {
        $enhanced_label .= '<div class="teleship-delivery-estimate">';
        /* translators: %1$s is the minimum delivery date, %2$s is the maximum delivery date */
        $enhanced_label .= sprintf(
            /* translators: %1$s is the minimum delivery date, %2$s is the maximum delivery date */
            __('(Delivers %1$s - %2$s)', 'teleship-global-shipping'),
            esc_html($min_date->format('M j')),
            esc_html($max_date->format('M j'))
        );
        $enhanced_label .= '</div>';

        // Add delivery info if available
        if (!empty($meta['teleship_delivery_info'])) {
            $enhanced_label .= '<div class="teleship-delivery-info">' . esc_html($meta['teleship_delivery_info']) . '</div>';
        }
    }

    // Add any additional description if available
    if (!empty($meta['teleship_description'])) {
        $enhanced_label .= '<div class="teleship-description">' . esc_html($meta['teleship_description']) . '</div>';
    }

    // Close the container
    $enhanced_label .= '</div>';

    // Add CSS styles once
    static $styles_added = false;
    if (!$styles_added) {
        $styles_added = true;
        add_action('wp_footer', 'teleship_add_shipping_styles');
        add_action('admin_footer', 'teleship_add_shipping_styles');
    }

    return $enhanced_label;
}

/**
 * Add styles for enhanced shipping display
 */
function teleship_add_shipping_styles() {
    ?>
    <style>
        .teleship-shipping-option {
            display: flex;
            flex-direction: column;
            margin-left: 25px;
        }
        .teleship-service-name {
            font-weight: bold;
            font-size: 1.05em;
        }
        .teleship-delivery-estimate {
            color: #757575;
            font-size: 0.9em;
            margin-top: 3px;
        }
        .teleship-delivery-info {
            color: #757575;
            font-size: 0.9em;
            margin-top: 3px;
        }
        .teleship-description {
            font-size: 0.85em;
            color: #555;
            margin-top: 3px;
            line-height: 1.4;
        }
        /* Match the Shopify-style layout */
        .woocommerce-shipping-methods li {
            display: flex !important;
            align-items: flex-start !important;
            margin-bottom: 12px !important;
            padding: 10px !important;
            border-radius: 4px !important;
            transition: background-color 0.2s ease !important;
        }
        .woocommerce-shipping-methods li:hover {
            background-color: #f8f9fa !important;
        }
        .woocommerce-shipping-methods li input[type="radio"] {
            margin-top: 4px !important;
            margin-right: 8px !important;
        }
        /* Price styling to match Shopify checkout */
        .woocommerce-shipping-methods .woocommerce-Price-amount {
            font-weight: bold;
        }
        /* For checkout page specific styling */
        .woocommerce-checkout .woocommerce-shipping-methods li {
            border: 1px solid #e6e6e6 !important;
            margin-bottom: 8px !important;
        }
        .woocommerce-checkout .woocommerce-shipping-methods li.shipping-method-item--selected {
            border-color: #2c6ecb !important;
            background-color: #f0f5ff !important;
        }
    </style>
    <script>
    // Add selected class to the selected shipping method
    jQuery(document).ready(function($) {
        // Initially mark selected shipping method
        $('input.shipping_method:checked').closest('li').addClass('shipping-method-item--selected');

        // Update when shipping method changes
        $(document).on('change', 'input.shipping_method', function() {
            $('.woocommerce-shipping-methods li').removeClass('shipping-method-item--selected');
            $('input.shipping_method:checked').closest('li').addClass('shipping-method-item--selected');
        });
    });
    </script>
    <?php
}

// #region Shipment Tracking Display

/**
 * Display Teleship tracking info in order emails
 * Hooks into woocommerce_email_order_meta - same hook Royal Mail and other carriers use
 */
add_action('woocommerce_email_order_meta', 'teleship_display_tracking_in_email', 10, 4);

function teleship_display_tracking_in_email($order, $sent_to_admin, $plain_text, $email) {
    // Only show in customer-facing emails
    if ($sent_to_admin) {
        return;
    }

    // Only show in completed/shipped order emails
    $allowed_emails = array('customer_completed_order', 'customer_shipped_order');
    if (!in_array($email->id, $allowed_emails, true)) {
        return;
    }

    $tracking_number = $order->get_meta('_teleship_tracking_number');
    $tracking_url = $order->get_meta('_teleship_tracking_url');
    $carrier = $order->get_meta('_teleship_tracking_carrier');

    if (empty($tracking_number)) {
        return;
    }

    if ($plain_text) {
        echo "\n\n==========\n\n";
        echo esc_html__('SHIPMENT TRACKING', 'teleship-global-shipping') . "\n\n";
        echo esc_html__('Carrier: ', 'teleship-global-shipping') . esc_html($carrier) . "\n";
        echo esc_html__('Tracking Number: ', 'teleship-global-shipping') . esc_html($tracking_number) . "\n";
        if (!empty($tracking_url)) {
            echo esc_html__('Track your shipment: ', 'teleship-global-shipping') . esc_url($tracking_url) . "\n";
        }
        echo "\n==========\n\n";
    } else {
        ?>
        <div style="margin-bottom: 40px; padding: 20px; background-color: #f8f9fa; border-radius: 8px; border-left: 4px solid #2c6ecb;">
            <h2 style="color: #333; font-size: 18px; margin: 0 0 15px 0;">
                <?php esc_html_e('Shipment Tracking', 'teleship-global-shipping'); ?>
            </h2>
            <table cellspacing="0" cellpadding="6" style="width: 100%; border: none;">
                <tr>
                    <td style="padding: 6px 12px 6px 0; border: none;"><strong><?php esc_html_e('Carrier:', 'teleship-global-shipping'); ?></strong></td>
                    <td style="padding: 6px 0; border: none;"><?php echo esc_html($carrier); ?></td>
                </tr>
                <tr>
                    <td style="padding: 6px 12px 6px 0; border: none;"><strong><?php esc_html_e('Tracking Number:', 'teleship-global-shipping'); ?></strong></td>
                    <td style="padding: 6px 0; border: none;"><?php echo esc_html($tracking_number); ?></td>
                </tr>
                <?php if (!empty($tracking_url)) : ?>
                <tr>
                    <td colspan="2" style="padding: 15px 0 0 0; border: none;">
                        <a href="<?php echo esc_url($tracking_url); ?>"
                           style="display: inline-block; padding: 12px 24px; background-color: #2c6ecb; color: #ffffff; text-decoration: none; border-radius: 4px; font-weight: bold;">
                            <?php esc_html_e('Track Your Shipment', 'teleship-global-shipping'); ?>
                        </a>
                    </td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
        <?php
    }
}

/**
 * Display Teleship tracking info on My Account order view
 */
add_action('woocommerce_order_details_after_order_table', 'teleship_display_tracking_in_account', 10, 1);

function teleship_display_tracking_in_account($order) {
    $tracking_number = $order->get_meta('_teleship_tracking_number');
    $tracking_url = $order->get_meta('_teleship_tracking_url');
    $carrier = $order->get_meta('_teleship_tracking_carrier');
    $shipped_date = $order->get_meta('_teleship_shipped_date');

    if (empty($tracking_number)) {
        return;
    }

    ?>
    <section class="teleship-tracking-info" style="margin: 20px 0; padding: 20px; background-color: #f8f9fa; border-radius: 8px; border-left: 4px solid #2c6ecb;">
        <h2 style="font-size: 1.2em; margin: 0 0 15px 0;"><?php esc_html_e('Shipment Tracking', 'teleship-global-shipping'); ?></h2>
        <p><strong><?php esc_html_e('Carrier:', 'teleship-global-shipping'); ?></strong> <?php echo esc_html($carrier); ?></p>
        <p><strong><?php esc_html_e('Tracking Number:', 'teleship-global-shipping'); ?></strong> <?php echo esc_html($tracking_number); ?></p>
        <?php if (!empty($shipped_date)) : ?>
            <p><strong><?php esc_html_e('Shipped:', 'teleship-global-shipping'); ?></strong> <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($shipped_date))); ?></p>
        <?php endif; ?>
        <?php if (!empty($tracking_url)) : ?>
            <p style="margin-top: 15px;">
                <a href="<?php echo esc_url($tracking_url); ?>" class="button" target="_blank" rel="noopener">
                    <?php esc_html_e('Track Your Shipment', 'teleship-global-shipping'); ?>
                </a>
            </p>
        <?php endif; ?>
    </section>
    <?php
}

// #endregion Shipment Tracking Display
