<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function aitd_normalize_url( $url ) {
    $url = trim( (string) $url );

    if ( '' === $url ) {
        return '';
    }

    if ( ! preg_match( '#^https?://#i', $url ) ) {
        $url = 'https://' . ltrim( $url, '/' );
    }

    return esc_url_raw( $url );
}

function aitd_get_tool_meta( $post_id, $key, $default = '' ) {
    $value = get_post_meta( $post_id, $key, true );
    return '' === $value ? $default : $value;
}

function aitd_has_completed_import() {
    return (bool) get_option( 'aitd_import_completed', false );
}

function aitd_mark_import_completed() {
    update_option( 'aitd_import_completed', 1 );
}

function aitd_get_curated_import_tools() {
    return [
        [
            'title'             => 'ChatGPT',
            'short_description' => 'AI assistant for writing, research, brainstorming, coding help, and everyday productivity.',
            'description'       => '<p>ChatGPT helps individuals and teams write faster, organize ideas, summarize documents, research topics, and automate repetitive text-heavy tasks. It is useful for drafting content, polishing messaging, building workflows, and accelerating problem solving across many industries.</p><p>Popular use cases include article drafting, email writing, study support, meeting recap creation, customer response drafting, and lightweight coding assistance.</p>',
            'website_url'       => 'https://chatgpt.com/',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 1,
            'categories'        => [ 'Writing & Content', 'Productivity & Automation' ],
            'tags'              => [ 'assistant', 'chatbot', 'research', 'writing' ],
        ],
        [
            'title'             => 'Claude',
            'short_description' => 'AI assistant focused on long-form analysis, writing, document work, and thoughtful reasoning.',
            'description'       => '<p>Claude is especially strong for reading long documents, extracting key ideas, drafting clear writing, and helping with planning or analysis-heavy work. It fits research, strategy, document review, and knowledge-heavy workflows.</p><p>Teams often use it for summarizing policies, generating outlines, preparing reports, and turning rough notes into polished communication.</p>',
            'website_url'       => 'https://claude.ai/',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 1,
            'categories'        => [ 'Writing & Content', 'Research & Data' ],
            'tags'              => [ 'analysis', 'documents', 'writing', 'assistant' ],
        ],
        [
            'title'             => 'Perplexity',
            'short_description' => 'Answer engine for web research, source-backed summaries, and fast topic exploration.',
            'description'       => '<p>Perplexity is built for finding answers quickly while surfacing sources, making it helpful for research, competitor checks, fact gathering, and market exploration. It reduces the time needed to move from search results to a concise overview.</p><p>Useful for researchers, founders, marketers, students, and operators who need quick source-based direction.</p>',
            'website_url'       => 'https://www.perplexity.ai/',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 0,
            'categories'        => [ 'Research & Data', 'Productivity & Automation' ],
            'tags'              => [ 'research', 'search', 'sources', 'summaries' ],
        ],
        [
            'title'             => 'Midjourney',
            'short_description' => 'AI image generator for concept art, campaigns, visual ideation, and creative exploration.',
            'description'       => '<p>Midjourney helps creators generate polished visuals from prompts for concept development, moodboards, advertising ideas, and artistic experimentation. It is especially popular with designers, marketers, and creative teams.</p><p>It works well when speed of ideation matters and teams want a wide range of visual directions before production.</p>',
            'website_url'       => 'https://www.midjourney.com/',
            'logo_url'          => '',
            'pricing'           => 'Paid',
            'featured'          => 0,
            'categories'        => [ 'Image & Design' ],
            'tags'              => [ 'image generation', 'design', 'art', 'creative' ],
        ],
        [
            'title'             => 'Canva',
            'short_description' => 'Design platform with AI tools for graphics, presentations, social posts, and quick brand assets.',
            'description'       => '<p>Canva combines templates, brand controls, and AI-assisted editing to help teams create marketing assets, presentations, videos, and social content quickly. It is useful for non-designers who still need polished results.</p><p>Common use cases include pitch decks, social media graphics, printable assets, and fast campaign creative.</p>',
            'website_url'       => 'https://www.canva.com/',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 0,
            'categories'        => [ 'Image & Design', 'Marketing & SEO' ],
            'tags'              => [ 'design', 'presentations', 'social media', 'branding' ],
        ],
        [
            'title'             => 'GitHub Copilot',
            'short_description' => 'AI coding assistant for code suggestions, boilerplate reduction, and developer productivity.',
            'description'       => '<p>GitHub Copilot helps developers write code faster by suggesting functions, tests, and repetitive patterns inside the editor. It is useful for speeding up implementation, learning APIs, and reducing time spent on boilerplate.</p><p>Engineering teams use it for application development, test scaffolding, refactoring support, and documentation help.</p>',
            'website_url'       => 'https://github.com/features/copilot',
            'logo_url'          => '',
            'pricing'           => 'Paid',
            'featured'          => 1,
            'categories'        => [ 'Coding & Development', 'Productivity & Automation' ],
            'tags'              => [ 'coding', 'developer tools', 'pair programming', 'automation' ],
        ],
        [
            'title'             => 'Notion AI',
            'short_description' => 'Workspace AI for note cleanup, summaries, drafting, and turning knowledge into action.',
            'description'       => '<p>Notion AI extends notes, docs, and internal knowledge with summarization, drafting, and question-answering features. It works well for operations, documentation, planning, and turning messy information into organized next steps.</p><p>Useful for teams centralizing project plans, SOPs, research notes, and meeting documentation.</p>',
            'website_url'       => 'https://www.notion.so/product/ai',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 0,
            'categories'        => [ 'Productivity & Automation' ],
            'tags'              => [ 'notes', 'knowledge base', 'summaries', 'workspace' ],
        ],
        [
            'title'             => 'Grammarly',
            'short_description' => 'Writing assistant for grammar, clarity, tone, and professional communication.',
            'description'       => '<p>Grammarly helps improve spelling, grammar, sentence clarity, and tone across emails, documents, and web writing. It is valuable for business communication, editing, and producing cleaner copy with less manual review.</p><p>It is commonly used by professionals, support teams, marketers, and students who want more polished writing.</p>',
            'website_url'       => 'https://www.grammarly.com/',
            'logo_url'          => '',
            'pricing'           => 'Freemium',
            'featured'          => 0,
            'categories'        => [ 'Writing & Content' ],
            'tags'              => [ 'editing', 'grammar', 'tone', 'writing' ],
        ],
    ];
}

