<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Category
 */


class Category extends CI_Controller
{

    private $CI;

    function __construct()
    {
        $this->CI = & get_instance();

    }

	function main()
	{

		if ( ! $this->CI->input->post_get('token')) {
			$this->CI->apilib->make_error("토큰 값이 넘어오지 않았습니다");
        }
		$token = $this->CI->input->post_get('token');


        $app_id = (int) trim($this->CI->input->post_get('app_id'));
        if (empty($app_id)) {
			$this->CI->apilib->make_error("어플 아이디가 넘어오지 않았습니다");
        }


		$allowed_depth = array('1', '2', '3', '4');

		$q = $this->CI->input->get('q');
		$depth = $this->CI->input->get('depth');
		if ($depth) {
			if ( ! is_numeric($depth)) {
				$this->CI->apilib->make_error('Depth 값이 잘못 넘어왔습니다. 값이 비어있든지, 1,2,3,4 중 하나의 값만 허용됩니다.');
			}
			if ( ! in_array($depth, $allowed_depth)) {
				$this->CI->apilib->make_error('Depth 값이 잘못 넘어왔습니다. 값이 비어있든지, 1,2,3,4 중 하나의 값만 허용됩니다.');
			}
		}
		

		$this->CI->load->model(array('Contents_category_model'));


		if ($q) {
			$this->CI->db->like('cat_name', $q);
		}
		if ($depth) {
			$this->CI->db->where('cat_depth', $depth);
		}
		$this->CI->db->where('app_id', $app_id);
		$this->CI->db->order_by('cat_sort', 'desc');
		$qry = $this->CI->db->get('contents_category');
		$data = $qry->result_array();

		$count = 0;
		$result = array();
		if ($data) {
            foreach ($data as $key => $val) {

				$cinfo = $this->CI->Contents_category_model->get_hierarchical_name($app_id, element('cat_id', $val));
				$result[$key]['cat1id'] = element('1', element('id', $cinfo));
				$result[$key]['cat2id'] = element('2', element('id', $cinfo));
				$result[$key]['cat1code'] = element('1', element('code', $cinfo));
				$result[$key]['cat2code'] = element('2', element('code', $cinfo));
				$result[$key]['cat1name'] = element('1', element('name', $cinfo));
				$result[$key]['cat2name'] = element('2', element('name', $cinfo));
				$count++;
			}
		}
		
		$arr = array(
			'result' => 'ok',
			'token' => $token,
			'app_id' => $app_id,
			'count' => $count,
			'list' => $result,
		);
		return $arr;
	}
}
