<?php

namespace Amazon\Affiliate\Admin;

/**

 * Class ProductImportByUrl

 * @package Amazon\Affiliate\Admin

 */

class ProductImportByUrl extends ProductsSearchWithoutApi
{

    /**

     * ProductImportByUrl constructor.

     */

    public function __construct()
    {

    }

    /**

     * Load product import page

     */

    public function product_import_page()
    {
        $this->get_amazon_cat();
        $this->get_wc_terms();
                 
        $template = __DIR__ . '/views/product-import-by-url.php';

        if (file_exists($template)) {

            require_once $template;

        }

    }

    /**

     * Product import by amazon url

     */

    public function product_import_by_url() {    
        $regions      = ams_get_amazon_regions();
        $locale = get_option( 'ams_amazon_country' );
        if(!isset($_POST['is_cron']) || $_POST['is_cron'] != 1){
            $region   = $regions[ $locale ]['RegionCode'];
        } else {
            $region   = isset($_POST['region']) ? $_POST['region'] : "";
        }


        $nonce = sanitize_text_field($_POST['nonce']);
        if (!wp_verify_nonce($nonce, 'ams_import_product_url')) {
            die(esc_html__('Busted!', 'ams-wc-amazon'));
        }
        if (isset($_POST['setSession']) && $_POST['setSession'] == true) {
            $product_urls = array_filter(explode(',', $_POST['product_url']));
            $response['product_urls'] = $product_urls;
            $response['product_url_string'] = implode(',', $product_urls);
            echo json_encode($response);
            wp_die();
        }
        if (ams_plugin_license_status() === false) {
            $license = sprintf('<div class="alert alert-warning mx-3 text-left" role="alert">%s</div>', esc_html__('Please activate the plugin license before searching the product.', 'ams-wc-amazon'));
            echo wp_kses_post($license);
            wp_die();
        }
        $this->active_site();
        $product_url = sanitize_text_field($_POST['product_url']);
        $response_body = $this->getAmazonPageHtml($product_url);



        $user_agent = $this->user_agent();
        

        $options = array(
              'http'=>array(
                'method'=>"GET",
                'header'=>"Accept-language: en\r\n" .
                          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36\r\n" // i.e. An iPad 
              )
            );
        // code run wait
        sleep( rand( 1, 5 ) );
        $context = stream_context_create( $options );
        // wp_remote_get() not working properly so I'm forced to use it
        $response_body = $page = file_get_contents( esc_url_raw( $product_url ), false, $context );

        /*if (strpos($response_body['body'], 'captcha') > 0) {
            $massage = sprintf('<div class="alert alert-danger mx-3 text-left" role="alert">%s</div>' , esc_html__('Too many attempts triggered for this amazon product, please try again after 48 hours! You can still try importing other products.', 'ams-wc-amazon'));
            echo wp_kses_post($massage);
            wp_die();
        }*/
        if (!empty($response_body)) {
            if (!class_exists('simple_html_dom')) {
                require_once AMS_PLUGIN_PATH . '/includes/Admin/lib/simplehtmldom/simple_html_dom.php';
            }
            $html = new \simple_html_dom();
            $html->load($response_body);
            // echo $html;wp_die();
            // Parser amazon product asin
            $asin = $html->find('#ASIN')[0]->value;
            if(empty($asin)) {
                $asin = $html->find('input[name="ASIN.0"]')[0]->value;
            }
            if(empty($asin)) {
                $urlArray = explode("dp/", $product_url);
                $urlArray = explode("/", $urlArray[1]);
                $asin = $urlArray[0];
            }
            if(empty($asin)) {
                die(esc_html__('ASIN not found!', 'ams-wc-amazon'));
            }
            $ams_all_asin = ams_get_all_products_info();
            if (!empty($ams_all_asin) && !empty($ams_all_asin['asin']) && in_array($asin, $ams_all_asin['asin']) ) {
                $massage = sprintf('<div class="alert alert-warning mx-3 text-left" role="alert">%s</div>', esc_html__(' This product is already imported', 'ams-wc-amazon'));
                echo $massage;
                wp_die();
            }
            $pricing = $this->fetchPriceFromHtml($html,$page);
            //var_dump($pricing);
            /*echo $page;
            exit;*/
            $title = $html->find('#productTitle');
            $title = $title[0]->innertext;
            $product_status = 'instock';
            if ($html->find('#outOfStock .a-color-price', 0)) {
                $product_status = 'outofstock';
            }
            $content = $this->fetchContentFromHtml($html);
            if (!empty($content)) {
                $gallery = $this->fetchImagesFromHtml($html);
                $image = $gallery[0];
                unset($gallery[0]);
                $user_id = get_current_user();
                $post_id = wp_insert_post(array(
                    'post_author' => $user_id,
                    'post_title' => stripslashes($title),
                    'post_content' => $content,
                    'post_status' => 'publish',
                    'post_type' => "product",
                    'post_parent' => '',
                ));
                wp_set_object_terms($post_id, 'simple', 'product_type');
                $product_category = $this->syncAndGetCategory($html);
                if(!empty($product_category)) {
                    wp_set_object_terms($post_id, $product_category, 'product_cat');
                }
                update_post_meta($post_id, '_visibility', 'visible');
                update_post_meta($post_id, '_stock_status', $product_status);
                update_post_meta($post_id, 'total_sales', '0');
                update_post_meta($post_id, '_downloadable', 'no');
                update_post_meta($post_id, '_virtual', 'yes');
                update_post_meta($post_id, '_sale_price', $pricing['amount']);
                update_post_meta($post_id, '_regular_price', $pricing['regular_price']);
                update_post_meta($post_id, '_price', $pricing['amount']);
                update_post_meta($post_id, '_purchase_note', '');
                update_post_meta($post_id, '_featured', 'no');
                update_post_meta($post_id, '_weight', '');
                update_post_meta($post_id, '_length', '');
                update_post_meta($post_id, '_width', '');
                update_post_meta($post_id, '_height', '');
                update_post_meta($post_id, '_sku', $asin);
                update_post_meta($post_id, '_product_attributes', array());
                update_post_meta($post_id, '_sale_price_dates_from', '');
                update_post_meta($post_id, '_sale_price_dates_to', '');
                update_post_meta($post_id, '_sold_individually', '');
                update_post_meta($post_id, '_manage_stock', 'no');
                update_post_meta($post_id, '_backorders', 'no');
                update_post_meta($post_id, '_stock', '');
                update_post_meta($post_id, '_wca_amazon_affiliate_asin', $asin);
                update_post_meta( $post_id, '_region', $region );
                update_post_meta( $post_id, '_import_method', '3' );
                update_post_meta( $post_id, '_detail_page_url', $product_url);

                if ( 'Yes' === get_option( 'ams_remote_amazon_images' ) ) {
                    $this->attach_product_thumbnail( $post_id, $image, 0 );
                    foreach( $gallery as $image ) {
                        $this->attach_product_thumbnail( $post_id, $image, 1 );
                    }
                }else {
                    $this->saveExternalImages($post_id,$image,$gallery);
                }

                $massage = sprintf('<div class="alert alert-success mx-3 text-left" role="alert">%s</div>', esc_html__(' Product import Successfully. --- ' . $_POST['product_url'], 'ams-wc-amazon'));
            } else {
                $massage = sprintf('<div class="alert alert-danger mx-3 text-left" role="alert">%s</div>' , esc_html__('Product not imported because product content is empty!', 'ams-wc-amazon'));
            }
        } else {
            $massage = sprintf('<div class="alert alert-danger mx-3 text-left" role="alert">%s</div>' , esc_html__('Something went wrong!', 'ams-wc-amazon'));
        }
        echo wp_kses_post($massage);
        sleep(3);
        wp_die();
    }

}