function aitd_get_curated_tool_names() {
    return array_map(
        static function( $tool ) {
            return $tool['title'];
        },
        aitd_get_curated_import_tools()
    );
}

function aitd_insert_imported_tool( $data ) {
    $title = sanitize_text_field( $data['title'] ?? '' );
    $website_url = aitd_normalize_url( $data['website_url'] ?? '' );

    if ( '' === $title ) {
        return 0;
    }

    $existing_tools = get_posts(
        [
            'post_type'      => AITD_POST_TYPE,
            'post_status'    => 'any',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'name'           => sanitize_title( $title ),
        ]
    );

    if ( ! empty( $existing_tools ) ) {
        return 0;
    }

    if ( $website_url ) {
        $existing_by_url = get_posts(
            [
                'post_type'      => AITD_POST_TYPE,
                'post_status'    => 'any',
                'posts_per_page' => 1,
                'fields'         => 'ids',
                'meta_query'     => [
                    [
                        'key'   => '_aitd_website_url',
                        'value' => $website_url,
                    ],
                ],
            ]
        );

        if ( ! empty( $existing_by_url ) ) {
            return 0;
        }
    }

    $post_id = wp_insert_post(
        [
            'post_type'    => AITD_POST_TYPE,
            'post_status'  => 'publish',
            'post_title'   => $title,
            'post_excerpt' => sanitize_textarea_field( $data['short_description'] ?? '' ),
            'post_content' => wp_kses_post( $data['description'] ?? '' ),
        ],
        true
    );

    if ( is_wp_error( $post_id ) ) {
        return 0;
    }

    update_post_meta( $post_id, '_aitd_website_url', $website_url );
    update_post_meta( $post_id, '_aitd_logo_url', aitd_normalize_url( $data['logo_url'] ?? ( $data['image_url'] ?? '' ) ) );
    update_post_meta( $post_id, '_aitd_pricing', sanitize_text_field( $data['pricing'] ?? 'Free' ) );
    update_post_meta( $post_id, '_aitd_featured', ! empty( $data['featured'] ) ? 1 : 0 );

    $categories = $data['categories'] ?? [];
    if ( is_string( $categories ) ) {
        $categories = array_filter( array_map( 'trim', preg_split( '/[|,]/', $categories ) ) );
    }

    if ( ! empty( $categories ) ) {
        $term_ids = [];
        foreach ( $categories as $category_name ) {
            $term = term_exists( $category_name, 'category' );
            if ( ! $term ) {
                $term = wp_insert_term( $category_name, 'category' );
            }

            if ( ! is_wp_error( $term ) ) {
                $term_ids[] = (int) ( is_array( $term ) ? $term['term_id'] : $term );
            }
        }

        if ( $term_ids ) {
            wp_set_post_terms( $post_id, $term_ids, 'category' );
        }
    }

    $tags = $data['tags'] ?? [];
    if ( is_string( $tags ) ) {
        $tags = array_filter( array_map( 'trim', preg_split( '/[|,]/', $tags ) ) );
    }

    if ( ! empty( $tags ) ) {
        wp_set_post_terms( $post_id, $tags, 'post_tag' );
    }

    return (int) $post_id;
}

