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



abstract class AbstractApiView {
    public $path = "isp_example";
    public $api;
    public $extraActions = [];

    public function create_or_get_term_id($name,$taxonomy,$parent_id=0,$slug=null){
        $term = term_exists( $name, $taxonomy ); 
        if(!$slug){
            $slug = "dk_".sanitize_title($name);
        }
        $data = [
            'description' => $name,
            'slug' => $slug,
            'parent' => $parent_id,
        ];
        
        if($term){
            $term = wp_update_term($term['term_id'], $taxonomy ,$data);
        }else{
            $term = wp_insert_term($name, $taxonomy ,$data);
        }
        return $term['term_id'];
    }
    public function get_current_terms($id,$taxonomy, $skip_dk = true){
        if($id){
            $cur_terms = get_the_terms($id, $taxonomy);
            if($cur_terms){
                $ids = [];
                foreach ($cur_terms as $key => $term) {
                    if(!str_contains($term->slug, "dk_")){
                        $ids[] = $term->term_id;
                    }
                    
                }
                return $ids;
            }
        }
        return [];
    }

    function register_actions($loader){
        $loader->add_action("wp_ajax_$this->path-list", $this, 'list');
        $loader->add_action("wp_ajax_$this->path-count", $this, 'count');
        $loader->add_action("wp_ajax_$this->path-get", $this, 'get');
        $loader->add_action("wp_ajax_$this->path-post", $this, 'post');
        $loader->add_action("wp_ajax_$this->path-put", $this, 'put');
        $loader->add_action("wp_ajax_$this->path-delete", $this, 'delete');
        foreach ($this->extraActions as $key => $action) {
            $loader->add_action("wp_ajax_$this->path-$action", $this, "$action");
        }
    }


    function list(){
        $q = $this->api;
        if(isset($_POST['fields'])){
            $q = $q->setJsonApiFields(explode(",",$_POST['fields']));
        }
        if(isset($_POST['page'])){
            $q = $q->setJsonApiPage($_POST['page']);
         }
        $request = $q->getRequestBuilder()->getRequest();
        
        $response = $q->client->sendRequest($request);
        return wp_send_json(json_decode($response->getBody()->__toString()));
      
        
    }
    
    function get(){
        $q = $this->api;
        if(isset($_POST['id'])){
            $q = $q->setJsonApiFields([
				'id'=>$_POST['id']
			]);   
        }
        if(isset($_POST['page'])){
           $q = $q->setJsonApiPage($_POST['page']);
        }
        if(isset($_POST['fields'])){
            $q = $q->setJsonApiFields(explode(",",$_POST['fields']));
        }
        
        $response = $q->client->sendRequest($request);
        return wp_send_json(json_decode($response->getBody()->__toString()));
		//return $r->getBody();
    }
    function post(){

    }
    function put(){

    }
    function delete(){

    }

}   

