<?php

/**
 * The admin-facing functionality of the plugin.
 *
 * @link       https://themeatelier.net
 * @since      1.0.0
 *
 * @package    domain-for-sale
 * @subpackage domain-for-sale/Admin
 * @author     ThemeAtelier <themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Admin;

use ThemeAtelier\DomainForSale\Admin\Helpers\Helpers;
use WP_REST_Server;

/**
 * Handles admin functionality for domain transactions.
 */
class ImportExport
{
    /**
     * Constructor.
     *
     * Hooks into WordPress actions and initializes required methods.
     *
     * @since 3.1.0
     */
    function __construct()
    {
        add_action('admin_head', array($this, 'dfs_localize_script'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'), 100);
        add_action('wp_ajax_dfs_import_domains', array($this, 'dfs_import_domains_callback'));
        add_action('wp_ajax_dfs_get_domains', array($this, 'dfs_get_domains_callback'));
        add_action('wp_ajax_dfs_get_listings', array($this, 'dfs_get_listings_callback'));
        add_action('wp_ajax_dfs_export_domains', array($this, 'dfs_export_domains_callback'));
        add_action('wp_ajax_dfs_export_settings', [$this, 'dfs_export_settings_callback']);
        add_action('wp_ajax_dfs_import_settings', [$this, 'dfs_import_settings_callback']);

        add_action('wp_ajax_dfs_export_listings', [$this, 'dfs_export_listings_callback']);
        add_action('wp_ajax_dfs_import_listings', [$this, 'dfs_import_listings_callback']);

        add_action('wp_ajax_dfs_check_domain_conflicts', [$this, 'dfs_check_domain_conflicts']);
        add_action('wp_ajax_dfs_check_listing_conflicts', [$this, 'dfs_check_listing_conflicts']);
    }

    /**
     * Localizes frontend strings for use in JavaScript.
     *
     * @since 3.1.0
     */
    public function dfs_localize_script()
    {
?>
        <script>
            window.domainForSaleImportExportString = <?php echo json_encode(self::domain_for_sale_string()); ?>;
        </script>
<?php
    }

    /**
     * Enqueues scripts and injects localized variables for the Offers page.
     *
     * @param string $hook Current admin page hook.
     *
     * @since 3.1.0
     */
    public static function enqueue_scripts($hook)
    {
        if ($hook === 'toplevel_page_domain-for-sale') {
            add_action('admin_print_scripts', function () {
                echo wp_print_inline_script_tag(
                    'window.domainForSaleImportExport = ' . wp_json_encode([
                        'dirUrl' => DOMAIN_FOR_SALE_DIR_URL,
                        'pluginVersion' => DOMAIN_FOR_SALE_VERSION,
                        'ajaxUrl' => admin_url('admin-ajax.php'),
                    ]) . ';'
                );
            });

            wp_enqueue_script(
                'domain-for-sale-admin-ui',
                plugin_dir_url(__FILE__) . 'assets/js/domain-for-sale-admin-ui.js',
                array(),
                DOMAIN_FOR_SALE_VERSION,
                true
            );
        }
    }

    private function normalize_csv_headers($headers)
    {
        return array_map(function ($h) {
            $h = strtolower($h);
            $h = trim($h);
            $h = str_replace([' ', '-'], ['_', '-'], $h);
            return $h;
        }, $headers);
    }

    public function dfs_import_domains_callback()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        if (empty($_FILES['file']['tmp_name'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
        }

        $file = $_FILES['file'];
        $type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        $conflict_action = sanitize_text_field($_POST['conflict_action'] ?? 'ignore');

        $imported = 0;
        $failed   = 0;

        /**
         * =====================
         * JSON IMPORT
         * =====================
         */
        if ($type === 'json') {

            $rows = json_decode(file_get_contents($file['tmp_name']), true);

            if (!is_array($rows)) {
                wp_send_json_error(['message' => 'Invalid JSON file']);
            }

            foreach ($rows as $data) {

                $slug = sanitize_title($data['domain_slug'] ?? '');
                if (!$slug) {
                    $failed++;
                    continue;
                }

                $existing = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {
                    if ($conflict_action === 'ignore') continue;

                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug($slug, 0, 'publish', 'dfs_template', 0);
                    }
                }

                $post_id = wp_insert_post([
                    'post_type'   => 'dfs_template',
                    'post_title'  => sanitize_text_field($data['domain_title'] ?? ''),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id)) {
                    $failed++;
                    continue;
                }

                $layout_preset = sanitize_title($data['layout_preset'] ?? 'layout_01');
                $dfs_layouts = get_post_meta($post_id, 'dfs_layouts', true);
                if (!is_array($dfs_layouts)) {
                    $dfs_layouts = [];
                }
                $dfs_layouts['dfs_layout_preset'] = $layout_preset;

                update_post_meta($post_id, 'dfs_layouts', $dfs_layouts);
                update_post_meta($post_id, 'dfs_template_options', $data['meta'] ?? []);

                $imported++;
            }
        }

        /**
         * =====================
         * XML IMPORT ✅ FIXED
         * =====================
         */
        if ($type === 'xml') {

            libxml_use_internal_errors(true);
            $xml = simplexml_load_file($file['tmp_name']);

            if (!$xml) {
                wp_send_json_error(['message' => 'Invalid XML file']);
            }

            foreach ($xml->domain as $item) {

                $slug = sanitize_title((string) $item->slug);
                if (!$slug) {
                    $failed++;
                    continue;
                }

                $existing = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {

                    if ($conflict_action === 'ignore') continue;

                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug($slug, 0, 'publish', 'dfs_template', 0);
                    }
                }

                $post_id = wp_insert_post([
                    'post_type'   => 'dfs_template',
                    'post_title'  => sanitize_text_field((string) $item->title),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id)) {
                    $failed++;
                    continue;
                }

                $default_meta = Helpers::dfs_default_domain_meta();
                $mapped_meta  = [];

                if (isset($item->meta)) {
                    foreach ($item->meta->children() as $key => $value) {
                        $val = (string) $value;
                        $decoded = json_decode($val, true);
                        $mapped_meta[$key] = (json_last_error() === JSON_ERROR_NONE)
                            ? $decoded
                            : sanitize_text_field($val);
                    }
                }

                // Merge default + imported
                $final_meta = array_replace_recursive($default_meta, $mapped_meta);

                $layout_preset = sanitize_title($data['layout_preset'] ?? 'layout_01');
                $dfs_layouts = get_post_meta($post_id, 'dfs_layouts', true);
                if (!is_array($dfs_layouts)) {
                    $dfs_layouts = [];
                }
                $dfs_layouts['dfs_layout_preset'] = $layout_preset;

                update_post_meta($post_id, 'dfs_layouts', $dfs_layouts);
                update_post_meta($post_id, 'dfs_template_options', $final_meta);

                $imported++;
            }
        }

        /**
         * =====================
         * CSV IMPORT (UNCHANGED)
         * =====================
         */
        if ($type === 'csv') {

            $handle = fopen($file['tmp_name'], 'r');

            if (!$handle) {
                wp_send_json_error(['message' => 'Cannot read file']);
            }

            $header = $this->normalize_csv_headers(fgetcsv($handle));

            while (($row = fgetcsv($handle)) !== false) {

                if (count($row) !== count($header)) {
                    $failed++;
                    continue;
                }

                $data = array_combine($header, $row);

                $slug = sanitize_title($data['domain_slug'] ?? '');
                if (!$slug) {
                    $failed++;
                    continue;
                }

                $existing = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {

                    if ($conflict_action === 'ignore') continue;

                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug($slug, 0, 'publish', 'dfs_template', 0);
                    }
                }

                $post_id = wp_insert_post([
                    'post_type'   => 'dfs_template',
                    'post_title'  => sanitize_text_field($data['domain_title'] ?? ''),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id)) {
                    $failed++;
                    continue;
                }

                $default_meta = Helpers::dfs_default_domain_meta();
                $mapped_meta  = [];

                // Map only known fields (optional but cleaner)
                if (!empty($data['domain_name'])) {
                    $mapped_meta['domain_name'] = sanitize_text_field($data['domain_name']);
                }

                if (isset($data['sell_price'])) {
                    $mapped_meta['sell_price'] = (float) $data['sell_price'];
                }
                if (!empty($data['domain_logo'])) {
                    $attachment_id = $this->upload_image_from_url($data['domain_logo'], $post_id);
                    if ($attachment_id) {
                        $image_url = wp_get_attachment_url($attachment_id);
                        $meta_data = wp_get_attachment_metadata($attachment_id);
                        $mapped_meta['domain_logo'] = [
                            'id'        => $attachment_id,
                            'url'       => $image_url,
                            'width'     => $meta_data['width'] ?? '',
                            'height'    => $meta_data['height'] ?? '',
                            'thumbnail' => wp_get_attachment_image_url($attachment_id, 'thumbnail'),
                            'alt'       => get_post_meta($attachment_id, '_wp_attachment_image_alt', true),
                            'title'     => get_the_title($attachment_id),
                        ];
                    } else {
                        $mapped_meta['domain_logo'] = [
                            'url' => esc_url_raw($data['domain_logo'])
                        ];
                    }
                }

                // Merge with default
                $final_meta = array_replace_recursive($default_meta, $mapped_meta);

                $layout_preset = sanitize_title($data['layout_preset'] ?? 'layout_01');
                $dfs_layouts = get_post_meta($post_id, 'dfs_layouts', true);
                if (!is_array($dfs_layouts)) {
                    $dfs_layouts = [];
                }
                $dfs_layouts['dfs_layout_preset'] = $layout_preset;

                update_post_meta($post_id, 'dfs_layouts', $dfs_layouts);
                update_post_meta($post_id, 'dfs_template_options', $final_meta);

                $imported++;
            }

            fclose($handle);
        }

        wp_send_json_success([
            'message'  => 'Domains imported successfully',
            'imported' => $imported,
            'failed'   => $failed,
        ]);
    }