add_action( 'admin_notices', 'aitd_import_admin_notices' );
function aitd_import_admin_notices() {
    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

    if ( ! $screen || AITD_POST_TYPE !== $screen->post_type ) {
        return;
    }

    if ( isset( $_GET['aitd_import'] ) && is_numeric( $_GET['aitd_import'] ) ) {
        ?>
        <div class="notice notice-success is-dismissible"><p><?php echo esc_html( sprintf( __( 'Imported %d tools.', 'aitd' ), (int) $_GET['aitd_import'] ) ); ?></p></div>
        <?php
    }

    if ( isset( $_GET['aitd_import_locked'] ) ) {
        ?>
        <div class="notice notice-info is-dismissible"><p><?php esc_html_e( 'Tool import is locked because it has already been used once.', 'aitd' ); ?></p></div>
        <?php
    }
}

function aitd_normalize_import_headers( $headers ) {
    $aliases = [
        'tool_name'         => 'title',
        'toolname'          => 'title',
        'name'              => 'title',
        'short_description' => 'short_description',
        'shortdescription'  => 'short_description',
        'description'       => 'description',
        'long_description'  => 'description',
        'longdescription'   => 'description',
        'full_description'  => 'description',
        'fulldescription'   => 'description',
        'website_url'       => 'website_url',
        'external_link'     => 'website_url',
        'externallink'      => 'website_url',
        'link'              => 'website_url',
        'url'               => 'website_url',
        'internal_link'     => 'internal_link',
        'internallink'      => 'internal_link',
        'logo_url'          => 'logo_url',
        'image_url'         => 'logo_url',
        'imageurl'          => 'logo_url',
        'image'             => 'logo_url',
        'pricing'           => 'pricing',
        'price'             => 'pricing',
        'featured'          => 'featured',
        'tags'              => 'tags',
        'tag'               => 'tags',
        'categories'        => 'categories',
        'category'          => 'categories',
    ];

    return array_map(
        static function( $header ) use ( $aliases ) {
            return $aliases[ $header ] ?? $header;
        },
        $headers
    );
}

add_action( 'admin_enqueue_scripts', 'aitd_admin_styles' );
function aitd_admin_styles( $hook ) {
    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

    if ( $screen && AITD_POST_TYPE === $screen->post_type ) {
        wp_enqueue_style( 'aitd-admin', AITD_URL . 'assets/admin.css' );
        return;
    }

    if ( false === strpos( $hook, 'aitd-import' ) ) {
        return;
    }

    wp_enqueue_style( 'aitd-admin', AITD_URL . 'assets/admin.css' );
}

add_action( 'add_meta_boxes', 'aitd_register_meta_boxes' );
function aitd_register_meta_boxes() {
    add_meta_box(
        'aitd-tool-details',
        __( 'Tool Details', 'aitd' ),
        'aitd_render_tool_details_meta_box',
        AITD_POST_TYPE,
        'normal',
        'high'
    );

    remove_meta_box( 'postexcerpt', AITD_POST_TYPE, 'normal' );
    add_meta_box(
        'aitd-tool-summary',
        __( 'Short Description', 'aitd' ),
        'aitd_render_excerpt_meta_box',
        AITD_POST_TYPE,
        'normal',
        'default'
    );

    remove_post_type_support( AITD_POST_TYPE, 'editor' );
    add_meta_box(
        'aitd-tool-description',
        __( 'Full Description', 'aitd' ),
        'aitd_render_description_meta_box',
        AITD_POST_TYPE,
        'normal',
        'default'
    );
}

