<?php
/**
 * ZERTI — WooCommerce product CSV import/export (same behavior as WC admin, zerti UI).
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Whether WooCommerce itself is active (same signal as other inventory screens).
 */
function zerti_is_woocommerce_active(): bool
{
    return class_exists('WooCommerce') || function_exists('WC');
}

/**
 * Load WC product CSV exporter class file when WooCommerce is active.
 */
function zerti_bootstrap_wc_product_exporter(): bool
{
    if (!zerti_is_woocommerce_active()) {
        return false;
    }

    if (class_exists('WC_Product_CSV_Exporter', false)) {
        return true;
    }

    if (!defined('WC_ABSPATH')) {
        return false;
    }

    $path = WC_ABSPATH . 'includes/export/class-wc-product-csv-exporter.php';

    if (!is_readable($path)) {
        return false;
    }

    include_once $path;

    return class_exists('WC_Product_CSV_Exporter', false);
}

/**
 * WooCommerce active and product CSV tools available.
 */
function zerti_product_import_export_available(): bool
{
    return zerti_bootstrap_wc_product_exporter();
}

/**
 * @return bool
 */
function zerti_product_import_allowed(): bool
{
    return current_user_can('edit_products') && current_user_can('import');
}

/**
 * @return bool
 */
function zerti_product_export_allowed(): bool
{
    return current_user_can('edit_products') && current_user_can('export');
}

/**
 * Admin URL for inventory › backup (import/export) with optional query args.
 *
 * @param array<string, scalar> $query
 */
function zerti_product_import_export_url(array $query = []): string
{
    $base = zerti_admin_route_url([
        'tab' => 'inventory',
        'inv' => 'import-export',
    ]);

    if ($query === []) {
        return $base;
    }

    return add_query_arg($query, $base);
}

/**
 * Active mode: import wizard, export form, or hub (tabs).
 */
