<?php

class MY_Controller extends CI_Controller
{
    protected $adminViewFolder = 'adm/';
    protected $categories;
    protected $request;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        if (strpos($this->uri->segment(1), 'adm') !== false && $this->session->userdata('Adm_Id') == '') {
            header('location: /admin');
            exit(3);
        }
        $this->categories = $this->config->item('categories');
        $this->load->model('category_model');
    }

    public function getRequest($contentType = 'json')
    {
        if (!$this->request) {
            $this->request = new stdClass;
            if ($contentType == 'json') {
                $this->request->body = json_decode(file_get_contents("php://input"), true);
            }
            parse_str($this->input->server('QUERY_STRING', null, ''), $this->request->param);   
            if(!$this->param('limit')) $this->request->param['limit'] = 30;
            if(!$this->param('order')) $this->request->param['order'] = 'desc';
        }
        return $this->request;
    }

    public function param($key = null)
    {
        return $key ? (empty($this->getRequest()->body[$key]) ? (empty($this->request->param[$key]) ? null : $this->request->param[$key]) : $this->getRequest()->body[$key]) : $this->getRequest()->body;
    }

    public function response($data = null, $code = 200, $message = 'Success', $contentType = 'application/json')
    {
        $data = array('code' => $code, 'message' => $message, 'data' => $data);
        if ($contentType == 'application/json') {
            $this->output
                ->set_content_type($contentType)
                ->set_output(json_encode($data));
        }
    }

    public function getSubCategoryId($parentCategoryName = 'grace-category')
    {
        $subCategoryId = $this->category_model->getSubCategoryId($parentCategoryName);
        return array_merge(array_values($this->categories[explode('-', $parentCategoryName)[0]]), $subCategoryId['subcategories']);
    }
}
