<?php
add_action( 'wp_ajax_cctv_services_run_demo_import', 'cctv_services_run_demo_import' );

function cctv_services_run_demo_import() {

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

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

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

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

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

    $cctv_services_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 ( $cctv_services_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;
        $cctv_services_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 */
    $cctv_services_products = array(
        array(
            'title' => 'Product Name Here',
            'price' => '25.00',
            'sale_price' => '20.00',
            'image' => get_stylesheet_directory() . '/assets/images/product1.png'
        ),
        array(
            'title' => 'Product Name Here',
            'price' => '25.00',
            'sale_price' => '20.00',
            'image' => get_stylesheet_directory() . '/assets/images/new-product2.png'
        ),
        array(
            'title' => 'NightGuard HD Dome Camera',
            'price' => '1200.00',
            'sale_price' => '800.00',
            'image' => get_stylesheet_directory() . '/assets/images/new-product1.png'
        ),
        array(
            'title' => 'NightGuard HD Dome Camera',
            'price' => '1200.00',
            'sale_price' => '800.00',
            'image' => get_stylesheet_directory() . '/assets/images/new-product2.png'
        ),
        array(
            'title' => 'NightGuard HD Dome Camera',
            'price' => '1200.00',
            'sale_price' => '800.00',
            'image' => get_stylesheet_directory() . '/assets/images/new-product3.png'
        )
    );

    foreach ( $cctv_services_products as $cctv_services_index => $cctv_services_product ) {

        // Insert product
        $cctv_services_product_id = wp_insert_post( array(
            'post_title'   => $cctv_services_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( $cctv_services_product_id ) ) {
            continue;
        }

        // Set product price
        update_post_meta( $cctv_services_product_id, '_regular_price', $cctv_services_product['price'] );

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

        // Assign category
        wp_set_object_terms(
            $cctv_services_product_id,
            $cctv_services_category_ids[ $cctv_services_index % count( $cctv_services_category_ids ) ],
            'product_cat'
        );

        /* FEATURED IMAGE */
        if ( ! empty( $cctv_services_product['image'] ) && file_exists( $cctv_services_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 = $cctv_services_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, $cctv_services_product_id );

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

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

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

    wp_send_json_success( 'Demo imported successfully' );
}