    private function upload_image_from_url($image_url, $post_id = 0)
    {
        if (empty($image_url)) return false;

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        // Download file to temp
        $tmp = download_url($image_url);

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

        // Prepare file array
        $file = [
            'name'     => basename($image_url),
            'type'     => mime_content_type($tmp),
            'tmp_name' => $tmp,
            'size'     => filesize($tmp),
        ];

        // Upload to media
        $attachment_id = media_handle_sideload($file, $post_id);

        if (is_wp_error($attachment_id)) {
            @unlink($tmp);
            return false;
        }

        return $attachment_id;
    }

    public function dfs_get_domains_callback()
    {
        $posts = get_posts([
            'post_type'      => 'dfs_template',
            'posts_per_page' => -1,
            'post_status'    => 'publish'
        ]);

        $data = array_map(function ($post) {
            return [
                'id'    => $post->ID,
                'label' => $post->post_title
            ];
        }, $posts);

        wp_send_json_success($data);
    }

    public function dfs_export_domains_callback()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        $type = $_POST['file_type'] ?? 'csv';

        $posts = get_posts([
            'post_type'      => 'dfs_template',
            'posts_per_page' => -1,
            'post_status'    => 'publish'
        ]);

        if ($type === 'json') {
            $data = [];
            foreach ($posts as $post) {
                $meta = get_post_meta($post->ID, 'dfs_template_options', true);
                $layout = get_post_meta($post->ID, 'dfs_layouts', true);
                $data[] = [
                    'domain_title' => $post->post_title,
                    'domain_slug'  => $post->post_name,
                    'layout_preset' => $layout['dfs_layout_preset'] ?? 'layout_01',
                    'meta'         => $meta ?: [],
                ];
            }

            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="domains.json"');

            echo json_encode($data);
            exit;
        }

