<?php
/**
 * Enqueues admin CSS and JS only on plugin pages.
 *
 * @package SkyEmagSync
 */

namespace SkyEmagSync\Admin;

defined( 'ABSPATH' ) || exit;

class Assets {

    /** Admin page slugs we own. */
    private const OUR_PAGES = [
        Menu::SETTINGS_SLUG,
        Menu::PRODUCTS_SLUG,
        Menu::CATEGORY_MAP_SLUG,
        Menu::CHAR_MAP_SLUG,
        Menu::FAMILY_MAP_SLUG,
        Menu::PUBLISH_SLUG,
        Menu::ORDERS_SLUG,
        Menu::NOTIFICATIONS_SLUG,
        Menu::LOGS_SLUG,
        Menu::HELP_SLUG,
        Menu::SETUP_SLUG,
    ];

    public function register(): void {
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
    }

    public function enqueue( string $hook ): void {
        // Setup wizard has its own scoped assets and bypasses the regular
        // admin enqueue (no jQuery, no admin.js).
        if ( false !== strpos( $hook, Menu::SETUP_SLUG ) ) {
            $this->enqueue_wizard_assets();
            return;
        }

        // $hook format: toplevel_page_wc-emag-sync  or  wc-emag-sync_page_wc-emag-sync-products
        $on_our_page = false;
        foreach ( self::OUR_PAGES as $slug ) {
            if ( strpos( $hook, $slug ) !== false ) {
                $on_our_page = true;
                break;
            }
        }

        // CSS-only enqueue for the WC Orders list table, so the eMAG badge
        // styling lands on imported orders. Both legacy CPT and HPOS hooks
        // are checked. JS / localization stay scoped to plugin pages.
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only $_GET inspection to detect WC screens, no state mutation.
        $is_wc_orders_list = (
            ( 'edit.php' === $hook && isset( $_GET['post_type'] ) && 'shop_order' === sanitize_key( wp_unslash( $_GET['post_type'] ) ) )
            || 'woocommerce_page_wc-orders' === $hook
        );

        // Single order edit screen — CSS + JS both needed for AWB meta box.
        // CPT mode: post.php with a shop_order post. HPOS mode: wc-orders with ?action=edit.
        $is_wc_order_edit = (
            ( 'post.php' === $hook && isset( $_GET['post'] )
                && 'shop_order' === get_post_type( absint( wp_unslash( $_GET['post'] ) ) ) )
            || ( false !== strpos( $hook, 'wc-orders' ) && isset( $_GET['action'] ) && 'edit' === sanitize_key( wp_unslash( $_GET['action'] ) ) )
        );
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        if ( ! $on_our_page && ! $is_wc_orders_list && ! $is_wc_order_edit ) {
            return;
        }

        wp_enqueue_style(
            'skyemag-admin',
            SKYEMAG_PLUGIN_URL . 'assets/css/admin.css',
            [],
            SKYEMAG_VERSION
        );

        if ( ! $on_our_page && ! $is_wc_order_edit ) {
            return; // WC Orders list — only the stylesheet is needed.
        }

        wp_enqueue_script(
            'skyemag-admin',
            SKYEMAG_PLUGIN_URL . 'assets/js/admin.js',
            [ 'jquery' ],
            SKYEMAG_VERSION,
            true
        );

        wp_localize_script( 'skyemag-admin', 'skyemagAdmin', [
            'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
            'wizardDismissNonce'  => wp_create_nonce( SetupWizard::NONCE ),
            // 3.8.0 async sync nonces — surfaced globally so the modal on
            // Products page can poll progress without separately rendering
            // hidden nonce inputs on that page. SettingsPage still embeds
            // hidden inputs for the inline progress section.
            'syncStartNonce'      => wp_create_nonce( SettingsPage::SYNC_START_AJAX ),
            'syncProgressNonce'   => wp_create_nonce( SettingsPage::SYNC_PROGRESS_AJAX ),
            'syncCancelNonce'     => wp_create_nonce( SettingsPage::SYNC_CANCEL_AJAX ),
            'i18n'                => [
                'confirmSync'    => __( 'Run a full sync now?', 'skyservers-product-sync-for-emag' ),
                /* translators: %d: number of filtered products */
                'confirmSyncAll' => __( 'Sync all %d filtered products now?', 'skyservers-product-sync-for-emag' ),
                /* translators: %d: number of filtered products */
                'confirmBulkAll' => __( 'Apply to all %d filtered products?', 'skyservers-product-sync-for-emag' ),
                'saving'         => __( 'Saving…', 'skyservers-product-sync-for-emag' ),
                'saved'          => __( 'Saved', 'skyservers-product-sync-for-emag' ),
                'error'          => __( 'Error', 'skyservers-product-sync-for-emag' ),
                'noSelection'    => __( 'Please select at least one product.', 'skyservers-product-sync-for-emag' ),
                'enterMargin'    => __( 'Please enter a margin % value.', 'skyservers-product-sync-for-emag' ),
                /* translators: %d: WC product id */
                'marginHistoryTitle' => __( 'Margin history — product #%d', 'skyservers-product-sync-for-emag' ),
                'inherited'      => __( '(inherited)', 'skyservers-product-sync-for-emag' ),
                'noHistory'      => __( 'No margin changes recorded yet.', 'skyservers-product-sync-for-emag' ),
                'revertTo'       => __( 'Revert to', 'skyservers-product-sync-for-emag' ),
                'when'           => __( 'When', 'skyservers-product-sync-for-emag' ),
                'change'         => __( 'Change', 'skyservers-product-sync-for-emag' ),
                'loading'        => __( 'Loading…', 'skyservers-product-sync-for-emag' ),
                /* translators: %1$d: shown count, %2$d: total count */
                'showingLast'    => __( 'Showing last %1$d of %2$d changes.', 'skyservers-product-sync-for-emag' ),
                'syncStarted'    => __( 'Sync started in background…', 'skyservers-product-sync-for-emag' ),
                'syncStarting'   => __( 'Starting sync…', 'skyservers-product-sync-for-emag' ),
                'syncInProgress' => __( 'Sync in progress', 'skyservers-product-sync-for-emag' ),
                'syncComplete'   => __( 'Sync complete', 'skyservers-product-sync-for-emag' ),
                'syncCancelled'  => __( 'Sync cancelled', 'skyservers-product-sync-for-emag' ),
                'syncCancel'     => __( 'Cancel', 'skyservers-product-sync-for-emag' ),
                'syncCancelling' => __( 'Cancelling…', 'skyservers-product-sync-for-emag' ),
                'syncConfirmCancel' => __( 'Cancel the sync that is currently running? Batches already in flight will still finish.', 'skyservers-product-sync-for-emag' ),
                'syncETA'        => __( 'ETA', 'skyservers-product-sync-for-emag' ),
                'syncQueuedFmt'  => __( 'Sync queued: %1$d products in %2$d batches.', 'skyservers-product-sync-for-emag' ),
                'syncSummaryFmt' => __( '%1$d synced, %2$d skipped, %3$d failed.', 'skyservers-product-sync-for-emag' ),
                'noEligibleSync' => __( 'No sync-enabled products were found.', 'skyservers-product-sync-for-emag' ),
                'close'          => __( 'Close', 'skyservers-product-sync-for-emag' ),
            ],
        ] );
    }

