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

class Group extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */

    function __construct() {
        parent::__construct();
        $this->load->model("Group_model", "group");
    }
	public function index()
	{
        $groups = $this->group->get_groups();
        $res['view'] = 'pages/group';
        $res['data'] = array('groups' => $groups["data"]);
		$this->load->view('layout', $res);
    }
    
    public function get_groups(){
        $res = $this->group->get_groups();
        header("Content-Type: application/json");
        echo json_encode($res["data"]);
    }

    public function add_group(){
        $name = $this->input->post("group_name");
        $row = array("parent_id"=>0, "group_name" => $name);
        $result = $this->group->insert($row);
        $row["id"] = $result;
        header("Content-Type: application/json");
        echo json_encode($row);
    }

    public function update_group(){
        $name = $this->input->post("group_name");
        $id = $this->input->post("id");
        $row = array("id"=>$id, "group_name" => $name, "parent_id" => 0);
        $this->group->update($row);
        header("Content-Type: application/json");
        echo json_encode($row);
    }

    public function delete_group(){
        $id = $this->input->post("id");
        $result = $this->group->delete($id);
        echo json_encode(TRUE);
    }

    public function get_subgroups($parent_id){
        $res = $this->group->get_subgroups($parent_id);
        header("Content-Type: application/json");
        echo json_encode($res["data"]);
    }

    public function add_subgroup($parent_id){
        $name = $this->input->post("group_name");
        $row = array("parent_id"=>$parent_id, "group_name" => $name);
        $result = $this->group->insert($row);
        $row["id"] = $result;
        header("Content-Type: application/json");
        echo json_encode($row);
    }

    public function update_subgroup($parent_id){
        $name = $this->input->post("group_name");
        $id = $this->input->post("id");
        $row = array("id"=>$id, "group_name" => $name, "parent_id" => $parent_id);
        $this->group->update($row);
        header("Content-Type: application/json");
        echo json_encode($row);
    }

    public function delete_subgroup($parent_id){
        $id = $this->input->post("id");
        $result = $this->group->delete($id);
        echo json_encode(TRUE);
    }
}