function aitd_render_excerpt_meta_box( $post ) {
    ?>
    <div class="aitd-card" style="box-shadow:none;padding:0;border:none;">
        <p style="margin-bottom:12px;color:#667085;"><?php esc_html_e( 'Write a short one-line summary for the card view. Keep it clear and benefit-focused.', 'aitd' ); ?></p>
        <textarea name="excerpt" rows="4" style="width:100%;padding:12px;border:1px solid #d0d7e2;border-radius:10px;" placeholder="Example: AI writing assistant for blog posts, emails, and landing page copy."><?php echo esc_textarea( $post->post_excerpt ); ?></textarea>
    </div>
    <?php
}

function aitd_render_description_meta_box( $post ) {
    ?>
    <div class="aitd-card" style="box-shadow:none;padding:0;border:none;">
        <p style="margin-bottom:12px;color:#667085;"><?php esc_html_e( 'Write the full description visitors will read on the individual tool page. You can include paragraphs, benefits, use cases, and features.', 'aitd' ); ?></p>
        <?php
        wp_editor(
            $post->post_content,
            'content',
            [
                'textarea_name' => 'content',
                'textarea_rows' => 12,
                'media_buttons' => false,
            ]
        );
        ?>
    </div>
    <?php
}

function aitd_render_tool_details_meta_box( $post ) {
    wp_nonce_field( 'aitd_save_tool_meta', 'aitd_tool_meta_nonce' );

    $website_url = aitd_get_tool_meta( $post->ID, '_aitd_website_url' );
    $logo_url    = aitd_get_tool_meta( $post->ID, '_aitd_logo_url' );
    $pricing     = aitd_get_tool_meta( $post->ID, '_aitd_pricing', 'Free' );
    $featured    = (int) aitd_get_tool_meta( $post->ID, '_aitd_featured', 0 );
    ?>
    <div class="aitd-form-grid" style="grid-template-columns:2fr 1fr;">
        <div class="aitd-card">
            <div class="aitd-field">
                <label for="aitd_website_url"><?php esc_html_e( 'Website / Tool URL', 'aitd' ); ?></label>
                <input type="url" id="aitd_website_url" name="aitd_website_url" value="<?php echo esc_attr( $website_url ); ?>" placeholder="https://example.com">
            </div>
            <div class="aitd-field">
                <label for="aitd_logo_url"><?php esc_html_e( 'Logo / Icon URL', 'aitd' ); ?></label>
                <input type="url" id="aitd_logo_url" name="aitd_logo_url" value="<?php echo esc_attr( $logo_url ); ?>" placeholder="https://example.com/logo.png">
            </div>
            <p class="description"><?php esc_html_e( 'Use the post excerpt for the short description and the editor content for the full description.', 'aitd' ); ?></p>
        </div>

        <div class="aitd-card">
            <div class="aitd-field">
                <label for="aitd_pricing"><?php esc_html_e( 'Pricing Model', 'aitd' ); ?></label>
                <select id="aitd_pricing" name="aitd_pricing">
                    <?php foreach ( [ 'Free', 'Freemium', 'Paid', 'Contact for Pricing' ] as $option ) : ?>
                        <option value="<?php echo esc_attr( $option ); ?>" <?php selected( $pricing, $option ); ?>><?php echo esc_html( $option ); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="aitd-field aitd-toggle-field">
                <label for="aitd_featured"><?php esc_html_e( 'Featured Tool', 'aitd' ); ?></label>
                <label class="aitd-toggle">
                    <input type="checkbox" id="aitd_featured" name="aitd_featured" value="1" <?php checked( $featured, 1 ); ?>>
                    <span class="aitd-toggle-slider"></span>
                </label>
            </div>
        </div>
    </div>
    <?php
}