function zerti_product_import_export_mode(): string
{
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only admin navigation; values sanitized below.
    if (isset($_GET['step']) && is_string($_GET['step'])) {
        $step = sanitize_key(wp_unslash($_GET['step']));
        if ($step !== '') {
            return 'import';
        }
    }

    if (isset($_GET['zerti_ie'])) {
        $mode = sanitize_key(wp_unslash((string) $_GET['zerti_ie']));
        if ($mode === 'import' || $mode === 'export') {
            return $mode;
        }
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return 'hub';
}

/**
 * Load WC importer controller dependencies.
 */
function zerti_bootstrap_wc_product_importer(): bool
{
    if (!zerti_is_woocommerce_active()) {
        return false;
    }

    zerti_bootstrap_wc_product_exporter();

    if (!class_exists('WP_Importer', false)) {
        $wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
        if (is_readable($wp_importer)) {
            require_once $wp_importer;
        }
    }

    if (!class_exists('WC_Product_CSV_Importer_Controller', false)) {
        include_once WC_ABSPATH . 'includes/import/class-wc-product-csv-importer.php';
        include_once WC_ABSPATH . 'includes/admin/importers/class-wc-product-csv-importer-controller.php';
    }

    return class_exists('WC_Product_CSV_Importer_Controller', false);
}

zerti_bootstrap_wc_product_importer();

/**
 * Zerti-scoped product CSV importer (redirects stay inside zerti admin).
 */
if (!class_exists('Zerti_Product_CSV_Importer_Controller', false) && class_exists('WC_Product_CSV_Importer_Controller', false)) {
    class Zerti_Product_CSV_Importer_Controller extends WC_Product_CSV_Importer_Controller
    {
        /**
         * @param string $step
         */
        public function get_next_step_link($step = ''): string
        {
            if (!$step) {
                $step = $this->step;
            }

            $keys = array_keys($this->steps);

            if (end($keys) === $step) {
                return zerti_admin_route_url(['tab' => 'inventory', 'inv' => 'warehouse']);
            }

            $step_index = array_search($step, $keys, true);

            if (false === $step_index) {
                return '';
            }

            $params = [
                'zerti_ie' => 'import',
                'step' => $keys[$step_index + 1],
                'file' => str_replace(DIRECTORY_SEPARATOR, '/', $this->file),
                'delimiter' => $this->delimiter,
                'update_existing' => $this->update_existing ? 1 : 0,
                'map_preferences' => $this->map_preferences ? 1 : 0,
                'character_encoding' => $this->character_encoding,
                '_wpnonce' => wp_create_nonce('woocommerce-csv-importer'),
            ];

            return add_query_arg($params, zerti_product_import_export_url());
        }

        protected function output_header(): void
        {
            echo '<div class="zerti-inv-ie-wizard woocommerce">';
            echo '<h2 class="zerti-inv-ie-wizard__title h5 mb-3">';
            esc_html_e('Import products', 'zerti');
            echo '</h2>';
            echo '<div class="woocommerce-progress-form-wrapper">';
        }

        protected function output_steps(): void
        {
            $labels = [
                'upload' => __('Upload CSV file', 'zerti'),
                'mapping' => __('Column mapping', 'zerti'),
                'import' => __('Import', 'zerti'),
                'done' => __('End', 'zerti'),
            ];
            ?>
            <ol class="wc-progress-steps zerti-inv-ie-steps">
                <?php foreach ($this->steps as $step_key => $step) : ?>
                    <?php
                    $step_class = '';
                    if ($step_key === $this->step) {
                        $step_class = 'active';
                    } elseif (array_search($this->step, array_keys($this->steps), true) > array_search($step_key, array_keys($this->steps), true)) {
                        $step_class = 'done';
                    }
                    $label = $labels[$step_key] ?? (string) ($step['name'] ?? $step_key);
                    ?>
                    <li class="<?php echo esc_attr($step_class); ?>">
                        <span class="zerti-inv-ie-steps__pill"><?php echo esc_html($label); ?></span>
                    </li>
                <?php endforeach; ?>
            </ol>
            <?php
        }

        protected function output_footer(): void
        {
            echo '</div></div>';
        }

        protected function mapping_form(): void
        {
            check_admin_referer('woocommerce-csv-importer');
            self::validate_file_path($this->file);

            $args = [
                'lines' => 1,
                'delimiter' => $this->delimiter,
                'character_encoding' => $this->character_encoding,
            ];

            $importer = self::get_importer($this->file, $args);
            $headers = $importer->get_raw_keys();
            $mapped_items = $this->auto_map_columns($headers);
            $sample = current($importer->get_raw_data());

            if (empty($sample)) {
                $this->add_error(
                    __('File is empty or not UTF-8 compatible; please upload another file.', 'zerti'),
                    [
                        [
                            'url' => zerti_product_import_export_url(['zerti_ie' => 'import', 'step' => 'upload']),
                            'label' => __('Upload new file', 'zerti'),
                        ],
                    ]
                );
                $this->output_errors();

                return;
            }

            include __DIR__ . '/views/inventory-import-export/mapping.php';
        }

        protected function upload_form(): void
        {
            $bytes = apply_filters('import_upload_size_limit', wp_max_upload_size());
            $size = size_format($bytes);
            $upload_dir = wp_upload_dir();

            include __DIR__ . '/views/inventory-import-export/upload.php';
        }

        protected function done(): void
        {
            check_admin_referer('woocommerce-csv-importer');
            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- nonce verified above; import result query args.
            $imported = isset($_GET['products-imported']) ? absint($_GET['products-imported']) : 0;
            $imported_variations = isset($_GET['products-imported-variations']) ? absint($_GET['products-imported-variations']) : 0;
            $updated = isset($_GET['products-updated']) ? absint($_GET['products-updated']) : 0;
            $failed = isset($_GET['products-failed']) ? absint($_GET['products-failed']) : 0;
            $skipped = isset($_GET['products-skipped']) ? absint($_GET['products-skipped']) : 0;
            $file_name = isset($_GET['file-name']) ? sanitize_text_field(wp_unslash($_GET['file-name'])) : '';
            // phpcs:enable WordPress.Security.NonceVerification.Recommended
            $errors = array_filter((array) get_user_option('product_import_error_log'));

            include __DIR__ . '/views/inventory-import-export/done.php';
        }

        public function import(): void
        {
            check_admin_referer('woocommerce-csv-importer');
            self::validate_file_path($this->file);

            // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above.
            if (!empty($_POST['map_from']) && !empty($_POST['map_to'])) {
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via wc_clean().
                $mapping_from = wc_clean(wp_unslash($_POST['map_from']));
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via wc_clean().
                $mapping_to = wc_clean(wp_unslash($_POST['map_to']));
                // phpcs:enable WordPress.Security.NonceVerification.Missing
                update_user_option(get_current_user_id(), 'woocommerce_product_import_mapping', $mapping_to);
            } else {
                // phpcs:enable WordPress.Security.NonceVerification.Missing
                wp_safe_redirect(esc_url_raw($this->get_next_step_link('upload')));
                exit;
            }

            wp_localize_script(
                'zerti-inventory-import-export',
                'zerti_product_import_params',
                [
                    'import_nonce' => wp_create_nonce('wc-product-import'),
                    'mapping' => [
                        'from' => $mapping_from,
                        'to' => $mapping_to,
                    ],
                    'file' => $this->file,
                    'update_existing' => $this->update_existing,
                    'delimiter' => $this->delimiter,
                    'character_encoding' => $this->character_encoding,
                ]
            );

            include __DIR__ . '/views/inventory-import-export/progress.php';
        }
    }
}

/**
 * Register / enqueue WooCommerce + zerti assets for import/export UI.
 */
function zerti_enqueue_product_import_export_assets(): void
{
    if (!zerti_product_import_export_available()) {
        return;
    }

    if (!wp_script_is('wc-product-export', 'registered')) {
        zerti_register_bundled_plugin_assets();
    }

    if (!wp_script_is('wc-product-export', 'registered')) {
        return;
    }

    wp_localize_script(
        'wc-product-export',
        'zerti_product_export_params',
        [
            'export_nonce' => wp_create_nonce('wc-product-export'),
        ]
    );

    if (wp_style_is('zerti-wc-select2', 'registered')) {
        wp_enqueue_style('zerti-wc-select2');
    }

    if (wp_script_is('wc-enhanced-select', 'registered')) {
        wp_enqueue_script('wc-enhanced-select');
    } elseif (wp_script_is('selectWoo', 'registered')) {
        wp_enqueue_script('selectWoo');
    }

    wp_enqueue_script('wc-product-export');
    // wc-product-import is enqueued only on the AJAX import step (see Zerti_Product_CSV_Importer_Controller::import).
    wp_enqueue_script('zerti-inventory-import-export');

    $cfg = zerti_admin_inv_import_export_client_config();
    wp_localize_script('zerti-inventory-import-export', 'zertiInvImportExport', $cfg);
    if (wp_script_is('zerti-admin-components', 'enqueued')) {
        wp_localize_script('zerti-admin-components', 'zertiInvImportExport', $cfg);
    }
}

/**
 * Client config for import/export JS.
 *
 * @return array<string, mixed>
 */
function zerti_admin_inv_import_export_client_config(): array
{
    return [
        'exportDownloadBase' => zerti_product_import_export_url(['zerti_ie' => 'export']),
        'importDoneBase' => add_query_arg(
            [
                'zerti_ie' => 'import',
                'step' => 'done',
                '_wpnonce' => wp_create_nonce('woocommerce-csv-importer'),
            ],
            zerti_product_import_export_url()
        ),
        'warehouseUrl' => zerti_admin_route_url(['tab' => 'inventory', 'inv' => 'warehouse']),
    ];
}

/**
 * CSV import may omit _product_type post meta; persist the resolved WC product type.
 *
 * @param WC_Product $product
 */
function zerti_product_import_ensure_product_type_meta($product): void
{
    if (!$product instanceof WC_Product) {
        return;
    }

    $product_id = (int) $product->get_id();
    if ($product_id < 1) {
        return;
    }

    if (!metadata_exists('post', $product_id, '_product_type')) {
        update_post_meta($product_id, '_product_type', $product->get_type());
    }
}

add_action('woocommerce_product_import_inserted_product_object', 'zerti_product_import_ensure_product_type_meta', 10, 1);

/**
 * Run product CSV import wizard (upload → mapping → import → done).
 */
function zerti_render_product_csv_import_wizard(): void
{
    if (!zerti_bootstrap_wc_product_importer() || !class_exists('Zerti_Product_CSV_Importer_Controller', false)) {
        echo '<p class="alert alert-warning mb-0">';
        esc_html_e('WooCommerce import tool is not available.', 'zerti');
        echo '</p>';

        return;
    }

    if (!zerti_product_import_allowed()) {
        echo '<p class="alert alert-warning mb-0">';
        esc_html_e('You do not have permission to import products.', 'zerti');
        echo '</p>';

        return;
    }

    $importer = new Zerti_Product_CSV_Importer_Controller();
    $importer->dispatch();
}

/**
 * Product CSV export form (WooCommerce fields, zerti layout).
 */
function zerti_render_product_csv_export_form(): void
{
    if (!zerti_product_import_export_available()) {
        echo '<p class="alert alert-warning mb-0">';
        esc_html_e('WooCommerce export tool is not available.', 'zerti');
        echo '</p>';

        return;
    }

    if (!zerti_product_export_allowed()) {
        echo '<p class="alert alert-warning mb-0">';
        esc_html_e('You do not have permission to export products.', 'zerti');
        echo '</p>';

        return;
    }

    include_once WC_ABSPATH . 'includes/export/class-wc-product-csv-exporter.php';

    $exporter = new WC_Product_CSV_Exporter();

    $product_ids_to_export = [];
    $is_exporting_product_ids = false;

    if (!empty($_GET['product_ids'])) {
        check_admin_referer('export-selected-products');
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified above; product IDs sanitized below.
        $ids_raw = explode(',', sanitize_text_field(wp_unslash((string) $_GET['product_ids'])));
        $product_ids_to_export = array_filter(array_map('absint', $ids_raw));
        $is_exporting_product_ids = $product_ids_to_export !== [];
    }

    include __DIR__ . '/views/inventory-import-export/export.php';
}

/**
 * Product-editor style tabs (ورود داده / خروج داده).
 */
function zerti_render_inventory_import_export_tabs(string $mode): void
{
    $import_ok = zerti_product_import_allowed();
    $export_ok = zerti_product_export_allowed();

    if (!$import_ok && !$export_ok) {
        return;
    }

    $import_url = zerti_product_import_export_url(['zerti_ie' => 'import', 'step' => 'upload']);
    $export_url = zerti_product_import_export_url(['zerti_ie' => 'export']);
    $import_active = $mode === 'import';
    $export_active = $mode === 'export';
    ?>
    <nav class="zerti-inv-ie-nav" aria-label="<?php esc_attr_e('Import and export', 'zerti'); ?>">
            <ul class="zerti-wc-tabs zerti-inv-ie-tabs wc-tabs nav flex-lg-column" role="tablist">
                <?php if ($import_ok) : ?>
                    <li class="zerti-wc-tabs__item import_options<?php echo $import_active ? ' active' : ''; ?>" role="presentation">
                        <a
                            href="<?php echo esc_url($import_url); ?>"
                            class="zerti-wc-tabs__link<?php echo $import_active ? ' active' : ''; ?>"
                            role="tab"
                            <?php echo $import_active ? ' aria-current="page"' : ''; ?>
                        >
                            <i class="fa-solid fa-file-import" aria-hidden="true"></i>
                            <?php esc_html_e('Import', 'zerti'); ?>
                        </a>
                    </li>
                <?php endif; ?>
                <?php if ($export_ok) : ?>
                    <li class="zerti-wc-tabs__item export_options<?php echo $export_active ? ' active' : ''; ?>" role="presentation">
                        <a
                            href="<?php echo esc_url($export_url); ?>"
                            class="zerti-wc-tabs__link<?php echo $export_active ? ' active' : ''; ?>"
                            role="tab"
                            <?php echo $export_active ? ' aria-current="page"' : ''; ?>
                        >
                            <i class="fa-solid fa-file-export" aria-hidden="true"></i>
                            <?php esc_html_e('Export', 'zerti'); ?>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
    </nav>
    <?php
}

/**
 * Hub tabs + import wizard or export panel.
 */
function zerti_render_inventory_import_export_content(): void
{
    $mode = zerti_product_import_export_mode();
    $import_ok = zerti_product_import_allowed();
    $export_ok = zerti_product_export_allowed();
    $hub_url = zerti_product_import_export_url();
    $import_url = zerti_product_import_export_url(['zerti_ie' => 'import', 'step' => 'upload']);
    $export_url = zerti_product_import_export_url(['zerti_ie' => 'export']);

    $show_back = $mode !== 'hub' && $import_ok && $export_ok;
    $show_hub_actions = $mode === 'hub' && ($import_ok || $export_ok);
    ?>
    <div class="zerti-inv-ie-layout zerti-wc-product-data">
        <?php if ($show_hub_actions) : ?>
        <div class="zerti-inv-ie-toolbar zerti-inv-ie-toolbar--hub" role="toolbar" aria-label="<?php esc_attr_e('Start import and export', 'zerti'); ?>">
            <?php if ($export_ok) : ?>
            <a class="btn btn-sm btn-outline-secondary d-inline-flex align-items-center gap-1" href="<?php echo esc_url($export_url); ?>">
                <?php esc_html_e('Start CSV export', 'zerti'); ?>
            </a>
            <?php endif; ?>
            <?php if ($import_ok) : ?>
            <a class="btn btn-sm btn-primary d-inline-flex align-items-center gap-1" href="<?php echo esc_url($import_url); ?>">
                <?php esc_html_e('Start CSV import', 'zerti'); ?>
            </a>
            <?php endif; ?>
        </div>
        <?php elseif ($show_back) : ?>
        <div class="zerti-inv-ie-toolbar" role="toolbar" aria-label="<?php esc_attr_e('Import and export navigation', 'zerti'); ?>">
            <a
                href="<?php echo esc_url($hub_url); ?>"
                class="btn btn-outline-secondary btn-sm zerti-inv-ie-back d-inline-flex align-items-center gap-1"
            >
                <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                <?php esc_html_e('Back', 'zerti'); ?>
            </a>
        </div>
        <?php endif; ?>
        <div class="zerti-inv-ie-layout__body d-flex flex-column flex-lg-row">
            <?php zerti_render_inventory_import_export_tabs($mode); ?>
            <div class="zerti-inv-ie-main flex-grow-1 min-w-0">
    <?php if ($mode === 'hub') : ?>
        <div class="card zerti-inv-ie-card w-100 border-0 rounded-0">
            <div class="card-body">
                <p class="text-body-secondary small mb-0">
                    <?php esc_html_e('Import and export products via CSV — same as default WooCommerce, in the ZERTI environment.', 'zerti'); ?>
                </p>
            </div>
        </div>
    <?php elseif ($mode === 'import') : ?>
        <div class="card zerti-inv-ie-card zerti-inv-ie-card--wizard w-100">
            <div class="card-body">
                <?php zerti_render_product_csv_import_wizard(); ?>
            </div>
        </div>
    <?php else : ?>
        <div class="card zerti-inv-ie-card w-100">
            <div class="card-body zerti-inv-ie-export-wrap">
                <?php zerti_render_product_csv_export_form(); ?>
            </div>
        </div>
    <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
}
