<?php
add_action( 'wp_ajax_interior_store_run_demo_import', 'interior_store_run_demo_import' );

function interior_store_run_demo_import() {

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

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

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

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

    /* PRODUCT CATEGORIES */
    $interior_store_categories = array(
        'Living Room',
        'Furniture',
        'Chairs',
        'Home Decor'
    );

    $interior_store_category_ids = array();

    foreach ( $interior_store_categories as $interior_store_cat ) {
        $interior_store_term = term_exists( $interior_store_cat, 'product_cat' );
        if ( ! $interior_store_term ) {
            $interior_store_term = wp_insert_term( $interior_store_cat, 'product_cat' );
        }
        $interior_store_category_ids[] = (int) $interior_store_term['term_id'];
    }

    /* PRODUCTS */
    $interior_store_products = array(
        array(
            'title' => 'Sofa',
            'price' => '49.99',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Comfortable modern sofa for stylish living rooms.',
            'description' => 'This premium sofa is designed for maximum comfort and elegance. Perfect for modern interiors, it blends durability with a soft, relaxing feel. Ideal for daily use and long seating hours.'
        ),
        array(
            'title' => 'Table',
            'price' => '49.99',
            'image' => get_stylesheet_directory() . '/images/product2.png',
            'short_description' => 'Elegant wooden table with a classic finish.',
            'description' => 'A beautifully crafted table made with durable wood. Its timeless design fits seamlessly into any interior, perfect for decor or daily use.'
        ),
        array(
            'title' => 'Modular Chair',
            'price' => '49.99',
            'image' => get_stylesheet_directory() . '/images/product3.png',
            'short_description' => 'Luxury modular chair with premium cushioning.',
            'description' => 'This modular chair offers superior comfort and an elegant design. Ideal for reading corners, lounges, or premium interior setups.'
        ),
        array(
            'title' => 'Minimalist Desk Plant',
            'price' => '49.99',
            'image' => get_stylesheet_directory() . '/images/product4.png',
            'short_description' => 'Minimal desk plant to enhance your workspace.',
            'description' => 'A modern minimalist plant that adds freshness and style to your desk or interior spaces. Easy to maintain and visually calming.'
        ),
    );

    foreach ( $interior_store_products as $interior_store_index => $interior_store_product ) {

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

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

        // Set product price
        update_post_meta( $interior_store_product_id, '_regular_price', $interior_store_product['price'] );
        update_post_meta( $interior_store_product_id, '_price', $interior_store_product['price'] );

        // Assign category
        wp_set_object_terms(
            $interior_store_product_id,
            $interior_store_category_ids[ $interior_store_index % count( $interior_store_category_ids ) ],
            'product_cat'
        );

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

            $interior_store_image_path = $interior_store_product['image'];

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

            if ( $interior_store_tmp_file ) {
                copy( $interior_store_image_path, $interior_store_tmp_file );

                $interior_store_file_array = array(
                    'name'     => basename( $interior_store_image_path ),
                    'tmp_name' => $interior_store_tmp_file
                );

                // Upload to WordPress media library
                $interior_store_attachment_id = media_handle_sideload( $interior_store_file_array, $interior_store_product_id );

                // Clean up temp file if error
                if ( is_wp_error( $interior_store_attachment_id ) ) {
                    @unlink( $interior_store_tmp_file );
                } else {
                    set_post_thumbnail( $interior_store_product_id, $interior_store_attachment_id );
                }
            }
        }
    }

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

    wp_send_json_success( 'Demo imported successfully' );
}