add_action( 'save_post_' . AITD_POST_TYPE, 'aitd_save_tool_meta' );
function aitd_save_tool_meta( $post_id ) {
    if ( ! isset( $_POST['aitd_tool_meta_nonce'] ) || ! wp_verify_nonce( $_POST['aitd_tool_meta_nonce'], 'aitd_save_tool_meta' ) ) {
        return;
    }

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    update_post_meta( $post_id, '_aitd_website_url', aitd_normalize_url( $_POST['aitd_website_url'] ?? '' ) );
    update_post_meta( $post_id, '_aitd_logo_url', aitd_normalize_url( $_POST['aitd_logo_url'] ?? '' ) );
    update_post_meta( $post_id, '_aitd_pricing', sanitize_text_field( $_POST['aitd_pricing'] ?? 'Free' ) );
    update_post_meta( $post_id, '_aitd_featured', isset( $_POST['aitd_featured'] ) ? 1 : 0 );

    if ( isset( $_POST['excerpt'] ) ) {
        remove_action( 'save_post_' . AITD_POST_TYPE, 'aitd_save_tool_meta' );
        wp_update_post(
            [
                'ID'           => $post_id,
                'post_excerpt' => sanitize_textarea_field( wp_unslash( $_POST['excerpt'] ) ),
            ]
        );
        add_action( 'save_post_' . AITD_POST_TYPE, 'aitd_save_tool_meta' );
    }
}

add_filter( 'enter_title_here', 'aitd_title_placeholder', 10, 2 );
function aitd_title_placeholder( $placeholder, $post ) {
    if ( $post instanceof WP_Post && AITD_POST_TYPE === $post->post_type ) {
        return __( 'Enter the AI tool name, for example ChatGPT', 'aitd' );
    }

    return $placeholder;
}

add_action( 'edit_form_after_title', 'aitd_editor_guidance' );
function aitd_editor_guidance( $post ) {
    if ( ! ( $post instanceof WP_Post ) || AITD_POST_TYPE !== $post->post_type ) {
        return;
    }
    ?>
    <div class="notice notice-info inline" style="margin:12px 0 18px;">
        <p><strong><?php esc_html_e( 'How to fill this tool entry', 'aitd' ); ?></strong></p>
        <p><?php esc_html_e( 'Title = tool name. Short Description = the small summary shown on cards. Main editor = the full long description shown on the single tool page.', 'aitd' ); ?></p>
    </div>
    <?php
}

add_filter( 'manage_' . AITD_POST_TYPE . '_posts_columns', 'aitd_admin_columns' );
function aitd_admin_columns( $columns ) {
    $columns['aitd_pricing']  = __( 'Pricing', 'aitd' );
    $columns['aitd_featured'] = __( 'Featured', 'aitd' );
    $columns['aitd_website']  = __( 'Website', 'aitd' );
    return $columns;
}

add_action( 'manage_' . AITD_POST_TYPE . '_posts_custom_column', 'aitd_render_admin_column', 10, 2 );
function aitd_render_admin_column( $column, $post_id ) {
    if ( 'aitd_pricing' === $column ) {
        echo esc_html( aitd_get_tool_meta( $post_id, '_aitd_pricing', 'Free' ) );
    }

    if ( 'aitd_featured' === $column ) {
        echo aitd_get_tool_meta( $post_id, '_aitd_featured', 0 ) ? 'Yes' : 'No';
    }

    if ( 'aitd_website' === $column ) {
        $url = aitd_get_tool_meta( $post_id, '_aitd_website_url' );
        if ( $url ) {
            echo '<a href="' . esc_url( $url ) . '" target="_blank" rel="noopener">Visit</a>';
        }
    }
}

add_action( 'admin_menu', 'aitd_import_menu' );
function aitd_import_menu() {
    if ( aitd_has_completed_import() ) {
        return;
    }

    add_submenu_page(
        'edit.php?post_type=' . AITD_POST_TYPE,
        __( 'Import AI Tools', 'aitd' ),
        __( 'Import Tools', 'aitd' ),
        'manage_options',
        'aitd-import',
        'aitd_render_import_page'
    );
}

