<?php

namespace SMFWC\Shiperman\Admin;

use SMFWC\Shiperman\Orders_List_Table\SMFWC_Shiperman_Orders_List_Table;
use SMFWC\Shiperman\API\SMFWC_Shiperman_API;

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

class SMFWC_Shiperman_Admin
{
    // private $api_base_url = 'https://api.shiperman.com/api';

    private $orders_list_table;

    public function __construct()
    {
        add_action('init', [$this, 'init_session'], 1);

        add_action('admin_menu', [$this, 'add_admin_menu']);

        add_action('admin_head', [$this, 'highlight_menu_if_invalid']);

        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);

        add_action('admin_post_shiperman_login', [$this, 'process_login']);

        add_action('admin_post_shiperman_logout', [$this, 'process_logout']);

        add_action('admin_footer', [$this, 'add_shipment_modal_html']);

        add_action('wp_ajax_fetch_shipment_data', [$this, 'fetch_shipment_data']);

        add_action('admin_post_shiperman_connect', [$this, 'handle_connect_form']);

        add_action('admin_notices', [$this, 'show_connection_notice']);

        add_action('admin_notices', [$this, 'check_configuration_notice']);

        add_action('admin_notices', [$this, 'display_admin_notice_order_page'] );
    }

    public function init_session()
    {
        if (!session_id()) {
            session_start();
        }
    }

    public function add_admin_menu()
    {
        // Top-level menu (always available)
        $api_key = get_option('shiperman_api_key');
        if (!$api_key) {
            add_menu_page('Shiperman', 'Shiperman', 'manage_options', 'shiperman_connect', [$this, 'render_connect_page'], 'dashicons-lock', 6);
        } else {
            add_menu_page(
                'Shiperman',
                'Shiperman',
                'manage_options',
                'shiperman_home',
                [$this, 'render_home_page'],
                SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/images/shiperman-favicon-20x20.png',
                6
            );
            $order_page_hook = add_submenu_page('shiperman_home', 'Orders', 'Orders', 'manage_options', 'shiperman_orders', [$this, 'render_orders_page']);
            add_submenu_page('shiperman_home', 'Our Depos', 'Our Depos', 'manage_options', 'shiperman_depos', [$this, 'render_depos_page']);

            $invalid_count = count($this->get_products_missing_shipping_info());
            $label = 'Validate Shop';

            if ($invalid_count > 0) {
                $label .= sprintf(
                    ' <span style="color:red; font-weight:bold;">(%d ⚠️)</span>',
                    $invalid_count
                );
            } else {
                $label .= ' <span style="color:green; font-weight:bold;">✅</span>';
            }

            add_submenu_page(
                'shiperman_home',
                'Validate Shop',
                $label,
                'manage_options',
                'shiperman_validate_shop_tools',
                [$this, 'render_validate_shop_tools']
            );

            $pricing_label = 'Set Pricing';

            if (!$this->is_pricing_configured()) {
                $pricing_label .= ' <span style="color:red; font-weight:bold;">⚠️</span>';
            } else {
                $pricing_label .= ' <span style="color:green; font-weight:bold;">✅</span>';
            }

            add_submenu_page(
                'shiperman_home',
                'Set Pricing',
                $pricing_label,
                'manage_options',
                'shiperman_shipment_pricing',
                [$this, 'render_shipment_pricing_page']
            );


            add_submenu_page('shiperman_home', 'Settings', 'Settings', 'manage_options', 'shiperman_settings', [$this, 'render_settings_page']);


            // add_submenu_page('shiperman_home', 'Logout', 'Logout', 'manage_options', 'shiperman_logout', [$this, 'process_logout']);

            add_action("load-$order_page_hook", array($this, 'init_table'));
        }
    }

    public function is_pricing_configured()
    {
        // Get the serialized settings from the database
        $settings = get_option('woocommerce_shiperman_shipping_method_settings');

        // Check if the settings exist and are properly unserialized
        if ($settings && is_array($settings)) {
            $pricing_type = $settings['pricing_type'];

            // Debug output to check the fetched settings
            error_log('Pricing Type: ' . $pricing_type);

            if ($pricing_type === 'flat_rate') {
                $flat_rate = isset($settings['flat_rate_cost']) ? $settings['flat_rate_cost'] : '';
                error_log('Flat Rate Cost: ' . $flat_rate); // Debug output
                return !empty($flat_rate);
            } elseif ($pricing_type === 'margin_rate') {
                $margin_rate = isset($settings['margin_rate']) ? $settings['margin_rate'] : '';
                error_log('Margin Rate: ' . $margin_rate); // Debug output
                return !empty($margin_rate);
            }
        }

        return false;
    }


    public function highlight_menu_if_invalid()
    {
        $invalid_count = count($this->get_products_missing_shipping_info());
        if ($invalid_count === 0) return;

        echo <<<CSS
        <style>
            #adminmenu .toplevel_page_shiperman_home .wp-submenu li a[href*="shiperman_validate_shop_tools"] {
                color: #b40205 !important;
                font-weight: bold;
            }
        </style>
        CSS;

        if ($this->is_pricing_configured()) return;

        echo <<<CSS
        <style>
            #adminmenu .toplevel_page_shiperman_home .wp-submenu li a[href*="shiperman_shipment_pricing"] {
                color: #b40205 !important;
                font-weight: bold;
            }
        </style> 
        CSS;
    }

    public function check_configuration_notice()
    {
        // Get the serialized settings from the database
        $settings = get_option('woocommerce_shiperman_shipping_method_settings');

        // Check if settings exist and are properly unserialized
        if ($settings && is_array($settings)) {
            $pricing_type = isset($settings['pricing_type']) ? $settings['pricing_type'] : '';
            $flat_rate = isset($settings['flat_rate_cost']) ? $settings['flat_rate_cost'] : '';
            $margin_rate = isset($settings['margin_rate']) ? $settings['margin_rate'] : '';

            $errors = [];

            // Check for missing pricing type
            if (empty($pricing_type)) {
                $errors[] = __('Pricing Type is not configured.', 'shiperman-for-woocommerce');
            }

            // Validate Flat Rate Cost if Pricing Type is flat_rate
            if ($pricing_type === 'flat_rate' && (empty($flat_rate) || $flat_rate <= 0)) {
                $errors[] = __('Flat Rate Cost must be greater than zero. Otherwise configure Free Shipping in WooCommerce.', 'shiperman-for-woocommerce');
            }

            // Validate Margin Rate if Pricing Type is margin_rate
            if ($pricing_type === 'margin_rate' && (empty($margin_rate) || $margin_rate <= 0)) {
                $errors[] = __('Margin Rate Multiplier must be greater than zero. Otherwise configure Free Shipping in WooCommerce.', 'shiperman-for-woocommerce');
            }

            // If there are errors, display them as notices
            if (!empty($errors)) {
                echo '<div class="notice notice-error">';
                echo '<p><strong>' . __('Shiperman Shipping configuration issue:', 'shiperman-for-woocommerce') . '</strong></p>';
                echo '<ul>';
                foreach ($errors as $error) {
                    echo '<li>' . esc_html($error) . '</li>';
                }
                echo '</ul>';
                echo '</div>';
            }
        } else {
            // If the settings aren't available or not unserialized properly, show a general error
            echo '<div class="notice notice-error">';
            echo '<p><strong>' . __('Shiperman Shipping configuration issue:', 'shiperman-for-woocommerce') . '</strong> ' . __('Settings could not be loaded. Please check the plugin configuration.', 'shiperman-for-woocommerce') . '</p>';
            echo '</div>';
        }
    }



    public static function is_api_key_valid($api_key)
    {
        $response = wp_remote_get("https://api.shiperman.com/api/user", [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Accept' => 'application/json',
            ],
            'timeout' => 10,
        ]);
        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200;
    }

    public function show_connection_notice()
    {
        if (!current_user_can('manage_options')) return;

        // Limit notice to specific admin pages (e.g., Shiperman or WooCommerce settings)
        $screen = get_current_screen();
        if (!isset($screen->id)) return;

        // Show only on Shiperman settings or WooCommerce shipping section
        if (
            strpos($screen->id, 'shiperman') === false &&
            strpos($screen->id, 'woocommerce_page_wc-settings') === false
        ) {
            return;
        }

        if (!$this->is_logged_in()) {
?>
            <div class="notice notice-error">
                <p>
                    <?php echo wp_kses(
                        __('Shiperman is not connected. Please <a href="' . admin_url('admin.php?page=shiperman_connect') . '">connect your account</a> by entering the API key.', 'shiperman-for-woocommerce'),
                        ['a' => ['href' => []]]
                    ); ?>
                </p>
            </div>
        <?php
        }
    }


    public function init_table()
    {
        // Create an instance of the list table
        $this->orders_list_table = new \SMFWC\Shiperman\Orders_List_Table\SMFWC_Shiperman_Orders_List_Table();
    }

    public function enqueue_admin_scripts($hook_suffix)
    {

        $allowed_pages = [
            'toplevel_page_shiperman_connect',
            'toplevel_page_shiperman_home',
            'shiperman_page_shiperman_orders',
            'shiperman_page_shiperman_customers',
            'shiperman_page_shiperman_wallet',
            'shiperman_page_shiperman_settings',
            'toplevel_page_shiperman_login',
            'woocommerce_page_wc-orders',
            'edit.php'
        ];

        if (in_array($hook_suffix, $allowed_pages)) {
            wp_enqueue_style('shiperman_roboto_font', 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap', [], null);
            wp_register_style('shiperman_admin_css', SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/css/admin-styles.css', [], SMFWC_SHIPERMAN_PLUGIN_VERSION);
            wp_enqueue_style('shiperman_admin_css');

            wp_enqueue_script('jquery');
            wp_enqueue_script('shipment-modal-script', SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/js/shipment-modal.js', ['jquery'], SMFWC_SHIPERMAN_PLUGIN_VERSION, true);
            wp_enqueue_script(
                'shiperman-admin-script',
                plugins_url('/assets/js/admin-script.js', dirname(__FILE__, 2)), // Path to admin-script.js
                ['jquery'],
                SMFWC_SHIPERMAN_PLUGIN_VERSION, // Use plugin version constant for cache-busting
                true // Load script in footer
            );

            wp_localize_script('shipment-modal-script', 'shipmentModalData', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce'    => wp_create_nonce('view_shipment_nonce'),
            ]);
        }
    }


    public function render_connect_page()
    {
        $api_key = get_option('shiperman_api_key', '');
        $error = isset($_GET['connect_error']) ? true : false;
        ?>
        <div class="wrap">
            <div class="shiperman-title">
                <h1><?php esc_html_e('Connect to Shiperman', 'shiperman-for-woocommerce'); ?></h1>
            </div>
            <div class="shiperman-login-wrapper">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <?php wp_nonce_field('shiperman_connect_nonce', 'shiperman_connect_nonce'); ?>
                    <input type="hidden" name="action" value="shiperman_connect">

                    <div class="shiperman-form-table">
                        <div class="shiperman-logo">
                            <img src="<?php echo esc_url(SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/images/shiperman-logo.png'); ?>" alt="<?php esc_attr_e('Shiperman logo', 'shiperman-for-woocommerce'); ?>">
                        </div>

                        <div class="shiperman-form-field">
                            <label for="api_key"><?php esc_html_e('API Key:', 'shiperman-for-woocommerce'); ?></label>
                            <input type="text" name="api_key" id="api_key" value="<?php echo esc_attr($api_key); ?>" style="width: 100%; min-width: 300px;" required>
                            <p class="description"><?php esc_html_e('Paste your Shiperman API key here to connect.', 'shiperman-for-woocommerce'); ?></p>
                        </div>

                        <?php if ($error): ?>
                            <p style="color: red; text-align:center; font-size:16px;"><?php esc_html_e('Invalid API Key. Please try again.', 'shiperman-for-woocommerce'); ?></p>
                        <?php endif; ?>

                        <div class="shiperman-submit">
                            <button type="submit" class="shiperman-btn btn-primary"><?php esc_html_e('Connect', 'shiperman-for-woocommerce'); ?></button>
                        </div>

                        <div class="shiperman-form-field">
                            <a href="https://platform.shiperman.com/plugins" target="_blank" class="shiperman-link"><?php esc_html_e('Get your API key', 'shiperman-for-woocommerce'); ?></a>
                            <a href="https://platform.shiperman.com" target="_blank" class="shiperman-link"><?php esc_html_e('Open Shiperman Platform', 'shiperman-for-woocommerce'); ?></a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php
    }


    public function handle_connect_form()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'shiperman-for-woocommerce'));
        }

        if (!isset($_POST['shiperman_connect_nonce']) || !wp_verify_nonce($_POST['shiperman_connect_nonce'], 'shiperman_connect_nonce')) {
            wp_die(__('Invalid nonce', 'shiperman-for-woocommerce'));
        }

        $api_key = sanitize_text_field($_POST['api_key'] ?? '');

        // Validate via API
        $response = wp_remote_get("https://api.shiperman.com/api/plugin/info", [
            'headers' => [
                'X-API-KEY' => $api_key,
                'Accept' => 'application/json',
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {

            wp_safe_redirect(admin_url('admin.php?page=shiperman_connect&connect_error=1'));
            exit;
        }

        // Save the key
        update_option('shiperman_api_key', $api_key);

        // Redirect success
        wp_safe_redirect(admin_url('admin.php?page=shiperman_home'));
        exit;
    }

    private function validate_api_key_cached($api_key)
    {
        $cached = get_transient('shiperman_api_key_valid');
        if ($cached !== false) {
            return $cached;
        }

        $valid = $this->validate_api_key($api_key);
        set_transient('shiperman_api_key_valid', $valid, 15 * MINUTE_IN_SECONDS);
        return $valid;
    }


    private function validate_api_key($api_key)
    {
        $response = wp_remote_get('https://api.shiperman.com/api/plugin/info', [
            'headers' => [
                'X-API-KEY' => $api_key,
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        return $code === 200;
    }


    public function render_login_page()
    {

        if (!$this->is_logged_in()) {
            $this->redirect_to_login();
            return;
        }
    ?>
        <div class="wrap">
            <div class="shiperman-title">
                <h1><?php esc_html_e('Login', 'shiperman-for-woocommerce'); ?></h1>
            </div>
            <div class="shiperman-login-wrapper">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <?php wp_nonce_field('shiperman_form_nonce', 'shiperman_form_nonce'); ?>
                    <input type="hidden" name="action" value="shiperman_login">
                    <div class="shiperman-form-table <?php echo esc_attr(isset($_GET['login_error']) ? 'has-error' : ''); ?>">
                        <div class="shiperman-logo">
                            <img src="<?php echo esc_url(SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/images/shiperman-logo.png'); ?>" alt="<?php esc_attr_e('Shiperman logo', 'shiperman-for-woocommerce'); ?>">
                        </div>
                        <div class="shiperman-form-field">
                            <label for="email"><?php esc_html_e('Email:', 'shiperman-for-woocommerce'); ?></label>
                            <input type="email" name="email" id="email" required>
                        </div>
                        <div class="shiperman-form-field">
                            <label for="password"><?php esc_html_e('Password:', 'shiperman-for-woocommerce'); ?></label>
                            <input type="password" name="password" id="password" required>
                        </div>
                        <?php if (isset($_GET['login_error'])): ?>
                            <p style="color: red; text-align:center; font-size:18px; line-height: 30px;"><?php esc_html_e('Wrong email or password!', 'shiperman-for-woocommerce'); ?></p>
                        <?php endif; ?>
                        <div class="shiperman-submit">
                            <button type="submit" class="shiperman-btn btn-primary"><?php esc_html_e('Login', 'shiperman-for-woocommerce'); ?></button>
                        </div>
                        <div class="shiperman-form-field">
                            <a href="https://platform.shiperman.com" target="_blank" class="shiperman-link"><?php esc_html_e('Get Started', 'shiperman-for-woocommerce'); ?></a>
                            <a href="https://platform.shiperman.com/forgotten-password" target="_blank" class="shiperman-link forgot-password"><?php esc_html_e('Forgotten Password', 'shiperman-for-woocommerce'); ?></a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php
    }

    public function process_login()
    {
        if (!isset($_POST['shiperman_form_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['shiperman_form_nonce'])), 'shiperman_form_nonce')) {
            wp_die(esc_html__('Nonce verification failed.', 'shiperman-for-woocommerce'));
        }

        if (!isset($_POST['email']) || !isset($_POST['password'])) {
            wp_safe_redirect(admin_url('admin.php?page=shiperman_login&login_error=1'));
            exit;
        }

        $email = sanitize_text_field(sanitize_email(wp_unslash($_POST['email'])));
        $password = sanitize_text_field(wp_unslash($_POST['password']));

        $shiperman_api = SMFWC_Shiperman_API::get_instance();

        $data = $shiperman_api->get_access_token($email, $password);

        if (isset($data['data']['token'])) {
            // Save token in session or transient
            $this->init_session();
            $_SESSION['shiperman_jwt_token'] = $data['data']['token'];
            wp_safe_redirect(admin_url('admin.php?page=shiperman_home'));
        } else {
            wp_safe_redirect(admin_url('admin.php?page=shiperman_home&login_error=1'));
        }
        exit;
    }

    public function process_logout()
    {
        $this->init_session();

        // Unset all session variables
        $_SESSION = [];
        unset($_SESSION['shiperman_jwt_token']);
        unset($_SESSION['shiperman_email']);

        // Destroy the session cookie
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(
                session_name(),
                '',
                time() - 42000,
                $params["path"],
                $params["domain"],
                $params["secure"],
                $params["httponly"]
            );
        }

        // Destroy the session
        session_destroy();

        wp_safe_redirect(admin_url('admin.php?page=shiperman_home'));
        exit;
    }

    // private function is_logged_in()
    // {
    //     return isset($_SESSION['shiperman_jwt_token']);
    // }

    private function is_logged_in()
    {
        $api_key = get_option('shiperman_api_key', '');
        return !empty($api_key);
    }


    public function render_home_page()
    {
        if (!$this->is_logged_in()) {
            $this->redirect_to_login();
            return;
        }
    ?>
        <div class="wrap">
            <div class="shiperman-title">
                <h1><?php esc_html_e('Home', 'shiperman-for-woocommerce'); ?></h1>
            </div>

            <div class="shiperman-home-wrapper">
                <!-- <div class="shiperman-recent-orders"> -->
                <?php
                $endpoint = "plugin/orders?page=1&size=5";
                $shiperman_api = SMFWC_Shiperman_API::get_instance();

                $recent_orders = $shiperman_api->make_authenticated_request($endpoint);

                if ($recent_orders) {
                    $recent_orders = apply_filters('shiperman_recent_orders_data', $recent_orders);
                    wc_get_template(
                        'shiperman/homepage-content-v2.php',
                        ['recent_orders' => $recent_orders],
                        'woocommerce/',
                        SMFWC_SHIPERMAN_TEMPLATE_PATH
                    );
                }
                // else {
                //     echo '<p>' . esc_html__('No fetching orders!', 'shiperman-for-woocommerce') . ' </p>';
                // } 
                ?>
                <!-- </div> -->

                <?php
                $balance = '0.00';
                $currency = '€';
                $shiperman_api = SMFWC_Shiperman_API::get_instance();
                $wallet_response = $shiperman_api->make_authenticated_request('plugin/wallet');

                if (isset($wallet_response['status']) && 'success' === $wallet_response['status']) {
                    $balance = esc_html($wallet_response['data']['balance']);
                    $currency = $wallet_response['data']['currency'] === 'EUR' ? '€' : esc_html($wallet_response['data']['currency']);
                }
                ?>

                <div class="shiperman-wallet-section">

                    <div class="shiperman-wallet-row">
                        <div class="shiperman-wallet-card">
                            <div class="shiperman-wallet-balance">
                                <span><?php esc_html_e('Wallet Balance:', 'shiperman-for-woocommerce'); ?></span>
                                <span class="shiperman-wallet-balance--display">
                                    <?php echo esc_html(number_format($balance, 2)) . ' ' . esc_html($currency); ?>
                                </span>
                            </div>
                            <div class="wallet-add-more">
                                <button type="button" class="shiperman-btn" id="add-more-balance" onclick="window.open('https://platform.shiperman.com/wallets/0', '_blank')">
                                    <?php esc_html_e('Add balance', 'shiperman-for-woocommerce'); ?>
                                </button>
                            </div>
                        </div>

                        <!-- Help / Platform Link Card -->
                        <div class="shiperman-help-card">
                            <p class="shiperman-help-text"><?php esc_html_e('Need help? Visit the full platform for more tools and settings.', 'shiperman-for-woocommerce'); ?></p>
                            <div class="wallet-add-more">
                                <button type="button" class="shiperman-btn" id="help-more" onclick="window.open('https://platform.shiperman.com/help', '_blank')">
                                    <?php esc_html_e('Go To Platform', 'shiperman-for-woocommerce'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div><?php

            }

            public function render_orders_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }

                // Initialize the list table
                $this->orders_list_table->prepare_items();
                ?>
        <div class="wrap">
            <div class="shiperman-title">
                <h1><?php esc_html_e('Orders', 'shiperman-for-woocommerce'); ?></h1>
            </div>

            <div class="shiperman-orders-list-table-wrapper">
                <!-- Single form for all filters and the table -->
                <form method="get">
                    <!-- Preserve necessary URL parameters -->
                    <input type="hidden" name="page" value="shiperman_orders">

                    <?php
                    // Display extra table filters at the top (status and date filters)
                    // $this->orders_list_table->extra_tablenav('top');

                    // Display search box
                    $this->orders_list_table->search_box(
                        esc_html__('Search Orders', 'shiperman-for-woocommerce'),
                        'shiperman_search'
                    );

                    // Display the filtered results
                    $this->orders_list_table->display();
                    ?>
                </form>
            </div>
        </div>

        <!-- Add optional JavaScript for better filter experience -->
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Auto-submit form when filter status changes
                $('#filter-by-status').on('change', function() {
                    // Only auto-submit if no date filters are being used
                    if (!$('#filter-date-from').val() && !$('#filter-date-to').val()) {
                        $('input[name="filter_action"]').click();
                    }
                });
            });
        </script>
    <?php
            }

            public function render_customers_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }
                echo '<h1>' . esc_html__('Customers', 'shiperman-for-woocommerce') . '</h1>';
            }

            public function render_wallet_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }

                echo '<h1>' . esc_html__('Wallet', 'shiperman-for-woocommerce') . '</h1>';

                // Card design with wallet information
                echo '<div class="shiperman-wallet-card">';
                echo '<div class="shiperman-wallet-card-content">';
                echo '<h2>' . esc_html__('Your Shiperman Wallet', 'shiperman-for-woocommerce') . '</h2>';
                echo '<p>' . esc_html__('Your Wallet allows you to create shipments using Shiperman. You can top up your balance by visiting the platform at', 'shiperman-for-woocommerce') . ' <a href="https://platform.shiperman.com" target="_blank">https://platform.shiperman.com</a>. ' . esc_html__('Once you log-in you can add more.', 'shiperman-for-woocommerce') . '</p>';
                echo '</div>';
                echo '</div>';

                // Add some inline CSS for the card with yellow as main color (251,213,61)
                echo '<style>
                    .shiperman-wallet-card {
                        background: linear-gradient(135deg, rgb(251,213,61), rgb(226,192,55));
                        border-radius: 12px;
                        box-shadow: 0 8px 16px rgba(0,0,0,0.1);
                        color: #333;
                        margin: 20px 0;
                        overflow: hidden;
                        padding: 25px;
                        transition: all 0.3s ease;
                    }
                    
                    .shiperman-wallet-card:hover {
                        box-shadow: 0 12px 20px rgba(0,0,0,0.2);
                        transform: translateY(-5px);
                    }
                    
                    .shiperman-wallet-card-content h2 {
                        color: #222;
                        font-size: 24px;
                        margin-bottom: 15px;
                    }
                    
                    .shiperman-wallet-card-content p {
                        font-size: 16px;
                        line-height: 1.6;
                    }
                    
                    .shiperman-wallet-card-content a {
                        color: rgb(215, 0, 2);
                        text-decoration: none;
                        font-weight: bold;
                        transition: color 0.2s ease;
                    }
                    
                    .shiperman-wallet-card-content a:hover {
                        color: rgb(240, 6, 10);
                        text-decoration: underline;
                    }
                </style>';
            }

            public function render_depos_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }

                // Prepare the API endpoint
                $endpoint = "plugin/depos";
                $shiperman_api = SMFWC_Shiperman_API::get_instance();
                $response = $shiperman_api->make_authenticated_request($endpoint, 'GET');

                // Check for errors in the API request
                if (is_wp_error($response)) {
                    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Failed to fetch depos data. Please try again.', 'shiperman-for-woocommerce') . '</p></div>';
                    return;
                }

                // Decode the API response
                $depos_data = $response['data'];

                // Check if data is available
                if (empty($depos_data)) {
                    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('No depos data found.', 'shiperman-for-woocommerce') . '</p></div>';
                    return;
                }

                // Get WooCommerce shop country
                $shop_country = get_option('woocommerce_default_country');
                $shop_country_code = explode(':', $shop_country)[0]; // handles formats like "DE:BE"

                // Sort depos_data to move the shop country to the top
                usort($depos_data, function ($a, $b) use ($shop_country_code) {
                    if ($a['country'] === $shop_country_code) return -1;
                    if ($b['country'] === $shop_country_code) return 1;
                    return 0;
                });

                // Country name mapping function
                function get_country_name($country_code)
                {
                    $country_names = array(
                        'DE' => 'Germany',
                        'FR' => 'France',
                        'IT' => 'Italy',
                        'ES' => 'Spain',
                        'HU' => 'Hungary',
                        'PL' => 'Poland',
                        'CZ' => 'Czech Republic',
                        'NL' => 'The Netherlands',
                        // Add more countries as needed
                    );

                    return isset($country_names[$country_code]) ? $country_names[$country_code] : $country_code;
                }

                // Add CSS for the new card design
    ?>
        <style>
            .shiperman-depo-title {
                margin-bottom: 8px;
            }

            .shiperman-depo-subtitle {
                margin-bottom: 20px;
                font-size: 1rem;
                font-weight: 500;
            }


            .shiperman-depo-row {
                display: flex;
                flex-wrap: wrap;
                gap: 26px;
                /* margin-right: -15px; */
                margin-left: -15px;
            }

            .shiperman-depo-col {
                flex: 0 0 100%;
                max-width: 100%;
                padding-right: 15px;
                padding-left: 15px;
                margin-bottom: 20px;
            }

            @media (min-width: 768px) {
                .shiperman-depo-col {
                    flex: 0 0 50%;
                    max-width: 45%;
                }
            }

            .shiperman-depo-card {
                position: relative;
                display: flex;
                flex-direction: column;
                height: 100%;
                background-color: #e0e0e0;
                border-radius: 4px;
                padding: 16px;
                box-shadow: 0 0 12px 1px rgba(0, 0, 0, 0.1);
                transition: box-shadow 0.3s, transform 0.3s;
            }

            .shiperman-depo-card:hover {
                box-shadow: 0 0 24px 2px rgba(0, 0, 0, 0.22);
            }

            .shiperman-depo-card-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 16px;
            }

            .shiperman-depo-card-title {
                display: flex;
                align-items: center;
                font-size: 18px;
                font-weight: 500;
                margin: 0;
            }

            .shiperman-depo-text {
                font-size: 16px;
                font-weight: 500;
            }

            .shiperman-depo-avatar {
                width: 34px;
                height: 34px;
                margin-right: 16px;
                border-radius: 4px;
                overflow: hidden;
            }

            .shiperman-depo-avatar img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .shiperman-depo-copy-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                color: #D70002;
                background: transparent;
                border: none;
                width: 30px;
                height: 30px;
                border-radius: 50%;
                cursor: pointer;
                transition: background-color 0.2s;
            }

            .shiperman-depo-copy-btn:hover {
                background-color: rgba(0, 0, 0, 0.04);
            }

            .shiperman-depo-note {
                background-color: #e7f5ff;
                border-left: 4px solid #D70002;
                padding: 12px;
                margin-bottom: 16px;
                border-radius: 4px;
            }

            .shiperman-depo-card-content {
                line-height: 1.8;
            }

            .shiperman-depo-icon {
                color: #D70002;
                width: 16px;
                height: 16px;
                margin-right: 8px;
            }

            .dashicons-small {
                font-size: 16px;
                width: 16px;
                height: 16px;
                vertical-align: text-top;
            }
        </style>

        <div class="wrap">
            <div class="shiperman-depo-title">
                <h1><?php esc_html_e('Our Depos', 'shiperman-for-woocommerce'); ?></h1>
            </div>
            <div class="shiperman-depo-subtitle">
                <span><?php esc_html_e('Please ship your consolidated package to any of the depots listed below. You can use any courier service convenient to you.', 'shiperman-for-woocommerce'); ?></span>
            </div>
            <div class="shiperman-depo-row">
                <?php foreach ($depos_data as $depo): ?>
                    <?php $is_shop_country = $depo['country'] === $shop_country; ?>
                    <div class="shiperman-depo-col">
                        <div class="shiperman-depo-card <?php echo $is_shop_country ? 'shiperman-shop-highlight' : ''; ?>">
                            <div class="shiperman-depo-card-header">
                                <h2 class="shiperman-depo-card-title">
                                    <div class="shiperman-depo-avatar">
                                        <img src="<?php echo esc_url(SMFWC_SHIPERMAN_PLUGIN_URL . 'assets/images/flags/' . strtolower($depo['country']) . '.svg'); ?>"
                                            alt="<?php echo esc_attr(get_country_name($depo['country'])); ?>">
                                    </div>
                                    <?php echo esc_html(get_country_name($depo['country'])); ?>
                                </h2>
                                <button class="shiperman-depo-copy-btn"
                                    onclick="copyToClipboard(`<?php echo esc_js("{$depo['senderName']}\n{$depo['address']}, {$depo['city']}, {$depo['zip']}\n" . get_country_name($depo['country'])); ?>`)"
                                    title="<?php esc_attr_e('Copy address', 'shiperman-for-woocommerce'); ?>">
                                    <span class="dashicons dashicons-clipboard"></span>
                                </button>
                            </div>

                            <?php if (!empty($depo['note'])): ?>
                                <div class="shiperman-depo-note">
                                    <span class="display-note"><?php echo esc_html($depo['note']); ?></span>
                                </div>
                            <?php endif; ?>

                            <?php if ($is_shop_country): ?>
                                <div class="shiperman-depo-note" style="background-color: #D70002; border-left-color: #f90; color:white;">
                                    <span><?php esc_html_e('Physical address configured currently here', 'shiperman-for-woocommerce'); ?></span>
                                </div>
                            <?php endif; ?>

                            <div class="shiperman-depo-card-content">
                                <p class="shiperman-depo-text">
                                    <span class="dashicons dashicons-admin-users dashicons-small shiperman-depo-icon"></span>
                                    <?php echo esc_html($depo['senderName']); ?>
                                </p>
                                <p class="shiperman-depo-text">
                                    <span class="dashicons dashicons-location dashicons-small shiperman-depo-icon"></span>
                                    <?php echo esc_html($depo['address'] . ', ' . $depo['city'] . ', ' . $depo['zip']); ?>
                                </p>
                                <p class="shiperman-depo-text">
                                    <span class="dashicons dashicons-admin-home dashicons-small shiperman-depo-icon"></span>
                                    <?php echo esc_html(get_country_name($depo['country'])); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>

            </div>
        </div>

        <!-- Toast Container -->
        <div id="shiperman-toast" style="display:none; position:fixed; bottom:20px; right:20px; background:#D70002; color:#fff; padding:12px 20px; border-radius:8px; box-shadow:0 2px 6px rgba(0,0,0,0.3); z-index:9999; transition: opacity 0.3s ease;">
            <?php esc_html_e('Address copied to clipboard!', 'shiperman-for-woocommerce'); ?>
        </div>

        <script>
            function copyToClipboard(text) {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                // Show toast
                const toast = document.getElementById('shiperman-toast');
                toast.style.display = 'block';
                toast.style.opacity = '1';

                setTimeout(() => {
                    toast.style.opacity = '0';
                    setTimeout(() => toast.style.display = 'none', 300);
                }, 2000);
            }
        </script>
    <?php
            }


            public function render_settings_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }
                $url = admin_url('admin.php?page=wc-settings&tab=shiperman');
                wp_safe_redirect($url);
                exit;
            }

            public function render_shipment_pricing_page()
            {
                if (!$this->is_logged_in()) {
                    $this->redirect_to_login();
                    return;
                }
                $url = admin_url('admin.php?page=wc-settings&tab=shipping&section=shiperman_shipping_method');
                wp_safe_redirect($url);
                exit;
            }

            public function render_validate_shop_tools()
            {
                if (isset($_GET['shiperman_export_csv']) && current_user_can('manage_options')) {
                    $this->export_invalid_products_csv();
                    exit;
                }


                $invalid_products = $this->get_products_missing_shipping_info();

                echo '<div class="wrap">';
                echo '<h1>Products Missing Shipping Info</h1>';

                if (empty($invalid_products)) {
                    echo '<p style="color:green;">All products have valid shipping info 🎉</p>';
                } else {
                    $export_url = add_query_arg([
                        'page' => 'shiperman_validate_shop_tools',
                        'shiperman_export_csv' => 1,
                    ]);

                    echo '<p><a href="' . esc_url($export_url) . '" class="button button-primary">Export Invalid Products as CSV</a></p>';

                    echo '<table class="widefat fixed">';
                    echo '<thead><tr><th>Product</th><th>Weight</th><th>Length</th><th>Width</th><th>Height</th></tr></thead>';
                    echo '<tbody>';
                    foreach ($invalid_products as $product) {
                        echo '<tr>';
                        echo '<td>
                            <a href="' . get_edit_post_link($product->get_id()) . '">' . esc_html($product->get_name()) . '</a><br/>
                            <small>
                                <a href="' . get_edit_post_link($product->get_id()) . '">Edit</a> | 
                                <a href="' . admin_url('post.php?post=' . $product->get_id() . '&action=edit#shipping_product_data') . '">Quick Edit</a>
                            </small>
                        </td>';
                        echo '<td>' . esc_html($product->get_weight() ?: '—') . '</td>';
                        echo '<td>' . esc_html($product->get_length() ?: '—') . '</td>';
                        echo '<td>' . esc_html($product->get_width() ?: '—') . '</td>';
                        echo '<td>' . esc_html($product->get_height() ?: '—') . '</td>';
                        echo '</tr>';
                    }
                    echo '</tbody>';
                    echo '</table>';
                }

                echo '</div>';
            }

            private function export_invalid_products_csv()
            {
                $products = $this->get_products_missing_shipping_info();

                // Get domain and sanitize it
                $domain = parse_url(home_url(), PHP_URL_HOST);
                $domain = str_replace('.', '-', $domain); // e.g., example.com -> example-com

                // Generate timestamp
                $date = date('Y-m-d');

                // Combine for filename
                $filename = "{$date}_{$domain}_shiperman_shipping_invalid_products.csv";

                header('Content-Type: text/csv');
                header("Content-Disposition: attachment; filename=\"$filename\"");

                $output = fopen('php://output', 'w');
                fputcsv($output, ['Product Name', 'Product ID', 'Weight', 'Length', 'Width', 'Height']);

                foreach ($products as $product) {
                    fputcsv($output, [
                        $product->get_name(),
                        $product->get_id(),
                        $product->get_weight(),
                        $product->get_length(),
                        $product->get_width(),
                        $product->get_height(),
                    ]);
                }

                fclose($output);
            }


            private function get_products_missing_shipping_info()
            {
                $args = [
                    'status' => 'publish',
                    'limit'  => -1,
                    'type'   => ['simple', 'variable'],
                    'return' => 'objects'
                ];

                $products = wc_get_products($args);
                $invalid_products = [];

                foreach ($products as $product) {
                    // Skip virtual products (they are not shipped)
                    if ($product->is_virtual() || $product->is_downloadable()) {
                        continue;
                    }

                    if (! $this->is_product_shipping_info_valid($product)) {
                        $invalid_products[] = $product;
                    }
                }

                return $invalid_products;
            }


            private function is_product_shipping_info_valid($product)
            {
                return $product->get_weight() &&
                    $product->get_length() &&
                    $product->get_width() &&
                    $product->get_height();
            }


            public function redirect_to_login()
            {
                wp_safe_redirect(admin_url('admin.php?page=shiperman_connect'));
                exit;
            }


            public function add_shipment_modal_html()
            {
    ?>
        <div id="shipment-modal" style="display:none;">
            <div class="shipment-modal-content">
                <span class="close-modal">&times;</span>
                <h2><?php esc_html_e('Shipment Details', 'shiperman-for-woocommerce'); ?></h2>
                <p><strong><?php esc_html_e('Order Number:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-order-number"></span></p>
                <p><strong><?php esc_html_e('Internal ID:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-internal-id"></span></p>
                <p><strong><?php esc_html_e('Price:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-price"></span></p>
                <p><strong><?php esc_html_e('Weight:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-weight"></span></p>
                <p><strong><?php esc_html_e('Service Type:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-service-type"></span></p>
                <p><strong><?php esc_html_e('Item Value:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-item-value"></span></p>
                <p><strong><?php esc_html_e('Tracking Number:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-tracking-number"></span></p>
                <p><strong><?php esc_html_e('Service:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-service"></span></p>
                <p><strong><?php esc_html_e('Carrier:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-carrier"></span></p>
                <p><strong><?php esc_html_e('Carrier Tracking Number:', 'shiperman-for-woocommerce'); ?></strong> <span id="shipment-carrier-tracking-number"></span></p>
                <p><strong><?php esc_html_e('Carrier Tracking URL:', 'shiperman-for-woocommerce'); ?></strong> <a id="shipment-tracking-url" href="#" target="_blank"><?php esc_html_e('Track Shipment', 'shiperman-for-woocommerce'); ?></a></p>
                <p><strong><?php esc_html_e('Download Label:', 'shiperman-for-woocommerce'); ?></strong> <a id="shipment-pdf-link" href="#" target="_blank"><?php esc_html_e('Download PDF', 'shiperman-for-woocommerce'); ?></a></p>
            </div>
        </div>
<?php
            }

            public function fetch_shipment_data()
            {
                check_ajax_referer('view_shipment_nonce', 'security');

                $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
                if (!$order_id) {
                    wp_send_json_error(esc_html__('Invalid Order ID', 'shiperman-for-woocommerce'));
                }

                /* $logger = new \WC_Logger(); */
                /* $log_context = 'Shipment meta'; */

                /* $logger->add($log_context, 'Order id ' . esc_html($order_id)); */

                // Get shipment data from post meta
                $shipment_data = get_post_meta($order_id, '_shiperman_shipment_data', true);
                /* $logger->add($log_context, 'Shipment Data ' . print_r($shipment_data, true)); */

                if (empty($shipment_data)) {
                    wp_send_json_error(esc_html__('No shipment data found.', 'shiperman-for-woocommerce'));
                }

                $pdf_url = '';
                if (!empty($shipment_data['items'][0]['label_image'])) {
                    $pdf_url = $this->save_base64_pdf($shipment_data['items'][0]['label_image'], $shipment_data['items'][0]['tracking_number'], $shipment_data['reference_id']);

                    if (is_wp_error($pdf_url)) {
                        wp_send_json_error(esc_html__('PDF url not found!', 'shiperman-for-woocommerce'));
                    }
                }

                $response_data = [
                    'order_number'              => isset($shipment_data['reference_id']) ? esc_html($shipment_data['reference_id']) : '',
                    'internal_id'               => isset($shipment_data['internal_id']) ? esc_html($shipment_data['internal_id']) : '',
                    'price'                     => isset($shipment_data['items'][0]['price']) ? esc_html($shipment_data['items'][0]['price']) : '',
                    'weight'                    => isset($shipment_data['items'][0]['weight']) ? esc_html($shipment_data['items'][0]['weight']) : '',
                    'item_value'                => isset($shipment_data['items'][0]['item_value']) ? esc_html($shipment_data['items'][0]['item_value']) : '',
                    'carrier'                   => isset($shipment_data['items'][0]['carrier']) ? esc_html($shipment_data['items'][0]['carrier']) : '',
                    'carrier_tracking_number'   => isset($shipment_data['items'][0]['carrier_tracking_number']) ? esc_html($shipment_data['items'][0]['carrier_tracking_number']) : '',
                    'service_type'              => isset($shipment_data['items'][0]['service_type']) ? esc_html($shipment_data['items'][0]['service_type']) : '',
                    'service'                   => isset($shipment_data['items'][0]['service']) ? esc_html($shipment_data['items'][0]['service']) : '',
                    'tracking_number'           => isset($shipment_data['items'][0]['tracking_number']) ? esc_html($shipment_data['items'][0]['tracking_number']) : '',
                    'tracking_url'              => isset($shipment_data['items'][0]['carrier_tracking_url']) ? esc_url($shipment_data['items'][0]['carrier_tracking_url']) : '',
                    'pdf_url'                   => esc_url($pdf_url),
                ];

                /* $logger->add($log_context, '$response_data ' . print_r($response_data, true)); */

                wp_send_json_success($response_data);
            }


            public function save_base64_pdf($base64_pdf, $tracking_number, $reference_id)
            {
                // Ensure WP_Filesystem is loaded
                if (! function_exists('get_filesystem_method')) {
                    require_once ABSPATH . 'wp-admin/includes/file.php';
                }

                // Initialize WP_Filesystem
                global $wp_filesystem;
                if (empty($wp_filesystem)) {
                    \WP_Filesystem();
                }

                // Get the upload directory
                $upload_dir = wp_upload_dir();
                $pdf_dir = $upload_dir['basedir'] . '/shiperman_pdfs';
                $pdf_url = $upload_dir['baseurl'] . '/shiperman_pdfs';

                // Ensure the directory exists
                if (! $wp_filesystem->is_dir($pdf_dir)) {
                    // Create the directory using WP_Filesystem
                    $wp_filesystem->mkdir($pdf_dir, 0755);
                }


                // Handle base64 PDF data
                if (preg_match('/^data:application\/pdf;base64,/', $base64_pdf)) {
                    $base64_pdf = substr($base64_pdf, strpos($base64_pdf, ',') + 1);
                }

                $pdf_data = base64_decode($base64_pdf);
                if ($pdf_data === false) {
                    // Return an error response if decoding fails
                    wp_send_json_error(__('Base64 decoding failed.', 'shiperman-for-woocommerce'));
                }

                // Set the PDF file path
                $pdf_file = "$pdf_dir/{$tracking_number}_{$reference_id}.pdf";

                // Write the PDF data to the file using WP_Filesystem
                if (! $wp_filesystem->put_contents($pdf_file, $pdf_data, FS_CHMOD_FILE)) {
                    wp_send_json_error(__('Failed to write PDF file.', 'shiperman-for-woocommerce'));
                }

                return "$pdf_url/{$tracking_number}_{$reference_id}.pdf";
            }

            /**
             * Display an admin notice on the WooCommerce Orders page.
             */
            public function display_admin_notice_order_page() {
                global $pagenow;
                // Check if it's the WooCommerce order edit page
                if ( $pagenow === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order' || $pagenow === 'admin.php' && isset($_GET['page']) && $_GET['page'] === 'wc-orders' ) {
                    echo '<div class="notice notice-error"><p style="color:red;"><strong>Note:</strong> Please enter the shipment weight. If left blank, a default value of 1 kg will be applied. Once the actual weight is verified, the charge will be adjusted accordingly to reflect the correct amount.</p></div>';
                }
            }
        }
