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

use Datacake\Core\Admin\ApiViews\AbstractApiView;
use Datacake\Core\Wda\CityApi;
use Datacake\Core\Models\IspCity;

class CityApiView extends AbstractApiView {
    public function __construct( $args = array()) {
        $this->path = "isp_city_view";
        $this->api = new CityApi();
        $this->extraActions = [
            "sync"
        ];
        $this->cityApi = new CityApi();
    }
    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([
            'created','updated','name','short_name',
				'id','code','lat','long',
				'redirect_url','is_neighborhood','neighborhood_name','products','products.id'
        ]);
        $q = $q->setJsonApiInclude([
            'products'
        ]);
        
        //'product_type',
        //'addons'
        //'options'
        //'categories'
        //'inventory'
        //'tags',
        try {
            $response = $q->list();
        } catch (\Throwable $e) {
            $message = ["status" => "error", "mensagem" => "Erro de conexao com a API: " . $e->getMessage()];
            return wp_send_json_error($message);
        }

        if($response->isSuccessful()){
            if($response->hasDocument()){

                foreach ($response->document()->primaryResources() as $key => $doc) {
                    $entity = IspCity::where('remote_id',$doc->id())->first();

                    $data = [
                        'name'=>$doc->attribute('name'),
                        'short_name'=>$doc->attribute('short_name'),
                        'code'=>$doc->attribute('code')?$doc->attribute('code'):$doc->attribute('name'),
                        'lat'=>$doc->attribute('lat'),
                        'long'=>$doc->attribute('long'),
                        'remote_id'=>$doc->id(),
                        'redirect_url'=>$doc->attribute('redirect_url'),
                        'is_neighborhood'=>$doc->attribute('is_neighborhood'),
                        'neighborhood_name'=>$doc->attribute('neighborhood_name'),
                    ];
                    if($entity){
                        $entity->update($data);
                    }else{
                        $entity = new IspCity();
                        $entity->create($data);
                    }
                    $this->addCityCategoryToProducts($doc->relationship('products'),$doc);
                }

                $meta = $response->document()->meta();
                if(isset($meta['pagination']['page']) && isset($meta['pagination']['pages'])){
                    if($meta['pagination']['page'] < $meta['pagination']['pages']){
                        $message = [
                            "status"=>"success",
                            "mensagem" => "Sincronização de cidades 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 cidades concluida",
                            "next_page" => null
                        ];
                    }
                } else {
                    $message = [
                        "status"=>"success",
                        "mensagem" => "Sincronização de cidades concluida",
                        "next_page" => null
                    ];
                }

            }else{
                $message = [
                    "status"=>"success",
                    "mensagem" => "Sem Cidades"
                ];
            }
        }else{
            $message = [
                "status"=>"error",
                "mensagem" => "Error from API"
            ];
        }

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

    function getPost($id){
        $posts = query_posts( 
            array(
                'post_per_page' => 1,
                'post_type' => "isp_planos",
                'meta_query' => array(
                array(
                  'key' => 'isp_remote_id',
                  'value' => $id,
                )
              ),
            ) 
        );
        $post = null;
        
        if($posts && count($posts) >= 1 ){
            $post = $posts[0];
        }
        return $post;
    }

    function addCityCategoryToProducts($documents,$city){
        $parent_id = $this->create_or_get_term_id( 'Cidades','isp_planos_category');
        foreach ($documents->resources() as $key => $doc) {
            $post = $this->getPost($doc->id());
            $ids = $this->get_current_terms($post->ID,'isp_planos_category');
            $ids[] = $parent_id;
            $term_id = $this->create_or_get_term_id( $city->attribute('name'), 'isp_planos_category' ,$parent_id); 
            $ids[] = $term_id;
            wp_set_object_terms($post->ID,$ids,'isp_planos_category',true);
            
            
        }
        
    }
}   

