<?php
add_action( 'wp_ajax_dropshipping_shop_run_demo_import', 'dropshipping_shop_run_demo_import' );

function dropshipping_shop_run_demo_import() {

    // Verify nonce
    check_ajax_referer( 'dropshipping_shop_demo_nonce', 'nonce' );

    // Check permissions
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Permission denied' );
    }

    // Prevent duplicate import
    if ( get_option( 'dropshipping_shop_demo_import_completed' ) ) {
        wp_send_json_success( 'Already imported' );
    }

    // WooCommerce check
    if ( ! class_exists( 'WooCommerce' ) ) {
        wp_send_json_error( 'WooCommerce not active' );
    }

    /* PRODUCT CATEGORIES */
    $dropshipping_shop_categories = array(
    'Home & Living'
    );

    $dropshipping_shop_category_ids = array();

    foreach ( $dropshipping_shop_categories as $dropshipping_shop_cat ) {
        $dropshipping_shop_term = term_exists( $dropshipping_shop_cat, 'product_cat' );
        if ( ! $dropshipping_shop_term ) {
            $dropshipping_shop_term = wp_insert_term( $dropshipping_shop_cat, 'product_cat' );
        }
        $dropshipping_shop_category_ids[] = (int) $dropshipping_shop_term['term_id'];
    }

    /* PRODUCTS */
    $dropshipping_shop_products = array(
        array(
            'title' => 'Timber Light',
            'price' => '120',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Elegant decorative timber lantern for modern homes.',
            'description' => 'The Timber Light is a stylish home décor lantern crafted with a wooden finish.
            Perfect for living rooms, bedrooms, and festive décor.
            Adds warmth and a cozy ambiance to your interior spaces.'
        ),
        array(
            'title' => 'Excite Run',
            'price' => '850',
            'image' => get_stylesheet_directory() . '/images/product2.png',
            'short_description' => 'Compact treadmill suitable for home workouts.',
            'description' => 'This Timber Light treadmill is ideal for indoor fitness routines.
            Designed for comfort and durability with smooth performance.
            Suitable for daily walking and light running exercises.'
        ),
        array(
            'title' => 'AKG Kettlebell',
            'price' => '220',
            'image' => get_stylesheet_directory() . '/images/product3.png',
            'short_description' => 'Heavy-duty kettlebell for strength training.',
            'description' => 'The Timber Light kettlebell is built for strength and endurance training.
            Ideal for home gyms and functional workouts.
            Durable grip and balanced weight for safe exercise.'
        ),
        array(
            'title' => 'Pet Inn',
            'price' => '95',
            'image' => get_stylesheet_directory() . '/images/product4.png',
            'short_description' => 'Minimal black feeding bowl for pets.',
            'description' => 'A sleek and durable pet bowl designed for everyday use.
            Easy to clean and suitable for both food and water.
            Perfect for modern pet-friendly homes.'
        ),
    );

    foreach ( $dropshipping_shop_products as $dropshipping_shop_index => $dropshipping_shop_product ) {

        // Insert product
        $dropshipping_shop_product_id = wp_insert_post( array(
        'post_title'   => $dropshipping_shop_product['title'],
        'post_content' => $dropshipping_shop_product['description'], 
        'post_excerpt' => $dropshipping_shop_product['short_description'], 
        'post_status'  => 'publish',
        'post_type'    => 'product',
        ));

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

        // Set product price
        update_post_meta( $dropshipping_shop_product_id, '_regular_price', $dropshipping_shop_product['price'] );
        update_post_meta( $dropshipping_shop_product_id, '_price', $dropshipping_shop_product['price'] );

        // Assign category
        wp_set_object_terms(
            $dropshipping_shop_product_id,
            $dropshipping_shop_category_ids[ $dropshipping_shop_index % count( $dropshipping_shop_category_ids ) ],
            'product_cat'
        );

        /* FEATURED IMAGE*/
        if ( ! empty( $dropshipping_shop_product['image'] ) && file_exists( $dropshipping_shop_product['image'] ) ) {

            $dropshipping_shop_image_path = $dropshipping_shop_product['image'];

            // Create a temporary file in wp-content/uploads
            $dropshipping_shop_tmp_file = wp_tempnam( $dropshipping_shop_image_path );

            if ( $dropshipping_shop_tmp_file ) {
                copy( $dropshipping_shop_image_path, $dropshipping_shop_tmp_file );

                $dropshipping_shop_file_array = array(
                    'name'     => basename( $dropshipping_shop_image_path ),
                    'tmp_name' => $dropshipping_shop_tmp_file
                );

                // Upload to WordPress media library
                $dropshipping_shop_attachment_id = media_handle_sideload( $dropshipping_shop_file_array, $dropshipping_shop_product_id );

                // Clean up temp file if error
                if ( is_wp_error( $dropshipping_shop_attachment_id ) ) {
                    @unlink( $dropshipping_shop_tmp_file );
                } else {
                    set_post_thumbnail( $dropshipping_shop_product_id, $dropshipping_shop_attachment_id );
                }
            }
        }
    }

    // Mark demo import as completed
    update_option( 'dropshipping_shop_demo_import_completed', true );

    wp_send_json_success( 'Demo imported successfully' );
}
