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

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

class ProductCategoryApiView extends AbstractApiView {
    public $taxonomy = "isp_planos_category";
    public function __construct( $args = array()) {
        $this->path = "isp_product_category_view";
        $this->api = new ProductCategoryApi();
        $this->extraActions = [
            "sync"
        ];
    }
    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','slug','name','description',
            'parent_id','code','is_displayable',
            'position','background_image_url','banner_url','icon_url'
        ]);
        
        
        $response = $q->list();
        
        if($response->isSuccessful()){
            if($response->hasDocument()){
                $parent_id = $this->create_or_get_term_id( 'Categorias',$this->taxonomy); 
                foreach ($response->document()->primaryResources() as $key => $doc) {
                    $term_id = $this->create_or_get_term_id( $doc->attribute('name'),$this->taxonomy,$parent_id );
                    update_term_meta( $term_id, 'wda_remote_id', $doc->id() );
              	}
			}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 categorias 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 categorias concluida",
                "next_page" => null
            ];
        }

        if($message['status'] == "error"){
            return wp_send_json_error($message);
        }
        return wp_send_json_success($message);
		
    }
}   

