<?php
namespace Datacake\Core\Admin\ApiViews;

use Datacake\Core\Admin\ApiViews\AbstractApiView;
use Datacake\Core\Wda\ProductApi;
use Datacake\Core\ORM\WP\Post;

class ProductApiView extends AbstractApiView {
    public $taxonomy = "isp_planos";
    public function __construct( $args = array()) {
        $this->path = "isp_product_view";
        $this->api = new ProductApi();
        $this->extraActions = [
            "sync"
        ];
        
    }
    public function sync(){
        
        $message = [
            "status"=>"error",
            "mensagem" => "starting"
        ];
        $q = $this->api;
        $page = ["number" => 1, "size" => 15];
        if(isset($_POST['page'])){
            $page["number"] = sanitize_key($_POST['page']);
        }
        
        
        $q = $q->setJsonApiPage($page);
        $q = $q->setJsonApiFields([
            'product_class', 'is_active', 'sku', 'visibility', 'name', 'pricing_list',
            'pricing_sale', 'description', 'position', 'track_inventory', 'data', 'quantity', 'shippable',
            'weight', 'shipping_width', 'shipping_height', 'shipping_depth', 'quantity_allocated', 'cost',
            'internal_product_code',  'images', 'disabled', 'price', 'kilogram_price', 'base_price', 
            'exclusive_pricing_sale', 'is_in_promotion', 'is_in_exclusive_promotion', 'option_required',
            'min_stock', 'variable_weight', 'unit_type', 'hide_customer_notes',
            'restricted_customers', 'tags','categories', 'product_type'
        ]);
        $q = $q->setJsonApiInclude([
            'tags','categories', 'product_type'
        ]);
        
        //'product_type',
        //'addons'
        //'options'
        //'categories'
        //'inventory'
        //'tags',
        $response = $q->list();
        
        if($response->isSuccessful()){
            if($response->hasDocument()){
                foreach ($response->document()->primaryResources() as $key => $doc) {
                    $prodct_type = $doc->relationship('product_type')->resource();
                    
                    $posts = query_posts( 
                        array(
                            'post_per_page' => 1,
                            'post_type' => $this->taxonomy,
                            'meta_query' => array(
                            array(
                              'key' => 'isp_remote_id',
                              'value' => $doc->id(),
                            )
                          ),
                        ) 
                    );
                    $post = null;
                    
                    if($posts && count($posts) >= 1 ){
                        $post = $posts[0];
                    }
                    
                    
                    $meta = [
                        'isp_remote_id' => $doc->id(),
                        'isp_product_type_id' => $prodct_type->id(),
                        'isp_product_type' => $prodct_type->attribute('name'),
                        'isp_product_class' => $doc->attribute('product_class'), 
                        'isp_is_active' => $doc->attribute('is_active'), 
                        'isp_sku' => $doc->attribute('sku'), 
                        'isp_visibility' => $doc->attribute('visibility'), 
                        'isp_name' => $doc->attribute('name'), 
                        'isp_pricing_list' => $doc->attribute('pricing_list'),
                        'isp_pricing_sale' => $doc->attribute('pricing_sale'), 
                        'isp_track_inventory' => $doc->attribute('track_inventory'),
                        'isp_quantity' => $doc->attribute('quantity'), 
                        'isp_shippable' => $doc->attribute('shippable'),
                        'isp_weight' => $doc->attribute('weight'),
                        'isp_shipping_width' => $doc->attribute('shipping_width'),
                        'isp_shipping_height' => $doc->attribute('shipping_height'),
                        'isp_shipping_depth' => $doc->attribute('shipping_depth'),
                        'isp_quantity_allocated' => $doc->attribute('quantity_allocated'),
                        'isp_cost' => $doc->attribute('cost'),
                        'isp_internal_product_code' => $doc->attribute('internal_product_code'),
                        'isp_images' => $doc->attribute('images'),
                        'isp_disabled' => $doc->attribute('disabled'),
                        'isp_price' => $doc->attribute('price'),
                        'isp_kilogram_price' => $doc->attribute('kilogram_price'),
                        'isp_base_price' => $doc->attribute('base_price'), 
                        'isp_exclusive_pricing_sale' => $doc->attribute('exclusive_pricing_sale'),
                        'isp_is_in_promotion' => $doc->attribute('is_in_promotion'),
                        'isp_is_in_exclusive_promotion' => $doc->attribute('is_in_exclusive_promotion'),
                        'isp_option_required' => $doc->attribute('option_required'),
                        'isp_min_stock' => $doc->attribute('min_stock'),
                        'isp_variable_weight' => $doc->attribute('variable_weight'),
                        'isp_unit_type' => $doc->attribute('unit_type'),
                        'isp_hide_customer_notes' => $doc->attribute('hide_customer_notes'),
                        'isp_restricted_customers' => $doc->attribute('restricted_customers'),
                    ];
                    
                    $data = $doc->attribute('data');
                    if($data){
                        foreach ($data as $key => $value) {
                            $meta['isp_data_'.$key] = $value;
                        }
                    }
                    $post_id = $post ? $post->ID : null;
                    $tags = $this->get_terms_tags_ids($doc->relationship('tags'),$post_id);
                    $cats = $this->get_category_ids($doc->relationship('categories'),$post_id);
                    /*

                    $cats = array_merge(
                        $this->get_category_ids($doc->relationship('categories'),$post_id),
                        $this->get_cidade_category($doc->relationship('products'),$post_id)
                    );
                    */

                    $data = [
                        'post_type' => $this->taxonomy,
                        'post_title' => $doc->attribute('name'),
                        'post_content'=> $doc->attribute('description'),
                        'menu_order' => $doc->attribute('position'),
                        'post_status'=> 'publish',
                        'tax_input'    => array(
                            "isp_planos_tag" => $tags,
                            "isp_planos_category" => $cats,
                        ),
                        'tags_input' => $tags, //(array) Array of tag names, slugs, or IDs. Default empty.
                        'meta_input' => $meta //(array) Array of post meta values keyed by their post meta key. Default empty.
                    ];
                    if($post){
                        $data['ID'] = $post->ID;
                        wp_update_post($data);
                       
                    }else{
                        wp_insert_post($data);
                    }
             
                  }
            }else{
                $message = [
                    "status"=>"success",
                    "mensagem" => "Sem produtos"
                ];    
            }
        }else{
            // TODO GET ERROR FROM API
            $message = [
                "status"=>"error",
                "mensagem" => "Error from API"
            ];
        }
        $meta = $response->document()->meta();
        if($meta['pagination']['page'] < $meta['pagination']['pages']){
            $message = [
                "status"=>"success",
                "mensagem" => "Sincronização de produtos pagina:".$meta['pagination']['page']." de ".$meta['pagination']['pages']." concluida",
                "next_page" => $meta['pagination']['page'] + 1,
                "pagination" => $meta['pagination']
            ];
        } else {
            $message = [
                "status"=>"success",
                "mensagem" => "Sincronização de produtos concluida",
                "next_page" => null
            ];
        }

        if($message['status'] == "error"){
            return wp_send_json_error($message);
        }
        return wp_send_json_success($message);
        
    }
    
