<?php
namespace ARCHM\Admin;

if ( ! defined('ABSPATH') ) {
    // phpcs:ignore Universal.PHP.RequireExitDieParentheses.Missing
    exit;
}

use ARCHM\Helpers\AssetsRegister;

class Assets {


    // Use utilities trait.
    use \ARCHM\Helpers\Utilities;

    // phpcs:ignore PHPCompatibility.Classes.NewTypedProperties.Found
    private mixed $plugin_now;
    /**
     * Initiate the class
     *
     * @author Siam Maruf
     * @since 1.0
     */
    public function __construct() {
        global $pagenow;
        $this->plugin_now = $pagenow;
        add_action('admin_enqueue_scripts', [ $this, 'register_all_scripts' ], 5);
    }

    /**
     * Register Scripts and Styles
     *
     * @return void
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function register_all_scripts( $script_page ): void {
        // Include order edit pages for single order archive functionality
        $allowed_pages = [ 'woocommerce_page_wc-orders', 'toplevel_page_master-archives', 'shop_order', 'woocommerce_page_wc-orders--edit', 'edit-shop_order' ];

        if ( in_array($script_page, $allowed_pages, true) || $this->is_order_edit_page() ) {
            $scripts               = $this->register_scripts();
            $styles                = $this->register_styles();
            $this->archm_global_style();
            $this->custom_admin_scripts($script_page);

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ( isset($_GET['page']) ) {
                // Unsanitize and sanitize the 'page' input
                $page = sanitize_text_field(wp_unslash($_GET['page'])); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

                if ( str_contains($page, 'master-archives') ) {
                    new AssetsRegister($scripts, $styles);
                }
            }
        }

        $screen = get_current_screen();
        if ( 'dashboard' === $screen->id ) {
            $archive_notice_script = $this->archive_notice_scripts();
            new AssetsRegister($archive_notice_script, $this->register_dashboard_notice_styles());
        }
    }

    /**
     * Add Script file to the theme admin
     *
     * @return array[]
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.arrayFound
    public function register_scripts(): array {
        return [
            'app' => [
                'src'       => ARCHM_PLUGIN_BUILD . '/index.js',
                'deps'      => [ 'wp-element' ],
                'version'   => 1.0,
                'in_footer' => true,
                'localize'  => [
                    'baseEndpoint' => esc_url_raw(rest_url('archm/v1/')),
                    'apiNonce'     => wp_create_nonce('wp_rest'),
                ],
            ],
        ];
    }

    /**
     * Add archive notice script file to the theme admin
     *
     * @return array[]
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.arrayFound
    public function archive_notice_scripts(): array {
        return [
            'app' => [
                'src'       => ARCHM_PLUGIN_BUILD . '/admin-archiving-notice.js',
                'deps'      => [ 'wp-element' ],
                'version'   => 1.0,
                'in_footer' => true,
                'localize'  => [
                    'baseEndpoint' => esc_url_raw(rest_url('archm/v1/')),
                    'apiNonce'     => wp_create_nonce('wp_rest'),
                ],
            ],
        ];
    }

    /**
     * Add Style File To The Theme Admin
     *
     * @return string[][]
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.arrayFound
    public function register_styles(): array {
        return [
            'app' => [
                'src' => ARCHM_PLUGIN_BUILD . '/main.css',
            ],
        ];
    }

    /**
     * Add Style File To The Dashboard Notice Admin
     *
     * @return array[]
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.arrayFound
    public function register_dashboard_notice_styles(): array {
        return [
            'app' => [
                'src' => ARCHM_PLUGIN_BUILD . '/admin-archiving-notice.css',
            ],
        ];
    }

    /**
     * Add the custom styles for menu icon to the enqueued stylesheet
     * Only targets ArchiveMaster menu icon to prevent conflicts with other plugins
     *
     * @return void
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function archm_global_style(): void {
        $custom_css = '
			/* ArchiveMaster menu icon - very specific selector to avoid conflicts */
			#adminmenu li#toplevel_page_master-archives .wp-menu-image img,
			#adminmenu li.toplevel_page_master-archives .wp-menu-image img {
                max-width: 18px;
                height: auto;
                margin: 0 auto;
                padding: 9px 0px 0;
            }
            /* Protect FlexOrder menu icon from ArchiveMaster styles - match FlexOrder\'s expected size */
            #adminmenu li#toplevel_page_osgsw-admin div.wp-menu-image img,
            #adminmenu li.toplevel_page_osgsw-admin div.wp-menu-image img {
                margin: 8px !important;
                padding: 0 !important;
            }
        ';
        wp_add_inline_style('wp-admin', $custom_css);
    }

    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function custom_admin_scripts( $script_page ): void {
        $is_pro = false;
        if ( function_exists('master_archive_pro') ) {
            $is_pro = master_archive_pro()->license_status;
        }
        // Include order edit pages for single order archive functionality
        $allowed_pages = [ 'woocommerce_page_wc-orders', 'toplevel_page_master-archives', 'shop_order', 'woocommerce_page_wc-orders--edit', 'edit-shop_order' ];

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( in_array($script_page, $allowed_pages, true) || $this->is_order_edit_page() ) {
            wp_enqueue_style('wa-admin-css', ARCHM_PLUGIN_BUILD . '/other.css', [], ARCHM_PLUGIN_VERSION);

            // Enqueue archive order button styles
            wp_enqueue_style('archm-archive-order-button', ARCHM_PLUGIN_ASSETS . '/css/archive-order-button.css', [], ARCHM_PLUGIN_VERSION);

            // Ensure WordPress core scripts are loaded
            wp_enqueue_script('wp-i18n');
            wp_enqueue_script('wp-polyfill');

            // Load our scripts
            wp_enqueue_script('wa-admin-js', ARCHM_PLUGIN_BUILD . '/admin.js', [ 'jquery', 'wp-i18n', 'wp-polyfill' ], ARCHM_PLUGIN_VERSION, true);
            wp_enqueue_script('wa-sizzle', ARCHM_PLUGIN_ASSETS . '/js/sizzle.min.js', [ 'jquery' ], ARCHM_PLUGIN_VERSION, true);

            // Set up translations for JavaScript
            if ( function_exists('wp_set_script_translations') ) {
                wp_set_script_translations('wa-admin-js', 'archive-master', ARCHM_PLUGIN_PATH . 'languages');
            }

            wp_localize_script('wa-admin-js', 'archm_admin', [
                'ajax_url'          => admin_url('admin-ajax.php'),
                'admin_url'         => admin_url(),
                'home_url'          => home_url(),
                'assets_url'        => ARCHM_PLUGIN_ASSETS,
                'nonce'             => wp_create_nonce('archm-admin-nonce'),
                'rest_url'          => rest_url(),
                'rest_nonce'        => wp_create_nonce('wp_rest'),
                'orders_url'        => admin_url('edit.php?post_type=shop_order'),
                'archm_settings'    => $this->option()->get_all(),
                'is_pro'            => $is_pro,
                'pdo_sqlite_enable' => extension_loaded('pdo_sqlite') ? true : false,
                'orderStatuses'     => $this->get_wc_order_statuses(),
                'active_plugins'    => $this->get_active_plugins_info(),
                'flexorder_promo'   => \ARCHM\Admin\FlexOrderPromotion::get_localize_data(),
                'google'            => [
                    'user_email' => get_option('archive_master_google_user_email'),
                    'user_name'  => get_option('archive_master_google_user_name'),
                ],
            ]);

            // Add custom styles.
            $custom_styles = '
			.archm-upgrade-plan{
				display: flex;
				align-items: center;
			}
			.archm-upgrade-icon-text{
				color: #34D399;;
				font-size: 14px;
				font-weight: 600;
				Line-height: 20px;
				margin-right: 5px;
				text-transform: uppercase;
			}
			';
            wp_add_inline_style('wa-admin-css', $custom_styles);
        }
    }

    /**
     * Get WooCommerce order statuses
     *
     * @return array
     */
    private function get_wc_order_statuses() {
        if ( ! function_exists('wc_get_order_statuses') ) {
            return [];
        }

        // Get all order statuses
        $wc_statuses = wc_get_order_statuses();

        // Default WooCommerce statuses
        $default_statuses = [
            'wc-pending'        => 'Pending payment',
            'wc-processing'     => 'Processing',
            'wc-on-hold'        => 'On hold',
            'wc-completed'      => 'Completed',
            'wc-cancelled'      => 'Cancelled',
            'wc-refunded'       => 'Refunded',
            'wc-failed'         => 'Failed',
            'wc-checkout-draft' => 'Draft',
        ];

        $formatted_statuses = [];

        foreach ( $wc_statuses as $status_key => $status_label ) {
            $formatted_statuses[] = [
                'value'    => $status_key,
                'label'    => $status_label,
                'isCustom' => ! array_key_exists($status_key, $default_statuses),
            ];
        }

        return $formatted_statuses;
    }

    /**
     * Get information about active subscription and membership plugins
     *
     * @return array
     */
    private function get_active_plugins_info() {
        if ( ! function_exists('is_plugin_active') ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active_plugins = [
            'subscriptions' => [
                'woocommerce-subscriptions'     => is_plugin_active('woocommerce-subscriptions/woocommerce-subscriptions.php'),
                'subscriptions-for-woocommerce' => is_plugin_active('subscriptions-for-woocommerce/subscriptions-for-woocommerce.php'),
                'yith-woocommerce-subscription' => is_plugin_active('yith-woocommerce-subscription/init.php'),
            ],
            'memberships'   => [
                'woocommerce-memberships'    => is_plugin_active('woocommerce-memberships/woocommerce-memberships.php'),
                'membership-for-woocommerce' => is_plugin_active('membership-for-woocommerce/membership-for-woocommerce.php'),
            ],
        ];

        // Check if any subscription plugins are active
        $active_plugins['has_subscriptions'] = array_filter($active_plugins['subscriptions']);

        // Check if any membership plugins are active
        $active_plugins['has_memberships'] = array_filter($active_plugins['memberships']);

        return $active_plugins;
    }

    /**
     * Check if current page is order edit page
     *
     * @return bool
     */
    private function is_order_edit_page() {
        global $pagenow, $typenow;

        // Check for new HPOS order edit page
        if ( 'admin.php' === $pagenow && isset($_GET['page']) && 'wc-orders' === $_GET['page'] && isset($_GET['action']) && 'edit' === $_GET['action'] ) {
            return true;
        }

        // Check for classic order edit page
        if ( 'post.php' === $pagenow && isset($_GET['action']) && 'edit' === $_GET['action'] && 'shop_order' === $typenow ) {
            return true;
        }

        // Check post type on edit pages
        if ( 'shop_order' === $typenow && in_array($pagenow, [ 'post.php', 'post-new.php' ], true) ) {
            return true;
        }

        return false;
    }
}
