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

use Datacake\Core\Admin\ApiViews\AbstractApiView;
use Datacake\Core\Wda\ChannelApi;

class ChannelApiView extends AbstractApiView {
    public $taxonomy = "isp_canais";
    public function __construct( $args = array()) {
        $this->path = "isp_channel_view";
        $this->api = new ChannelApi();
        $this->extraActions = [
            "sync"
        ];
    }
    public function sync(){
        
        $message = [
            "status"=>"error",
            "mensagem" => "starting"
        ];
        $q = $this->api;
        $page = ["number" => 1, "size" => 40];
        if(isset($_POST['page'])){
            $page["number"] = sanitize_key($_POST['page']);
        }
        
        
        $q = $q->setJsonApiPage($page);
        $q = $q->setJsonApiFields([
            'id','name','logo','number','position',
            'is_hd','is_audio','products','types','groups',
        ]);
        $q = $q->setJsonApiInclude([
            'products','types', 'groups'
        ]);
        
        //'product_type',
        //'addons'
        //'options'
        //'categories'
        //'inventory'
        //'tags',
        $response = $q->list();
        
        if($response->isSuccessful()){
            if($response->hasDocument()){
                foreach ($response->document()->primaryResources() as $key => $doc) {
                    
                    
                    $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_logo'=> $doc->attribute("logo"),
                        'isp_number'=> $doc->attribute("number"),
                        'isp_is_hd'=> $doc->attribute("is_hd"),
                        'isp_is_audio'=> $doc->attribute("is_audio"),
                        
                    ];
                    
                    $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('types'),$post_id);
                    $cats = array_merge(
                        $this->get_category_ids($doc->relationship('groups'),$post_id),
                        $this->get_plan_category($doc->relationship('products'),$post_id)
                    );
                    
                    $data = [
                        'post_type' => $this->taxonomy,
                        'post_title' => $doc->attribute('name'),
                        'post_content'=> $doc->attribute('name'),
                        'menu_order' => $doc->attribute('position'),
                        'post_status'=> 'publish',
                        'tax_input'    => array(
                            "isp_canais_tag" => $tags,
                            "isp_canais_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 canais"
                ];    
            }
        }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 canais 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 canais 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){
        
        $ids = $this->get_current_terms($id,'isp_canais_tag');
        
        foreach ($documents->resources() as $key => $doc) {
            $term_id = $this->create_or_get_term_id($doc->attribute('name'),'isp_canais_tag');
            if($term_id){
              $ids[] = $term_id;
            }
        }
        
        return $ids;
    }
    private function get_category_ids($documents,$id){
        $parent_id = $this->create_or_get_term_id( 'Grupos','isp_canais_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_canais_category');
        //$ids = [];
        $ids[] = $parent_id;
        foreach ($documents->resources() as $key => $doc) {
            $term_id = $this->create_or_get_term_id($doc->attribute('name'),'isp_canais_category',$parent_id);
            
            if($term_id){
                $ids[] = $term_id;
            }
        }
        return $ids;
    }
    
    
    private function get_plan_category($plans,$id){
        $parent_id = $this->create_or_get_term_id( 'Planos','isp_canais_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_canais_category');
        //$ids = [];
        $ids[] = $parent_id;
        foreach ($plans->resources() as $key => $doc) {
            $term_id = $this->create_or_get_term_id($doc->attribute('name'),'isp_canais_category',$parent_id,"dk_".$doc->attribute('sku'));
            if($term_id){
                $ids[] = $term_id;
            }
        }
        return $ids;
    }

}   