    private function get_terms_tags_ids($documents,$id){
        // Não adianta pegar as tags e categorias que estão no produto por que se não na hora que uma tag for removido do wda não vai ser removida daqui
        $ids = $this->get_current_terms($id,'isp_planos_tag');
        //$ids = [];
        foreach ($documents->resources() as $key => $doc) {
            $term = term_exists( $doc->attribute('value'), 'isp_planos_tag' ); 
            if($term){
                $ids[] = $doc->attribute('value');
            }
        }
        
        return $ids;
    }


    

    private function get_category_ids($documents,$id){
        $parent_id = $this->create_or_get_term_id( 'Categorias','isp_planos_category'); 
        // Não adianta pegar as tags e categorias que estão no produto por que se não na hora que uma tag for removido do wda não vai ser removida daqui
        $ids = $this->get_current_terms($id,'isp_planos_category');
        //$ids = [];
        $ids[] = $parent_id;
        foreach ($documents->resources() as $key => $doc) {
            $term_id = $this->create_or_get_term_id( $doc->attribute('name'), 'isp_planos_category' ,$parent_id); 
            if($term_id){
                $ids[] = $term_id;
            }
        }
        return $ids;
    }
    private function get_cidade_category($cities,$id){
        $parent_id = $this->create_or_get_term_id( 'Cidades','isp_planos_category'); 
        // Não adianta pegar as tags e categorias que estão no produto por que se não na hora que uma tag for removido do wda não vai ser removida daqui
        $ids = $this->get_current_terms($id,'isp_planos_category');
        //$ids = [];
        $ids[] = $parent_id;
        foreach ($plans->resources() as $key => $doc) {
            $term_id = $this->create_or_get_term_id( $doc->attribute('name'), 'isp_planos_category' ,$parent_id); 
            if($term_id){
                $ids[] = $term_id;
            }
        }
        return $ids;
    }

    

}   