add_action( 'admin_init', 'aitd_handle_import' );
function aitd_handle_import() {
    if ( ! isset( $_POST['aitd_import_tools'] ) && ! isset( $_POST['aitd_download_template'] ) && ! isset( $_POST['aitd_import_starter_tools'] ) ) {
        return;
    }

    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( aitd_has_completed_import() ) {
        wp_safe_redirect( admin_url( 'edit.php?post_type=' . AITD_POST_TYPE . '&aitd_import_locked=1' ) );
        exit;
    }

    if ( isset( $_POST['aitd_download_template'] ) ) {
        check_admin_referer( 'aitd_import_tools' );

        $template = "title,short_description,description,website_url,logo_url,pricing,featured,categories,tags\n";
        $template .= "\"ChatGPT\",\"AI assistant for writing, research, and everyday tasks.\",\"ChatGPT helps teams and individuals write, brainstorm, research, and automate workflows with natural language prompts.\",\"https://chatgpt.com/\",\"https://chatgpt.com/favicon.ico\",\"Freemium\",\"1\",\"Writing & Content|Productivity & Automation\",\"assistant|chatbot|writing\"\n";
        $template .= "\"Midjourney\",\"AI image generator for concept art and creative visuals.\",\"Midjourney creates stylized images from prompts for design, ideation, advertising, and creative production.\",\"https://www.midjourney.com/\",\"https://www.midjourney.com/favicon.ico\",\"Paid\",\"0\",\"Image & Design\",\"image generation|art|design\"\n";

        nocache_headers();
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=ai-tools-import-template.csv' );
        echo $template;
        exit;
    }

    check_admin_referer( 'aitd_import_tools' );

    if ( isset( $_POST['aitd_import_starter_tools'] ) ) {
        $imported = 0;

        foreach ( aitd_get_curated_import_tools() as $tool ) {
            $imported += aitd_insert_imported_tool( $tool ) ? 1 : 0;
        }

        if ( $imported > 0 ) {
            aitd_mark_import_completed();
        }

        wp_safe_redirect( add_query_arg( 'aitd_import', $imported, admin_url( 'edit.php?post_type=' . AITD_POST_TYPE ) ) );
        exit;
    }

    if ( empty( $_FILES['aitd_import_file']['tmp_name'] ) ) {
        wp_safe_redirect( add_query_arg( 'aitd_import', 'missing_file', admin_url( 'edit.php?post_type=' . AITD_POST_TYPE . '&page=aitd-import' ) ) );
        exit;
    }

    $file = fopen( $_FILES['aitd_import_file']['tmp_name'], 'r' );
    if ( ! $file ) {
        wp_safe_redirect( add_query_arg( 'aitd_import', 'open_failed', admin_url( 'edit.php?post_type=' . AITD_POST_TYPE . '&page=aitd-import' ) ) );
        exit;
    }

    $headers = fgetcsv( $file );
    if ( ! $headers ) {
        fclose( $file );
        wp_safe_redirect( add_query_arg( 'aitd_import', 'empty_file', admin_url( 'edit.php?post_type=' . AITD_POST_TYPE . '&page=aitd-import' ) ) );
        exit;
    }

    $headers = array_map(
        static function( $header ) {
            $header = trim( (string) $header );
            $header = preg_replace( '/^\xEF\xBB\xBF/', '', $header );
            $header = strtolower( $header );
            $header = preg_replace( '/[\s\-\/]+/', '_', $header );
            return sanitize_key( $header );
        },
        $headers
    );

    $headers = array_values( array_filter( $headers ) );
    $headers = aitd_normalize_import_headers( $headers );

    $imported = 0;

    while ( false !== ( $row = fgetcsv( $file ) ) ) {
        if ( ! is_array( $row ) ) {
            continue;
        }

        $non_empty_row = array_filter(
            $row,
            static function( $value ) {
                return '' !== trim( (string) $value );
            }
        );

        if ( empty( $non_empty_row ) ) {
            continue;
        }

        if ( count( $row ) > count( $headers ) ) {
            $row = array_slice( $row, 0, count( $headers ) );
        }

        $row = array_pad( $row, count( $headers ), '' );

        if ( count( $headers ) !== count( $row ) ) {
            continue;
        }

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

        if ( false === $data ) {
            continue;
        }

        $categories_source = $data['categories'] ?? '';
        if ( '' === trim( (string) $categories_source ) ) {
            $categories_source = $data['tags'] ?? '';
        }

        $data['categories'] = array_filter( array_map( 'trim', preg_split( '/[|,]/', (string) $categories_source ) ) );
        $data['tags']       = array_filter( array_map( 'trim', preg_split( '/[|,]/', (string) ( $data['tags'] ?? '' ) ) ) );

        $imported += aitd_insert_imported_tool( $data ) ? 1 : 0;
    }

    fclose( $file );

    if ( $imported > 0 ) {
        aitd_mark_import_completed();
    }

    wp_safe_redirect( add_query_arg( 'aitd_import', $imported, admin_url( 'edit.php?post_type=' . AITD_POST_TYPE ) ) );
    exit;
}

