<?php
add_action( 'wp_ajax_vw_furniture_shop_run_demo_import', 'vw_furniture_shop_run_demo_import' );

function vw_furniture_shop_run_demo_import() {

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

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

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

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

    /*   PRODUCT CATEGORY */

    $category_name = 'Furniture';

    $term = term_exists( $category_name, 'product_cat' );
    if ( ! $term ) {
        $term = wp_insert_term( $category_name, 'product_cat' );
    }

    $category_id = (int) $term['term_id'];

    /*   PRODUCTS (Screenshot Based) */

    $products = array(

        array(
            'title' => 'Charcoal Grey Sofa',
            'regular_price' => '580',
            'sale_price' => '320',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Modern charcoal grey sofa with premium comfort and stylish design.',
            'description' => 'Upgrade your living space with this elegant Charcoal Grey Sofa. Crafted with high-quality fabric and sturdy frame, it offers superior comfort and durability. Perfect for modern interiors and spacious living rooms.'
        ),

        array(
            'title' => 'Brown Sofa',
            'regular_price' => '480',
            'sale_price' => '300',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Comfortable brown sectional sofa designed for modern homes.',
            'description' => 'This Brown Sofa adds warmth and sophistication to your home. Designed with plush cushions and strong support, it ensures long-lasting relaxation. Ideal for family gatherings and cozy evenings.'
        ),

        array(
            'title' => 'Beige Sofa',
            'regular_price' => '300',
            'sale_price' => '280',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Elegant beige sofa with luxurious finishing and premium feel.',
            'description' => 'The Beige Sofa offers a minimal and classy look for contemporary interiors. Built with premium upholstery and comfort-focused design, it blends perfectly with any décor style.'
        ),

    );

    /*   INSERT PRODUCTS */

    foreach ( $products as $product ) {

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

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

        // Set product type
        wp_set_object_terms( $product_id, 'simple', 'product_type' );

        // Set category
        wp_set_object_terms( $product_id, $category_id, 'product_cat' );

        // Set prices
        update_post_meta( $product_id, '_regular_price', $product['regular_price'] );
        update_post_meta( $product_id, '_sale_price', $product['sale_price'] );
        update_post_meta( $product_id, '_price', $product['sale_price'] );

        // Stock
        update_post_meta( $product_id, '_stock_status', 'instock' );
        update_post_meta( $product_id, '_manage_stock', 'no' );

        /* 
           FEATURED IMAGE
        = */

        if ( ! empty( $product['image'] ) && file_exists( $product['image'] ) ) {

            $tmp = wp_tempnam( $product['image'] );

            if ( $tmp ) {

                copy( $product['image'], $tmp );

                $file_array = array(
                    'name'     => basename( $product['image'] ),
                    'tmp_name' => $tmp
                );

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

                $attachment_id = media_handle_sideload( $file_array, $product_id );

                if ( ! is_wp_error( $attachment_id ) ) {
                    set_post_thumbnail( $product_id, $attachment_id );
                } else {
                    @unlink( $tmp );
                }
            }
        }
    }

    // Mark import complete
    update_option( 'vw_furniture_shop_demo_import_completed', true );

    wp_send_json_success( 'Demo imported successfully' );
}
