<?php
namespace Amazon\Affiliate\Admin;
/**
 * Admin setting page and setting handler
 *
 * @package Amazon\Affiliate\Admin
 */
class Setting {
    /**
     * Setting page load
     */
    public function setting_page() {
        $template = __DIR__ . '/views/settings.php';
        if ( file_exists( $template ) ) {
            require_once $template;
        }
        // $template = __DIR__ . '/views/setting-amazon-cron.php';
        // if ( file_exists( $template ) ) {
        //     require_once $template;
        // }
        // $action = '';
        // if ( isset( $_GET['action'] ) ) {
        //     $action = $_GET['action'];
        // }
        // switch ( $action ) {
        //     case 'affiliates':
        //         $template = __DIR__ . '/views/setting-affiliate.php';
        //         if ( file_exists( $template ) ) {
        //             require_once $template;
        //         }
        //         break;
        //     case 'product_avail':
        //         $template = __DIR__ . '/views/setting-amazon-cron.php';
        //         if ( file_exists( $template ) ) {
        //             require_once $template;
        //         }
        //      break;
        //     default:
        //         $template = __DIR__ . '/views/setting-general.php';
        //         if ( file_exists( $template ) ) {
        //             require_once $template;
        //         }
        // }
    }
    // public function general_ams_product_cron(){
    // }
    /**
     * Amazon setting form handler
     */
    public function general_amazon_setting_handler() {
        check_admin_referer( 'general_amazon_setting_nonce' );
        $access_key_id     = sanitize_text_field( $_POST['access_key_id'] );
        $secret_access_key = sanitize_text_field( $_POST['secret_access_key'] );
        $associate_tag     = sanitize_text_field( $_POST['ams_associate_tag'] );
        $country           = sanitize_text_field( $_POST['ams_amazon_country'] );

        $woocommerce_currency  = sanitize_text_field( $_POST['woocommerce_currency'] );
        update_option( 'woocommerce_currency', $woocommerce_currency );
        
        update_option( 'ams_access_key_id', $access_key_id );
        update_option( 'ams_secret_access_key', $secret_access_key );
        update_option( 'ams_associate_tag', $associate_tag );
        update_option( 'ams_amazon_country', $country );
        // wp_redirect( 'admin.php?page=wc-product-setting-page&action=affiliates' );

        wp_redirect( 'admin.php?page=wc-product-setting-page&action=affiliates&tab='.$_POST['action_tab'] );
    }
    public function product_cat_country_setting(){
         $country  = sanitize_text_field( $_POST['ams_amazon_country'] );
         update_option( 'ams_amazon_country', $country );
         $ams_default_category        = sanitize_text_field( $_POST['ams_default_category'] );
         update_option( 'ams_default_category', $ams_default_category );
         $woocommerce_currency        = sanitize_text_field( $_POST['woocommerce_currency'] );
         update_option( 'woocommerce_currency', $woocommerce_currency );
         $page_redirect = sanitize_text_field($_POST['page_redirect']);
         wp_safe_redirect(
            esc_url(
                // Retrieves the site url for the current site.
                //https://test.affiliateproamazon.com/wp-admin/admin.php?page=products-search-without-api
                site_url( '/wp-admin/admin.php?page='.$page_redirect )
                )
         );
        exit();
         // wp_redirect( 'admin.php?page=wc-product-setting-page' );
          wp_redirect( ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
         // return true;
    }
    public function general_ams_product_cron(){
        update_option( 'product_price_cron', $_POST['product_price_cron'] );
        update_option( 'product_sku_cron', $_POST['product_sku_cron'] );
        update_option( 'product_variants_cron', $_POST['product_variants_cron'] );
        update_option( 'product_tags_cron', $_POST['product_tags_cron'] );
        update_option( 'product_out_of_stock_cron', $_POST['product_out_of_stock_cron'] );
        update_option( 'product_description_cron', $_POST['product_description_cron'] );
        update_option( 'product_image_cron', $_POST['product_image_cron'] );
        update_option( 'product_category_cron', $_POST['product_category_cron'] );
        wp_redirect( 'admin.php?page=wc-product-setting-page&action=product_avail&tab='.$_POST['action_tab'] );
        die();
        $product_tags_cron =  get_option('product_tags_cron');
        $product_variants_cron =  get_option('product_variants_cron');
        $product_sku_cron = get_option('product_sku_cron');
        $product_price_cron =  get_option('product_price_cron');
        $product_category_cron =  get_option('product_category_cron');
        $product_out_of_stock_cron = get_option('product_out_of_stock_cron');
        $product_description_cron = get_option('product_description_cron');
        if ( ! class_exists( 'simple_html_dom' ) ) {
            require_once __DIR__ . '/lib/simplehtmldom/simple_html_dom.php';
        }
        $asins = ams_get_all_products_info();
        // echo "<pre>";print_r($asins);die;
        $id_asin = array_combine( $asins['id'], $asins['asin'] );
        foreach ( $id_asin as $id => $asin ) {
                // $asin = 'B07X4YF5S6';
                // $id = 5322;
            // echo $asin;die;
            $url = sprintf( 'https://www.amazon.%s/dp/%s', get_option( 'ams_amazon_country' ), $asin );
            sleep( rand( 1, 5 ) );
            $product_import = new \Amazon\Affiliate\Admin\ProductsSearchWithoutApi();
            $user_agent = $product_import->user_agent();
            $options = array(
                'http' => array(
                    'method' => "GET",
                    'header' => "Accept-language: en\r\n" .
                        $user_agent
                )
            );
            $context = stream_context_create( $options );
            $response_body = file_get_contents( esc_url_raw( $url ), false, $context );
            $html = new \simple_html_dom();
            $html->load( $response_body );
            $product_status = 'instock';
            if ( $html->find( '#outOfStock .a-color-price', 0 ) ) {
                $product_status = 'outofstock';
            }
            $newBuyBoxPrice =  $html->find('#newBuyBoxPrice');
            $price = $html->find('#price');
            $priceblock_ourprice = $html->find('#priceblock_ourprice');
            $priceblock_dealprice = $html->find('#priceblock_dealprice');
            $priceblock_saleprice = $html->find('#priceblock_saleprice');
            if ( isset( $newBuyBoxPrice[0] )){
                $amount = $newBuyBoxPrice[0]->innertext;
            } 
            if ( isset( $price[0] )){
                $amount = $price[0]->innertext;
            } 
            if ( isset( $priceblock_ourprice[0] ) ) {
               $amount = $priceblock_ourprice[0]->innertext;
            } 
            if ( isset( $priceblock_saleprice[0] ) ) {
               $amount = $priceblock_saleprice[0]->innertext;
            }
            if ( isset( $priceblock_dealprice[0] ) ) {
               $amount = $priceblock_dealprice[0]->innertext;
            }
            $amount = preg_replace("/[^0-9 .]/", "", $amount );
        $amount = str_replace( ',', '.', $amount );
        $amount = strtok( $amount, ' ' );
        if($product_sku_cron){
            update_post_meta($id, '_sku', $asin );
        }
        if($product_out_of_stock_cron){
            update_post_meta( $id, '_stock_status', $product_status );
        }
        if($product_price_cron){
            update_post_meta( $id, '_price', $amount );
            update_post_meta( $id, '_regular_price', $amount );
            update_post_meta( $id, '_sale_price', $amount);
        }
        // if($product_description_cron){
        //     $post = get_post( $id );
        //     $post->post_content = "Some other content";
        //     wp_update_post( $post );
        // }
        if($product_variants_cron){
            global $wpdb;           
            $product = wc_get_product($id);
            $children_ids = $product->get_children();
            $meta_prefix = $wpdb->prefix . 'options';    
            $query =  "DELETE FROM $meta_prefix
                WHERE (option_name LIKE '_transient_wc_var_prices_".$id."'
                OR option_name LIKE '_transient_timeout_wc_var_prices_".$id."')";
            $wpdb->query( $query);
            if(isset($children_ids) && !empty($children_ids)){
                foreach ($children_ids as $key => $children_id) {
                    update_post_meta( $children_id, '_price', sanitize_text_field($amount) );
                    update_post_meta( $children_id, '_sale_price', $amount);
                }
            }
        }
        wc_delete_product_transients($id);
    }
}
    /**
     * General setting form handler
     */
    public function general_setting() {
        check_admin_referer( 'general_setting_nonce' );
        $product_per_page            = sanitize_text_field( $_POST['product_per_page'] );
        $buy_now_label               = sanitize_text_field ($_POST['buy_now_label'] );
        $buy_action_btn              = sanitize_text_field( $_POST['buy_action_btn'] );
        $enable_no_follow_link       = sanitize_text_field( $_POST['enable_no_follow_link'] );
        $ams_default_category        = sanitize_text_field( $_POST['ams_default_category'] );
        $checkout_mass_redirected    = sanitize_text_field( $_POST['checkout_mass_redirected'] );
        $checkout_redirected_seconds = sanitize_text_field( $_POST['checkout_redirected_seconds'] );
        $remote_amazon_images        = sanitize_text_field( $_POST['remote_amazon_images'] );
        $product_thumbnail_size      = sanitize_text_field( $_POST['product_thumbnail_size'] );
        $percentage_profit      = sanitize_text_field( $_POST['percentage_profit'] );
        update_option( 'ams_product_per_page', $product_per_page );
        update_option( 'ams_buy_now_label', $buy_now_label );
        update_option( 'ams_buy_action_btn', $buy_action_btn );
        update_option( 'ams_enable_no_follow_link', $enable_no_follow_link );
        update_option( 'ams_default_category', $ams_default_category );
        update_option( 'ams_checkout_mass_redirected', $checkout_mass_redirected );
        update_option( 'ams_checkout_redirected_seconds', $checkout_redirected_seconds );
        update_option( 'ams_remote_amazon_images', $remote_amazon_images );
        update_option( 'ams_product_thumbnail_size', $product_thumbnail_size );
        update_option( 'ams_percentage_profit', $percentage_profit );
        // wp_redirect( 'admin.php?page=wc-product-setting-page' );

        wp_redirect( 'admin.php?page=wc-product-setting-page&tab='.$_POST['action_tab'] );


    }
    /**
     * Get option
     *
     * @param $name
     * @return string|void
     */
    public function get_option( $name ) {
        $option =  get_option( $name );
        return  $option;
    }
    /**
     * Get WooCommerce categories list
     *
     * @return array
     */
    function get_wc_terms() {
        $categories = get_terms( array(
            'hide_empty' => false,
        ) );
        $cat = array();
        foreach ( $categories as $row ) {
            if ( 'product_cat' === $row->taxonomy ) {
                $cat[] = array(
                    'term_id'  => $row->term_id,
                    'name'  => $row->name,
                );
            }
        }
        return array_reverse( $cat );
    }
    /**
     * Amazon api test
     *
     * @return bool
     */
    public function test_api() {
        $keyword = array( 'puppy poster','kitten poster','disney movies','Game of Thrones','kids' );
        $keyword_index = rand( 0, 5 );
        $keyword_key = $keyword[ $keyword_index ];
        $ams_product_per_page   = get_option( 'ams_product_per_page' );
        $locale      = get_option( 'ams_amazon_country' );
        $regions     = ams_get_amazon_regions();
        $marketplace = 'www.amazon.'. get_option( 'ams_amazon_country' );
        $serviceName = 'ProductAdvertisingAPI';
        $region      = $regions[ $locale ]['RegionCode'];
        $accessKey   = get_option( 'ams_access_key_id' );
        $secretKey   = get_option( 'ams_secret_access_key' );
        $payloadArr = array();
        $payloadArr['Keywords']    = $keyword_key;
        $payloadArr['Resources']   = array( 'CustomerReviews.Count', 'CustomerReviews.StarRating', 'Images.Primary.Small', 'Images.Primary.Medium', 'Images.Primary.Large', 'Images.Variants.Small', 'Images.Variants.Medium', 'Images.Variants.Large', 'ItemInfo.ByLineInfo', 'ItemInfo.ContentInfo', 'ItemInfo.ContentRating', 'ItemInfo.Classifications', 'ItemInfo.ExternalIds', 'ItemInfo.Features', 'ItemInfo.ManufactureInfo', 'ItemInfo.ProductInfo', 'ItemInfo.TechnicalInfo', 'ItemInfo.Title', 'ItemInfo.TradeInInfo', 'Offers.Listings.Availability.MaxOrderQuantity', 'Offers.Listings.Availability.Message', 'Offers.Listings.Availability.MinOrderQuantity', 'Offers.Listings.Availability.Type', 'Offers.Listings.Condition', 'Offers.Listings.Condition.SubCondition', 'Offers.Listings.DeliveryInfo.IsAmazonFulfilled', 'Offers.Listings.DeliveryInfo.IsFreeShippingEligible', 'Offers.Listings.DeliveryInfo.IsPrimeEligible', 'Offers.Listings.DeliveryInfo.ShippingCharges', 'Offers.Listings.IsBuyBoxWinner', 'Offers.Listings.LoyaltyPoints.Points', 'Offers.Listings.MerchantInfo', 'Offers.Listings.Price', 'Offers.Listings.ProgramEligibility.IsPrimeExclusive', 'Offers.Listings.ProgramEligibility.IsPrimePantry', 'Offers.Listings.Promotions', 'Offers.Listings.SavingBasis', 'Offers.Summaries.HighestPrice', 'Offers.Summaries.LowestPrice', 'Offers.Summaries.OfferCount', 'ParentASIN','SearchRefinements' );
        $payloadArr["ItemCount"]   = (int) $ams_product_per_page;
        $payloadArr["ItemPage"]    = 1;
        $payloadArr["SortBy"]      = 'Relevance';
        $payloadArr["SearchIndex"] = 'All';
        $payloadArr['PartnerTag']  = get_option( 'ams_associate_tag' );
        $payloadArr['PartnerType'] = 'Associates';
        $payloadArr['Marketplace'] = $marketplace;
        $payload                   = json_encode( $payloadArr );
        $host                      = $regions[ $locale ]['Host'];
        $uri_path                   = "/paapi5/searchitems";
        $api      = new  \Amazon\Affiliate\Api\Amazon_Product_Api( $accessKey, $secretKey, $region, $serviceName, $uri_path, $payload, $host, 'SearchItems' );
        $response = $api->do_request();
        if ( isset( $response->Errors ) ) {
            $massage = sprintf( '<div class="alert alert-danger mx-0 text-left" role="alert">%s</div>', wp_json_encode( $response ) );
        } elseif ( isset( $response->SearchResult ) ) {
            $massage = sprintf( '<div class="alert alert-success mx-0 text-left" role="alert">%s</div>', esc_html__( 'Your api connected successfully', 'ams-wc-amazon' ) );
        } else {
            $massage = sprintf( '<div class="alert alert-warning mx-0 text-left" role="alert">%s</div>', esc_html__( 'Api Connection problem', 'ams-wc-amazon' ) );
        }
        echo wp_kses_post( $massage );
        wp_die();
    }
}