function aitd_render_import_page() {
    if ( aitd_has_completed_import() ) {
        ?>
        <div class="wrap aitd-wrap">
            <h1><?php esc_html_e( 'Import AI Tools', 'aitd' ); ?></h1>
            <div class="notice notice-info"><p><?php esc_html_e( 'The import has already been completed once, so this page is now locked to prevent duplicate tool entries.', 'aitd' ); ?></p></div>
        </div>
        <?php
        return;
    }

    ?>
    <div class="wrap aitd-wrap">
        <h1><?php esc_html_e( 'Import AI Tools', 'aitd' ); ?></h1>
        <div class="aitd-card" style="max-width:760px;">
            <p><strong><?php esc_html_e( 'Recommended:', 'aitd' ); ?></strong> <?php esc_html_e( 'Import the curated starter collection once to instantly populate the directory with well-known, useful AI tools.', 'aitd' ); ?></p>
            <p><?php esc_html_e( 'Starter tools included:', 'aitd' ); ?> <?php echo esc_html( implode( ', ', aitd_get_curated_tool_names() ) ); ?></p>
            <form method="post" style="margin:16px 0 22px;">
                <?php wp_nonce_field( 'aitd_import_tools' ); ?>
                <button type="submit" name="aitd_import_starter_tools" class="button button-primary"><?php esc_html_e( 'Import Curated Starter Tools', 'aitd' ); ?></button>
            </form>

            <p><?php esc_html_e( 'Upload a CSV to import many tools at once. Supported columns: title, short_description, description, website_url, logo_url or image_url, pricing, featured, categories or category, tags.', 'aitd' ); ?></p>
            <p><?php esc_html_e( 'Use | or commas between multiple categories or tags in one cell. Categories will be created automatically if they do not exist yet.', 'aitd' ); ?></p>
            <form method="post" enctype="multipart/form-data">
                <?php wp_nonce_field( 'aitd_import_tools' ); ?>
                <input type="file" name="aitd_import_file" accept=".csv" required>
                <p style="margin-top:16px;">
                    <button type="submit" name="aitd_import_tools" class="button button-primary"><?php esc_html_e( 'Import Tools', 'aitd' ); ?></button>
                    <button type="submit" name="aitd_download_template" class="button"><?php esc_html_e( 'Download CSV Template', 'aitd' ); ?></button>
                </p>
            </form>
        </div>
    </div>
    <?php
}

function aitd_maybe_migrate_legacy_tools() {
    global $wpdb;

    $table = $wpdb->prefix . 'ai_tools';
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );

    if ( $table_exists !== $table || get_option( 'aitd_legacy_migrated' ) ) {
        return;
    }

    $tools = $wpdb->get_results( "SELECT * FROM {$table} ORDER BY id ASC" );

    foreach ( $tools as $tool ) {
        $existing = get_page_by_path( $tool->slug, OBJECT, AITD_POST_TYPE );
        if ( $existing ) {
            continue;
        }

        $post_id = wp_insert_post(
            [
                'post_type'    => AITD_POST_TYPE,
                'post_status'  => 'publish',
                'post_title'   => $tool->title,
                'post_name'    => $tool->slug,
                'post_excerpt' => $tool->short_description,
                'post_content' => $tool->description,
                'post_date'    => $tool->created_at ? gmdate( 'Y-m-d H:i:s', strtotime( $tool->created_at ) ) : current_time( 'mysql' ),
            ],
            true
        );

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

        update_post_meta( $post_id, '_aitd_website_url', aitd_normalize_url( $tool->website_url ) );
        update_post_meta( $post_id, '_aitd_logo_url', aitd_normalize_url( $tool->logo_url ) );
        update_post_meta( $post_id, '_aitd_pricing', sanitize_text_field( $tool->pricing ?: 'Free' ) );
        update_post_meta( $post_id, '_aitd_featured', (int) $tool->featured );

        if ( ! empty( $tool->category ) ) {
            $term = term_exists( $tool->category, 'category' );
            if ( ! $term ) {
                $term = wp_insert_term( $tool->category, 'category' );
            }

            if ( ! is_wp_error( $term ) ) {
                wp_set_post_terms( $post_id, [ (int) ( is_array( $term ) ? $term['term_id'] : $term ) ], 'category' );
            }
        }

        if ( ! empty( $tool->tags ) ) {
            $tags = array_filter( array_map( 'trim', explode( ',', $tool->tags ) ) );
            if ( $tags ) {
                wp_set_post_terms( $post_id, $tags, 'post_tag' );
            }
        }
    }

    update_option( 'aitd_legacy_migrated', 1 );
}