    private function enqueue_wizard_assets(): void {
        wp_enqueue_style(
            'skyemag-wizard',
            SKYEMAG_PLUGIN_URL . 'assets/css/wizard.css',
            [],
            SKYEMAG_VERSION
        );
        wp_enqueue_script(
            'skyemag-wizard',
            SKYEMAG_PLUGIN_URL . 'assets/js/wizard.js',
            [],
            SKYEMAG_VERSION,
            true
        );

        $cfg = [
            'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
            'adminPostUrl'       => admin_url( 'admin-post.php' ),
            'settingsUrl'        => admin_url( 'admin.php?page=' . Menu::SETTINGS_SLUG ),
            'nonce'              => wp_create_nonce( SetupWizard::NONCE ),
            // Settings page nonce — needed by the Step 5 Detect button which
            // reuses SettingsPage::ajax_detect_sources(). The handler validates
            // capability + premium independently, so cross-page reuse is safe.
            'settingsNonce'      => wp_create_nonce( 'skyemag_settings_nonce' ),
            'bootstrapImporting' => __( 'Importing offers from eMAG…', 'skyservers-product-sync-for-emag' ),
            'bootstrapDone'      => __( 'Imported — Run again?', 'skyservers-product-sync-for-emag' ),
            'copiedLabel'        => __( 'Copied', 'skyservers-product-sync-for-emag' ),
            'testingLabel'       => __( 'Testing…', 'skyservers-product-sync-for-emag' ),
            'detectingLabel'    => __( 'Scanning your products…', 'skyservers-product-sync-for-emag' ),
            'detectNoneLabel'   => __( 'No matching meta keys found in your product catalog.', 'skyservers-product-sync-for-emag' ),
            'detectErrorLabel'  => __( 'Detection failed. Try again or fill the field manually.', 'skyservers-product-sync-for-emag' ),
        ];
        wp_add_inline_script(
            'skyemag-wizard',
            'window.skyemagWizardCfg = ' . wp_json_encode( $cfg ) . ';',
            'before'
        );
    }
}
