<?php
add_action( 'wp_ajax_vehicle_detailing_run_demo_import', 'vehicle_detailing_run_demo_import' );

function vehicle_detailing_run_demo_import() {

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

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

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

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

    /* PRODUCT CATEGORIES */
    $vehicle_detailing_categories = array(
        'Premium Detailing',
        'Ceramic Protection',
        'Interior Makeover',
        'Car Care Packages'
    );

    $vehicle_detailing_category_ids = array();

    foreach ( $vehicle_detailing_categories as $vehicle_detailing_cat ) {
        $vehicle_detailing_term = term_exists( $vehicle_detailing_cat, 'product_cat' );
        if ( ! $vehicle_detailing_term ) {
            $vehicle_detailing_term = wp_insert_term( $vehicle_detailing_cat, 'product_cat' );
        }
        $vehicle_detailing_category_ids[] = (int) $vehicle_detailing_term['term_id'];
    }

    /* PRODUCTS */
    $vehicle_detailing_products = array(
        array(
            'title' => 'Express Wash',
            'price' => '25',
            'image' => get_stylesheet_directory() . '/images/product1.png',
            'short_description' => 'Fast and efficient exterior car wash service.Removes dirt, dust, and road grime quickly.',
            'description' => 'Our Express Wash is designed for drivers who want quick and reliable car cleaning.It includes foam wash, high-pressure rinse, and gentle hand drying.
             Perfect for daily or weekly maintenance.Keeps your car looking fresh and well maintained.Ideal for busy schedules.'
        ),
        array(
            'title' => 'Ceramic Pro',
            'price' => '25',
            'image' => get_stylesheet_directory() . '/images/product2.png',
            'short_description' => 'Advanced ceramic protection for long-lasting shine.Guards paint against dirt and UV damage.',
            'description' => 'Ceramic Pro provides a durable protective layer for your vehicle.It enhances gloss while repelling water and contaminants.Helps prevent fading, oxidation, and light scratches.
             Easy to maintain with long-term protection.Perfect for premium car care.'
        ),
        array(
            'title' => 'Ultimate Makeover',
            'price' => '25',
            'image' => get_stylesheet_directory() . '/images/product3.png',
            'short_description' => 'Complete interior and exterior car transformation.Restores showroom-level appearance.',
            'description' => 'The Ultimate Makeover offers full car rejuvenation.Includes deep interior cleaning and exterior polishing.Removes stains, odors, and surface imperfections.
             Enhances shine and comfort inside the cabin.Best choice for total vehicle refresh.'
        ),
        array(
            'title' => 'Premium Detailing',
            'price' => '25',
            'image' => get_stylesheet_directory() . '/images/product4.png',
            'short_description' => 'High-end detailing for superior finish.Designed for luxury and performance vehicles.',
            'description' => 'Premium Detailing delivers meticulous care for your car.Includes thorough washing, polishing, and waxing.Interior surfaces are cleaned and protected carefully.
             Restores original shine and elegance.Ideal for car enthusiasts and professionals.'
        ),
    );

    foreach ( $vehicle_detailing_products as $vehicle_detailing_index => $vehicle_detailing_product ) {

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

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

        // Set product price
        update_post_meta( $vehicle_detailing_product_id, '_regular_price', $vehicle_detailing_product['price'] );
        update_post_meta( $vehicle_detailing_product_id, '_price', $vehicle_detailing_product['price'] );

        // Assign category
        wp_set_object_terms(
            $vehicle_detailing_product_id,
            $vehicle_detailing_category_ids[ $vehicle_detailing_index % count( $vehicle_detailing_category_ids ) ],
            'product_cat'
        );

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

            $vehicle_detailing_image_path = $vehicle_detailing_product['image'];

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

            if ( $vehicle_detailing_tmp_file ) {
                copy( $vehicle_detailing_image_path, $vehicle_detailing_tmp_file );

                $vehicle_detailing_file_array = array(
                    'name'     => basename( $vehicle_detailing_image_path ),
                    'tmp_name' => $vehicle_detailing_tmp_file
                );

                // Upload to WordPress media library
                $vehicle_detailing_attachment_id = media_handle_sideload( $vehicle_detailing_file_array, $vehicle_detailing_product_id );

                // Clean up temp file if error
                if ( is_wp_error( $vehicle_detailing_attachment_id ) ) {
                    @unlink( $vehicle_detailing_tmp_file );
                } else {
                    set_post_thumbnail( $vehicle_detailing_product_id, $vehicle_detailing_attachment_id );
                }
            }
        }
    }

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

    wp_send_json_success( 'Demo imported successfully' );
}