        if ($type === 'xml') {

            header('Content-Type: text/xml');
            header('Content-Disposition: attachment; filename="domains.xml"');

            echo "<domains>";

            foreach ($posts as $post) {

                $meta = get_post_meta($post->ID, 'dfs_template_options', true);
                $layout = get_post_meta($post->ID, 'dfs_layouts', true);
                echo "<domain>";

                echo "<title><![CDATA[{$post->post_title}]]></title>";
                echo "<slug>{$post->post_name}</slug>";
                echo "<layout_preset><![CDATA[" . ($layout['dfs_layout_preset'] ?? 'layout_01') . "]]></layout_preset>";

                echo "<meta>";

                if (is_array($meta)) {
                    foreach ($meta as $key => $val) {

                        if (is_array($val)) {
                            $val = json_encode($val);
                        }

                        echo "<{$key}><![CDATA[{$val}]]></{$key}>";
                    }
                }

                echo "</meta>";
                echo "</domain>";
            }

            echo "</domains>";
            exit;
        }

        if (ob_get_length()) ob_clean();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=domains.csv');

        $output = fopen('php://output', 'w');
        $all_keys = [];
        foreach ($posts as $post) {
            $meta = get_post_meta($post->ID, 'dfs_template_options', true);
            if (is_array($meta)) {
                foreach ($meta as $key => $val) {
                    $all_keys[$key] = $key;
                }
            }
        }

