<?php

declare(strict_types=1);

use MyParcelNL\Sdk\src\Model\MyParcelRequest;

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

if (class_exists("WCMP_Assets")) {
    return new WCMP_Assets();
}

class WCMP_Assets
{
    public function __construct()
    {
        add_action("admin_enqueue_scripts", [$this, "enqueueScripts"], 9999);
    }

    public function enqueueScripts(): void
    {
        global $post_type;
        $screen = get_current_screen();

        // KRITIEK: Block ALL script loading on product pages (variable products fix)
        if ($screen && in_array($screen->id, ['product', 'edit-product'])) {
            return; // Exit immediately - no scripts at all
        }

        // Support both traditional shop_order and HPOS wc-orders screen
        $is_order_screen = ($post_type === "shop_order") || 
                          (is_object($screen) && $screen->id === "woocommerce_page_wc-orders");
        $is_myparcel_screen = (is_object($screen) && strpos($screen->id, "wcmp") !== false);
        
        if ($is_order_screen || $is_myparcel_screen) {
            self::enqueue_admin_scripts_and_styles();
        }

        $this->enqueueAdminScriptsForAllPages();
    }

    /**
     * Load styles & scripts
     */
    public static function enqueue_admin_scripts_and_styles(): void
    {
        // WC2.3+ load all WC scripts for shipping_method search!
        if (version_compare(WOOCOMMERCE_VERSION, "2.3", ">=")) {
            wp_enqueue_script("woocommerce_admin");
            wp_enqueue_script("iris");

            if (! wp_script_is("wc-enhanced-select", "registered")) {
                $suffix = defined("SCRIPT_DEBUG") && SCRIPT_DEBUG ? "" : ".min";
                wp_register_script(
                    "wc-enhanced-select",
                    WC()->plugin_url() . "/assets/js/admin/wc-enhanced-select" . $suffix . ".js",
                    ["jquery", version_compare(WC()->version, "3.2.0", ">=") ? "selectWoo" : "select2"],
                    WC_VERSION
                );
            }
            wp_enqueue_script("wc-enhanced-select");
            wp_enqueue_script("jquery-ui-sortable");
            wp_enqueue_script("jquery-ui-autocomplete");
            wp_enqueue_style(
                "woocommerce_admin_styles",
                WC()->plugin_url() . "/assets/css/admin.css",
                [],
                WC_VERSION
            );
        }

        wp_enqueue_script("thickbox");
        wp_enqueue_style("thickbox");
        self::enqueueJs('wcmp-admin', 'wcmp-admin.js', ['jquery', 'thickbox']);

        wp_localize_script(
            "wcmp-admin",
            "wcmp",
            [
                "api_url"                => (new MyParcelRequest())->getRequestUrl(),
                "actions"                => [
                    "export"        => WCMP_Export::EXPORT,
                    "export_return" => WCMP_Export::EXPORT_RETURN,
                    "export_order"  => WCMP_Export::EXPORT_ORDER,
                    "get_labels"    => WCMP_Export::GET_LABELS,
                    "modal_dialog"  => WCMP_Export::MODAL_DIALOG,
                ],
                "bulk_actions"           => [
                    "export"       => WCMYPA_Admin::BULK_ACTION_EXPORT,
                    "print"        => WCMYPA_Admin::BULK_ACTION_PRINT,
                    "export_print" => WCMYPA_Admin::BULK_ACTION_EXPORT_PRINT,
                ],
                "ajax_url"               => admin_url("admin-ajax.php"),
                "nonce"                  => wp_create_nonce(WCMYPA::NONCE_ACTION),
                "download_display"       => WCMYPA()->setting_collection->getByName(
                    WCMYPA_Settings::SETTING_DOWNLOAD_DISPLAY
                ),
                "ask_for_print_position" => WCMYPA()->setting_collection->isEnabled(
                    WCMYPA_Settings::SETTING_ASK_FOR_PRINT_POSITION
                ),
                "strings"                => [
                    "no_orders_selected" => __("You have not selected any orders!", "woocommerce-myparcel"),
                    "dialog"             => [
                        "return" => __("Export options", "woocommerce-myparcel")
                    ],
                ],
            ]
        );

        wp_enqueue_style(
            "wcmp-admin-styles",
            WCMYPA()->plugin_url() . "/assets/css/wcmp-admin-styles.css",
            [],
            WC_MYPARCEL_NL_VERSION,
            "all"
        );

        // Legacy styles (WC 2.1+ introduced MP6 style with larger buttons)
        if (version_compare(WOOCOMMERCE_VERSION, "2.1", "<=")) {
            wp_enqueue_style(
                "wcmp-admin-styles-legacy",
                WCMYPA()->plugin_url() . "/assets/css/wcmp-admin-styles-legacy.css",
                [],
                WC_MYPARCEL_NL_VERSION,
                "all"
            );
        }
    }

    /**
     * load scripts that should be available on all pages
     */
    private function enqueueAdminScriptsForAllPages(): void
    {
        // KRITIEK: Prevent loading on product edit pages to avoid conflicts with variable products
        $screen = get_current_screen();
        
        // Blacklist: Never load on these pages (causes conflicts)
        $blacklist = ['product', 'edit-product'];
        if ($screen && in_array($screen->id, $blacklist)) {
            return;
        }
        
        // Whitelist: Only load on these specific admin pages
        $allowed_pages = [
            'shop_order',
            'woocommerce_page_wc-orders',
            'woocommerce_page_wc-settings',
            'toplevel_page_wcmp-settings',
            'woocommerce_page_wcmp-settings'
        ];
        
        // Check if we're on an allowed page or a MyParcel page
        $is_allowed_page = false;
        if ($screen) {
            foreach ($allowed_pages as $page) {
                if ($screen->id === $page || strpos($screen->id, 'wcmp') !== false) {
                    $is_allowed_page = true;
                    break;
                }
            }
        }
        
        // Don't load on non-whitelisted pages
        if (!$is_allowed_page) {
            return;
        }
        
        wp_register_script(
            'wcmp-admin-all-pages',
            WCMYPA()->plugin_url() . '/assets/js/wcmp-admin-notices.js',
            ['jquery'],
            '1.0',
            false
        );

        wp_localize_script('wcmp-admin-all-pages', 'wcmp_params',
            [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce'    => wp_create_nonce(WCMYPA::NONCE_ACTION),
            ]
        );

        self::enqueueJs('wcmp-admin-all-pages', 'wcmp-admin-notices.js');
    }

    /**
     * @param  string $handle
     * @param  string $file
     * @param  array  $dependencies
     *
     * @return void
     */
    private static function enqueueJs(string $handle, string $file, array $dependencies = []): void
    {
        if ('development' === getenv('WP_ENV')) {
            $path = 'src';
        } else {
            $path = 'assets';
        }

        wp_enqueue_script(
            $handle,
            sprintf('%s/%s/js/%s', WCMYPA()->plugin_url(), $path, $file),
            $dependencies,
            WC_MYPARCEL_NL_VERSION
        );
    }
}

return new WCMP_Assets();
