<?php
$loader = $this->registry->get('load');
$loader->controller('api/controllerapi');

class ControllerApiCategory extends ControllerApi{

  private function getparent($categoryid){
    $level_2_data = array();
    $categories_2 = $this->model_catalog_category->getCategories($categoryid);

    foreach ($categories_2 as $category_2) {
      $level_2_data[] = array(
        'name'     => $category_2['name'],
        'href'     => str_replace('&amp;', '&', $this->url->link('product/category', 'path=' . $categoryid . '_' . $category_2['category_id']))
      );
    }
    return $level_2_data;
  }

   public function categoryall(){
      parent::validaAutenticacao();

      if(parent::haserror()){
         $retorno = parent::geterror();
      }else{
        $this->load->model('catalog/category');

        $retorno      = array();
        $categories_1 = $this->model_catalog_category->getCategories(0);

    		foreach ($categories_1 as $category_1) {

          $children_data = array();
          $children = $this->model_catalog_category->getCategories($category_1['category_id']);
      
          foreach ($children as $child) {

            $subchildren_data = array();
            $subchildren = $this->model_catalog_category->getCategories($child['category_id']);
            
            foreach ($subchildren as $subchild) {    
              $subchildren_data[] = array(
                'category_id' => $subchild['category_id'],
                'name'        => $subchild['name'],
                'href'        => str_replace('&amp;', '&', $this->url->link('product/category', 'path='.$child['category_id'].'_'.$subchild['category_id']))
              );
    
            }

            $children_data[] = array(
              'category_id' => $child['category_id'],
              'name'        => html_entity_decode($child['name'], ENT_QUOTES, 'UTF-8'),
              'children'    => $subchildren_data,
              'href'        => str_replace('&amp;', '&', $this->url->link('product/category', 'path='.$category_1['category_id'].'_'.$child['category_id']))
            );            
            
          }

    			$retorno[] = array(
    				'name'     => $category_1['name'],
    				'children' => $children_data,
    				'href'     => str_replace('&amp;', '&', $this->url->link('product/category', 'path=' . $category_1['category_id']))
    			);
    		}
      }

      $this->response->setOutputJson($retorno);
   }

   public function subcategorys(){
     parent::validaAutenticacao();
     parent::validFieldValue(Type_requisicao::Tp_reqGet, 'category_id');

     if(parent::haserror()){
        $retorno = parent::geterror();
     }else{
       $this->load->model('catalog/category');
       $parent  = $this->request->get['category_id'];
       $retorno = $this->getparent($parent);
     }

     $this->response->setOutputJson($retorno);
   }

}
