<?php
add_action( 'wp_ajax_summer_program_run_demo_import', 'summer_program_run_demo_import' );

function summer_program_run_demo_import() {

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

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

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

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

    /* PRODUCT CATEGORIES */
    $summer_program_categories = array(
        array(
            'name'  => 'Camera',
        ),
    );

    $summer_program_category_ids = array();

    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';
    foreach ( $summer_program_categories as $category ) {

        $term = term_exists( $category['name'], 'product_cat' );

        if ( ! $term ) {
            $term = wp_insert_term( $category['name'], 'product_cat' );
        }

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

        $term_id = is_array( $term ) ? $term['term_id'] : $term;
        $summer_program_category_ids[] = (int) $term_id;

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

            $upload_dir = wp_upload_dir();
            $filename   = basename( $category['image'] );
            $new_path   = $upload_dir['path'] . '/' . $filename;

            if ( copy( $category['image'], $new_path ) ) {

                $filetype = wp_check_filetype( $filename, null );

                $attachment = array(
                    'post_mime_type' => $filetype['type'],
                    'post_title'     => sanitize_file_name( $filename ),
                    'post_status'    => 'inherit'
                );

                $attach_id = wp_insert_attachment( $attachment, $new_path );

                $attach_data = wp_generate_attachment_metadata( $attach_id, $new_path );
                wp_update_attachment_metadata( $attach_id, $attach_data );

                update_term_meta( $term_id, 'thumbnail_id', $attach_id );
            }
        }
    }

    /* PRODUCTS */
    $summer_program_products = array(
        array(
            'title' => 'Product Name Here',
            'price' => '25.00',
            'sale_price' => '20.00',
            'image' => get_stylesheet_directory() . '/assets/images/service-img2.png'
        ),
        array(
            'title' => 'Product Name Here',
            'price' => '25.00',
            'sale_price' => '20.00',
            'image' => get_stylesheet_directory() . '/assets/images/service-img3.png'
        ),
    );

    foreach ( $summer_program_products as $summer_program_index => $summer_program_product ) {

        // Insert product
        $summer_program_product_id = wp_insert_post( array(
            'post_title'   => $summer_program_product['title'],
            'post_content' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.', 
            'post_excerpt' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 
            'post_status'  => 'publish',
            'post_type'    => 'product',
        ));

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

        // Set product price
        update_post_meta( $summer_program_product_id, '_regular_price', $summer_program_product['price'] );

        if ( ! empty( $summer_program_product['sale_price'] ) ) {
            update_post_meta( $summer_program_product_id, '_sale_price', $summer_program_product['sale_price'] );
            update_post_meta( $summer_program_product_id, '_price', $summer_program_product['sale_price'] );
        } else {
            update_post_meta( $summer_program_product_id, '_price', $summer_program_product['price'] );
        }

        // Assign category
        wp_set_object_terms(
            $summer_program_product_id,
            $summer_program_category_ids[ $summer_program_index % count( $summer_program_category_ids ) ],
            'product_cat'
        );

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

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

            $image_path = $summer_program_product['image'];

            $upload_dir = wp_upload_dir();
            $filename   = basename( $image_path );

            // Copy image to uploads directory
            $new_file_path = $upload_dir['path'] . '/' . $filename;

            if ( copy( $image_path, $new_file_path ) ) {

                $filetype = wp_check_filetype( $filename, null );

                $attachment = array(
                    'post_mime_type' => $filetype['type'],
                    'post_title'     => sanitize_file_name( $filename ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );

                $attach_id = wp_insert_attachment( $attachment, $new_file_path, $summer_program_product_id );

                $attach_data = wp_generate_attachment_metadata( $attach_id, $new_file_path );
                wp_update_attachment_metadata( $attach_id, $attach_data );

                set_post_thumbnail( $summer_program_product_id, $attach_id );
            }
        }
    }

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

    wp_send_json_success( 'Demo imported successfully' );
}