        // Header
        $headers = [
            'Domain Title',
            'Domain Slug',
            'Layout Preset',
        ];

        foreach ($all_keys as $key) {
            $headers[] = ucwords(str_replace(['_', '-'], ' ', $key));
        }
        fputcsv($output, $headers);

        foreach ($posts as $post) {
            $meta = get_post_meta($post->ID, 'dfs_template_options', true);
            $layout = get_post_meta($post->ID, 'dfs_layouts', true);
            $row = [
                $post->post_title,
                $post->post_name,
                $layout['dfs_layout_preset'] ?? 'layout_01',
            ];

            foreach ($all_keys as $key) {
                $value = $meta[$key] ?? '';
                $row[] = is_array($value) ? json_encode($value) : $value;
            }

            fputcsv($output, $row);
        }

        fclose($output);
        wp_die();
    }

    public function dfs_get_listings_callback()
    {
        $posts = get_posts([
            'post_type'      => 'domain_listing',
            'posts_per_page' => -1,
            'post_status'    => 'publish'
        ]);
        $data = array_map(function ($post) {
            return [
                'id'    => $post->ID,
                'label' => $post->post_title
            ];
        }, $posts);

        wp_send_json_success($data);
    }

    public function dfs_export_listings_callback()
    {
        $type = $_POST['file_type'] ?? 'csv';
        $posts = get_posts([
            'post_type' => 'domain_listing',
            'posts_per_page' => -1
        ]);

        if ($type === 'csv') {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="listings.csv"');

            $out = fopen('php://output', 'w');

            // Collect dynamic keys only from listing_template_options
            $all_keys = [];
            foreach ($posts as $post) {
                $meta = get_post_meta($post->ID, 'listing_template_options', true);
                if (is_array($meta)) {
                    foreach ($meta as $key => $val) {
                        $all_keys[$key] = $key;
                    }
                }
            }

            $headers = ['Title', 'Slug', 'Layout'];

            foreach ($all_keys as $key) {
                $headers[] = ucwords(str_replace(['_', '-'], ' ', $key));
            }
            fputcsv($out, $headers);

            foreach ($posts as $post) {
                $meta_layout = get_post_meta($post->ID, 'listing_layouts', true);
                $meta = get_post_meta($post->ID, 'listing_template_options', true);

                $row = [
                    $post->post_title,
                    $post->post_name,
                    $meta_layout['listing_layout_preset'] ?? 'grid_layout',
                ];

                foreach ($all_keys as $key) {
                    $value = $meta[$key] ?? '';
                    $row[] = is_array($value) ? json_encode($value) : $value;
                }

                fputcsv($out, $row);
            }

            fclose($out);
            exit;
        }

        // XML Export
        if ($type === 'xml') {
            header('Content-Type: text/xml; charset=utf-8');
            header('Content-Disposition: attachment; filename="listings.xml"');

            echo '<?xml version="1.0" encoding="UTF-8"?>';
            echo '<listings>';

            foreach ($posts as $post) {

                $meta_layout = get_post_meta($post->ID, 'listing_layouts', true);
                $meta = get_post_meta($post->ID, 'listing_template_options', true);

                echo '<listing>';

                echo '<title><![CDATA[' . $post->post_title . ']]></title>';
                echo '<slug><![CDATA[' . $post->post_name . ']]></slug>';
                echo '<layout><![CDATA[' . ($meta_layout['listing_layout_preset'] ?? 'grid_layout') . ']]></layout>';

                echo '<meta>';

                if (is_array($meta)) {
                    foreach ($meta as $key => $val) {

                        if (is_array($val)) {
                            $val = json_encode($val);
                        }

                        echo '<' . esc_html($key) . '><![CDATA[' . $val . ']]></' . esc_html($key) . '>';
                    }
                }

                echo '</meta>';
                echo '</listing>';
            }

            echo '</listings>';
            exit;
        }

        if ($type === 'json') {
            $data = [];
            foreach ($posts as $post) {
                $meta_layout = get_post_meta($post->ID, 'listing_layouts', true);
                $meta = get_post_meta($post->ID, 'listing_template_options', true);

                $data[] = [
                    'title'  => $post->post_title,
                    'slug'   => $post->post_name,
                    'layout' => $meta_layout['listing_layout_preset'] ?? 'grid_layout',
                    'meta'   => $meta ?: [],
                ];
            }

            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="listings.json"');

            echo json_encode($data);
            exit;
        }
    }

    public function dfs_import_listings_callback()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        if (empty($_FILES['file']['tmp_name'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
        }

        $file = $_FILES['file'];
        $type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if (!in_array($type, ['csv', 'xml'])) {
            wp_send_json_error(['message' => 'Invalid file type']);
        }

        $conflict_action = sanitize_text_field($_POST['conflict_action'] ?? 'replace');

        $imported = 0;
        $failed   = 0;

        /**
         * =========================
         * CSV IMPORT (FIXED)
         * =========================
         */
        if ($type === 'csv') {
            $handle = fopen($file['tmp_name'], 'r');
            if (!$handle) {
                wp_send_json_error(['message' => 'Cannot read file']);
            }

            $header = fgetcsv($handle);

            if (empty($header)) {
                fclose($handle);
                wp_send_json_error(['message' => 'Invalid CSV header']);
            }

            $header = $this->normalize_csv_headers($header);

            /**
             * 🔥 Normalize header (Human → System keys)
             */
            $normalized_header = array_map(function ($h) {
                $h = strtolower($h);
                $h = str_replace([' ', '-'], ['_', '-'], $h);
                return $h;
            }, $header);

            while (($row = fgetcsv($handle)) !== false) {

                if (count($row) !== count($normalized_header)) {
                    $failed++;
                    continue;
                }

                $data = array_combine($normalized_header, $row);

                if (!$data) {
                    $failed++;
                    continue;
                }

                $slug = sanitize_title($data['slug'] ?? '');

                if (!$slug) {
                    $failed++;
                    continue;
                }

                // 🔥 Conflict Handling
                $existing = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {

                    if ($conflict_action === 'ignore') {
                        continue;
                    }

                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug(
                            $slug,
                            0,
                            'publish',
                            'domain_listing',
                            0
                        );
                    }
                }

                $post_id = wp_insert_post([
                    'post_type'   => 'domain_listing',
                    'post_title'  => sanitize_text_field($data['title'] ?? ''),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id) || !$post_id) {
                    $failed++;
                    continue;
                }

                // Layout
                $layout = [
                    'listing_layout_preset' => sanitize_text_field($data['layout'] ?? 'grid_layout'),
                ];

                $meta = [];

                foreach ($data as $key => $value) {

                    if (in_array($key, ['title', 'slug', 'layout'])) {
                        continue;
                    }

                    $decoded = json_decode($value, true);

                    $meta[$key] = (json_last_error() === JSON_ERROR_NONE)
                        ? $decoded
                        : sanitize_text_field($value);
                }

                update_post_meta($post_id, 'listing_layouts', $layout);
                update_post_meta($post_id, 'listing_template_options', $meta);

                $imported++;
            }

            fclose($handle);
        }

        /**
         * =========================
         * XML IMPORT (unchanged)
         * =========================
         */
        if ($type === 'xml') {

            libxml_use_internal_errors(true);
            $xml = simplexml_load_file($file['tmp_name'], 'SimpleXMLElement', LIBXML_NOCDATA);

            if (!$xml) {
                wp_send_json_error(['message' => 'Invalid XML file']);
            }

            foreach ($xml->listing as $item) {

                $slug = sanitize_title((string) $item->slug);

                if (!$slug) {
                    $failed++;
                    continue;
                }

                // 🔥 Conflict Handling
                $existing = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {

                    if ($conflict_action === 'ignore') continue;

                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug(
                            $slug,
                            0,
                            'publish',
                            'domain_listing',
                            0
                        );
                    }
                }

                $post_id = wp_insert_post([
                    'post_type'   => 'domain_listing',
                    'post_title'  => sanitize_text_field((string) $item->title),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id) || !$post_id) {
                    $failed++;
                    continue;
                }

                // ✅ Layout FIXED
                $layout = [
                    'listing_layout_preset' => sanitize_text_field((string) ($item->layout ?? 'grid_layout')),
                ];

                $meta = [];

                if (isset($item->meta)) {
                    foreach ($item->meta->children() as $key => $value) {

                        $val = (string) $value;

                        $decoded = json_decode($val, true);

                        $meta[$key] = (json_last_error() === JSON_ERROR_NONE)
                            ? $decoded
                            : sanitize_text_field($val);
                    }
                }

                update_post_meta($post_id, 'listing_layouts', $layout);
                update_post_meta($post_id, 'listing_template_options', $meta);

                $imported++;
            }
        }

        if ($type === 'json') {

            $content = file_get_contents($file['tmp_name']);
            $rows = json_decode($content, true);

            if (!is_array($rows)) {
                wp_send_json_error(['message' => 'Invalid JSON file']);
            }

            $conflict_action = sanitize_text_field($_POST['conflict_action'] ?? 'replace');

            $imported = 0;
            $failed   = 0;

            foreach ($rows as $data) {
                $slug = sanitize_title($data['slug'] ?? '');
                if (!$slug) {
                    $failed++;
                    continue;
                }

                // 🔥 conflict handling
                $existing = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($existing)) {

                    if ($conflict_action === 'ignore') continue;
                    if ($conflict_action === 'replace') {
                        wp_delete_post($existing[0]->ID, true);
                    }

                    if ($conflict_action === 'keepboth') {
                        $slug = wp_unique_post_slug($slug, 0, 'publish', 'domain_listing', 0);
                    }
                }
                $post_id = wp_insert_post([
                    'post_type'   => 'domain_listing',
                    'post_title'  => sanitize_text_field($data['title'] ?? ''),
                    'post_name'   => $slug,
                    'post_status' => 'publish',
                ], true);

                if (is_wp_error($post_id) || !$post_id) {
                    $failed++;
                    continue;
                }

                update_post_meta($post_id, 'listing_layouts', [
                    'listing_layout_preset' => sanitize_text_field($data['layout'] ?? 'grid_layout'),
                ]);
                update_post_meta(
                    $post_id,
                    'listing_template_options',
                    $data['meta'] ?? []
                );
                $imported++;
            }

            wp_send_json_success([
                'message'  => 'JSON import completed',
                'imported' => $imported,
                'failed'   => $failed,
            ]);
        }

        wp_send_json_success([
            'message'  => 'Listings imported successfully',
            'imported' => $imported,
            'failed'   => $failed,
        ]);
    }

    public function dfs_export_settings_callback()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }
        $option_name = 'dfs-opt';
        $settings = get_option($option_name);

        if (empty($settings)) {
            wp_send_json_error(['message' => 'No settings found']);
        }
        if (ob_get_length()) ob_clean();

        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename=dfs-settings.json');
        echo json_encode($settings);

        wp_die();
    }

    public function dfs_import_settings_callback()
    {
        if (!isset($_FILES['file'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
        }

        $file = $_FILES['file'];
        $content = file_get_contents($file['tmp_name']);
        $settings = json_decode($content, true);

        if (!$settings) {
            wp_send_json_error(['message' => 'Invalid JSON']);
        }

        update_option('dfs-opt', $settings);

        wp_send_json_success(['message' => 'Settings imported']);
    }

    public function dfs_check_domain_conflicts()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        if (empty($_FILES['file']['tmp_name'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
        }

        $file = $_FILES['file'];
        $type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        $conflicts = [];

        /**
         * =========================
         * NORMALIZE SLUG FUNCTION
         * =========================
         */
        $get_slug = function ($value) {
            return sanitize_title($value ?? '');
        };

        /**
         * =========================
         * JSON CHECK
         * =========================
         */
        if ($type === 'json') {

            $rows = json_decode(file_get_contents($file['tmp_name']), true);

            if (!is_array($rows)) {
                wp_send_json_error(['message' => 'Invalid JSON file']);
            }

            foreach ($rows as $data) {

                $slug = $get_slug($data['domain_slug'] ?? null);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * CSV CHECK
         * =========================
         */
        if ($type === 'csv') {

            $handle = fopen($file['tmp_name'], 'r');

            if (!$handle) {
                wp_send_json_error(['message' => 'File error']);
            }

            $header = fgetcsv($handle);

            if (empty($header)) {
                fclose($handle);
                wp_send_json_error(['message' => 'Invalid CSV header']);
            }

            $header = array_map(function ($h) {
                return str_replace([' ', '-'], ['_', '-'], strtolower(trim($h)));
            }, $header);

            while (($row = fgetcsv($handle)) !== false) {

                if (count($row) !== count($header)) continue;

                $data = array_combine($header, $row);
                if (!$data) continue;

                $slug = $get_slug($data['domain_slug'] ?? null);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            fclose($handle);

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * XML CHECK (FIXED + ADDED)
         * =========================
         */
        if ($type === 'xml') {

            libxml_use_internal_errors(true);
            $xml = simplexml_load_file($file['tmp_name']);

            if (!$xml) {
                wp_send_json_error(['message' => 'Invalid XML file']);
            }

            foreach ($xml->domain as $item) {

                $slug = $get_slug((string) $item->slug);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'dfs_template',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * UNSUPPORTED
         * =========================
         */
        wp_send_json_error(['message' => 'Unsupported file type']);
    }
    public function dfs_check_listing_conflicts()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        if (empty($_FILES['file']['tmp_name'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
        }

        $file = $_FILES['file'];
        $type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        $conflicts = [];

        /**
         * =========================
         * NORMALIZE SLUG HELPER
         * =========================
         */
        $get_slug = function ($value) {
            return sanitize_title($value ?? '');
        };

        /**
         * =========================
         * JSON CHECK
         * =========================
         */
        if ($type === 'json') {

            $rows = json_decode(file_get_contents($file['tmp_name']), true);

            if (!is_array($rows)) {
                wp_send_json_error(['message' => 'Invalid JSON file']);
            }

            foreach ($rows as $data) {

                $slug = $get_slug($data['slug'] ?? null);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * CSV CHECK
         * =========================
         */
        if ($type === 'csv') {

            $handle = fopen($file['tmp_name'], 'r');

            if (!$handle) {
                wp_send_json_error(['message' => 'File error']);
            }

            $header = fgetcsv($handle);

            if (empty($header)) {
                fclose($handle);
                wp_send_json_error(['message' => 'Invalid CSV header']);
            }

            $header = array_map(function ($h) {
                return str_replace([' ', '-'], ['_', '-'], strtolower(trim($h)));
            }, $header);

            while (($row = fgetcsv($handle)) !== false) {

                if (count($row) !== count($header)) continue;

                $data = array_combine($header, $row);
                if (!$data) continue;

                $slug = $get_slug($data['slug'] ?? null);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            fclose($handle);

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * XML CHECK (FIXED)
         * =========================
         */
        if ($type === 'xml') {

            libxml_use_internal_errors(true);
            $xml = simplexml_load_file($file['tmp_name']);

            if (!$xml) {
                wp_send_json_error(['message' => 'Invalid XML file']);
            }

            foreach ($xml->listing as $item) {

                $slug = $get_slug((string) $item->slug);
                if (!$slug) continue;

                $exists = get_posts([
                    'post_type'   => 'domain_listing',
                    'name'        => $slug,
                    'post_status' => 'any',
                    'numberposts' => 1
                ]);

                if (!empty($exists)) {
                    $conflicts[] = $slug;
                }
            }

            wp_send_json_success([
                'conflicts' => array_values(array_unique($conflicts))
            ]);
        }

        /**
         * =========================
         * UNSUPPORTED FILE TYPE
         * =========================
         */
        wp_send_json_error(['message' => 'Unsupported file type']);
    }

    /**
     * Returns localized strings for the offers admin UI.
     *
     * @return array
     *
     * @since 3.1.0
     */
    public static function domain_for_sale_string()
    {
        return [
            'import_export' => esc_html__('Tools', 'domain-for-sale'),
            'import' => esc_html__('Import', 'domain-for-sale'),
            'export' => esc_html__('Export', 'domain-for-sale'),
            'import_domain' => esc_html__('Import Domain', 'domain-for-sale'),
            'import_listing' => esc_html__('Import Listing', 'domain-for-sale'),
            'import_settings' => esc_html__('Import Settings', 'domain-for-sale'),
            'export_domain' => esc_html__('Export Domain', 'domain-for-sale'),
            'export_listing' => esc_html__('Export Listing', 'domain-for-sale'),
            'export_settings' => esc_html__('Export Settings', 'domain-for-sale'),
            'drag_drop' => __('Drag & drop a file here, or click to select', 'domain-for-sale'),
            'supports_csv_xml' => esc_html__('Supports CSV, XML, and JSON', 'domain-for-sale'),
            'import_your_domains' => esc_html__('To import your Domains, please upload the .xml, .csv and .json file here.', 'domain-for-sale'),
            'download_sample_csv' => esc_html__('Download sample csv file', 'domain-for-sale'),
            'import_your_listings' => esc_html__('To import your Domain Listing, please upload the .xml, .csv and .json file here.', 'domain-for-sale'),
            'drag_drop_settings' => __('Drag & drop settings file or click to select', 'domain-for-sale'),
            'only_json_file_supported' => esc_html__('Only .json file supported', 'domain-for-sale'),
            'upload_settings' => esc_html__('Upload previously exported settings file (.json)', 'domain-for-sale'),
            'select_domain' => esc_html__('Select Domain', 'domain-for-sale'),
            'all' => esc_html__('All', 'domain-for-sale'),
            'selected_domain_included' => esc_html__('Selected domain will be included in the export.', 'domain-for-sale'),
            'all_domain_included' => esc_html__('All domain will be included in the export.', 'domain-for-sale'),
            'selected_listing_included' => esc_html__('Selected listing will be included in the export.', 'domain-for-sale'),
            'all_listing_included' => esc_html__('All listing will be included in the export.', 'domain-for-sale'),
            'select_file_type' => esc_html__('Select File Type', 'domain-for-sale'),
            'settings_export_info' => esc_html__('Simply click on “Export Settings” button to download your Domain For Sale settings in .json format', 'domain-for-sale'),
            'imported_successfully' => esc_html__('Imported successfully ✅', 'domain-for-sale'),
            'import_failed' => esc_html__('Import failed ❌', 'domain-for-sale'),
            'uploading' => esc_html__('Uploading...', 'domain-for-sale'),
            'drop_the_file_here' => esc_html__('Drop the file here...', 'domain-for-sale'),
            'some_domains_exist_notice' => esc_html__('Some domains with same slug already exist. What would you like to do?', 'domain-for-sale'),
            'some_listings_exist_notice' => esc_html__('Some listings with same slug already exist. What would you like to do?', 'domain-for-sale'),
            'ignore' => esc_html__('Ignore', 'domain-for-sale'),
            'keep_both' => esc_html__('Keep Both', 'domain-for-sale'),
            'replace' => esc_html__('Replace', 'domain-for-sale'),
            'importing' => esc_html__('Importing...', 'domain-for-sale'),
            'import_listings_info' => esc_html__('To import your Listing, please upload the .xml, .csv and .json file here.', 'domain-for-sale'),
            'drop_json_file_here' => esc_html__('Drop JSON file here...', 'domain-for-sale'),
            'select_listing' => esc_html__('Select Listing', 'domain-for-sale'),
            'no_domain_found' => esc_html__('No Domain Found', 'domain-for-sale'),
            'no_listing_found' => esc_html__('No Listing Found', 'domain-for-sale'),
            'import_export_settings' => esc_html__('Import and Export Domains, Listings, and Settings.', 'domain-for-sale'),
            'see_docs' => esc_html__('See Docs', 'domain-for-sale'),
        ];
    }
}
