<?php

class Priviledge extends MY_Controller
{
   var $db_onedev;
   public function index()
   {
      echo "USERGROUP PRIVILEDGE API";
   }
   public function __construct()
   {
      parent::__construct();
      $this->db_onedev = $this->load->database("onedev", true);
   }

   public function lookupusergroup()
   {
      try {
         //# cek token valid
         if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
         }

         $prm = $this->sys_input;
         $search = $prm['search'];
         $all = $prm['all'];
         $limit = '';
         if ($all == 'N') {
            $limit = ' LIMIT 10';
         }
         $sql = "select COUNT(*) as total
            from m_usergroup
            where
            M_UserGroupIsActive = 'Y'";
         $sql_param = array($search);
         $total = $this->db_onedev->query($sql, $sql_param)->row()->total;


         $sql = "select M_UserGroupID as id, M_UserGroupDashboard as dashboard, M_UserGroupName as name,  M_UserGroupIsClinic as clinic,   M_UserGroupName as description , 'xxx' as usergrouptype
            from m_usergroup
            where
            M_UserGroupName LIKE CONCAT('%','{$search}','%')  AND
            M_UserGroupIsActive = 'Y' $limit";
         $sql_param = array($search);
         $query = $this->db_onedev->query($sql);
         //echo $this->db_onedev->last_query();
         if ($query) {
            $rows = $query->result_array();
         } else {
            $this->sys_error_db("m_usergroup select");
            exit;
         }


         $result = array("total" => $total, "total_filter" => count($rows), "records" => $rows);
         $this->sys_ok($result);
      } catch (Exception $exc) {
         $message = $exc->getMessage();
         $this->sys_error($message);
      }
   }

   public function lookuppriviledge()
   {
      try {
         //# cek token valid
         if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
         }

         $prm = $this->sys_input;

         $sql = "SELECT S_MenuID as id, S_MenuUrl, S_MenuName as name, '' as childs FROM s_menu WHERE S_MenuParentS_MenuID = 0 AND S_MenuIsActive = 'Y' ORDER BY S_MenuOrder ASC";
         $query = $this->db_onedev->query($sql);
         //echo $this->db_onedev->last_query();
         if ($query) {
            $rows = $query->result_array();
            if ($prm['code'] == 'R') {
               foreach ($rows as $k => $v) {
                  if ($v['S_MenuUrl'] == '#') {
                     $sql = "	SELECT S_MenuID as id, S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
                        FROM s_menu 
                        LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
                        WHERE
                        S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$v['id']}'
                        ORDER BY S_MenuOrder ASC";
                     $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array();
                     if ($rows[$k]['childs']) {
                        foreach ($rows[$k]['childs'] as $kx => $vx) {
                           if ($vx['S_MenuUrl'] == '#') {
                              $sql = "	SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
                                 FROM s_menu 
                                 LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
                                 WHERE
                                 S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$vx['id']}'
                                 ORDER BY S_MenuOrder ASC";
                              $rows[$k]['childs'][$kx]['childs'] = $this->db_onedev->query($sql)->result_array();
                           }
                        }
                     }
                  } else {
                     $sql = "	SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
                        FROM s_menu 
                        LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
                        WHERE
                        S_MenuIsActive = 'Y' AND S_MenuID = '{$v['id']}'
                        ORDER BY S_MenuOrder ASC";
                     $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array();
                  }
               }
            } else {
               foreach ($rows as $k => $v) {
                  if ($v['S_MenuUrl'] == '#') {
                     $sql = "	SELECT S_MenuID as id, S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
							FROM s_menu 
							LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
							WHERE
							S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$v['id']}' AND S_MenuRegional = '{$prm['code']}'
							ORDER BY S_MenuOrder ASC";
                     $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array();
                     if ($rows[$k]['childs']) {
                        foreach ($rows[$k]['childs'] as $kx => $vx) {
                           if ($vx['S_MenuUrl'] == '#') {
                              $sql = "	SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
										FROM s_menu 
										LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
										WHERE
										S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$vx['id']}' AND S_MenuRegional = '{$prm['code']}'
										ORDER BY S_MenuOrder ASC";
                              $rows[$k]['childs'][$kx]['childs'] = $this->db_onedev->query($sql)->result_array();
                           }
                        }
                     }
                  } else {
                     $sql = "	SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs
							FROM s_menu 
							LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' 
							WHERE
							S_MenuIsActive = 'Y' AND S_MenuID = '{$v['id']}' AND S_MenuRegional = '{$prm['code']}'
							ORDER BY S_MenuOrder ASC";
                     $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array();
                  }
               }
            }
         } else {
            $this->sys_error_db("m_usergroup select");
            exit;
         }


         $result = array("total" => count($rows), "records" => $rows);
         $this->sys_ok($result);
      } catch (Exception $exc) {
         $message = $exc->getMessage();
         $this->sys_error($message);
      }
   }

   public function save()
   {
      try {
         //# cek token valid
         if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
         }

         $prm = $this->sys_input;
         $datas = $prm['datas'];
         foreach ($datas as $k => $v) {
            foreach ($v['childs'] as $kx => $vx) {
               if ($vx['active'] == 'Y') {
                  if (is_null($vx['S_PrivilegeID']) && $vx['status'] == 'Y') {
                     $sql = "INSERT INTO s_privilege (
									S_PrivilegeM_UserGroupID,
									S_PrivilegeS_MenuID,
									S_PrivilegeCreated
								)
								VALUES(
									{$vx['usergroupid']},
									{$vx['S_MenuID']},
									NOW()
								)";
                     $this->db_onedev->query($sql);
                     //echo $this->db_onedev->last_query();
                  }

                  if (!is_null($vx['S_PrivilegeID'])) {
                     $sql = "UPDATE s_privilege SET
									S_PrivilegeIsActive = '{$vx['status']}'
								WHERE
									S_PrivilegeID = '{$vx['S_PrivilegeID']}'
								";
                     $this->db_onedev->query($sql);
                     //echo $this->db_onedev->last_query();
                  }
               }
               if ($vx['childs']) {
                  foreach ($vx['childs'] as $kxz => $vxz) {
                     if ($vxz['active'] == 'Y') {
                        if (is_null($vxz['S_PrivilegeID']) && $vxz['status'] == 'Y') {
                           $sql = "INSERT INTO s_privilege (
											S_PrivilegeM_UserGroupID,
											S_PrivilegeS_MenuID,
											S_PrivilegeCreated
										)
										VALUES(
											{$vxz['usergroupid']},
											{$vxz['S_MenuID']},
											NOW()
										)";
                           $this->db_onedev->query($sql);
                           //echo $this->db_onedev->last_query();
                        }

                        if (!is_null($vxz['S_PrivilegeID'])) {
                           $sql = "UPDATE s_privilege SET
											S_PrivilegeIsActive = '{$vxz['status']}'
										WHERE
											S_PrivilegeID = '{$vxz['S_PrivilegeID']}'
										";
                           $this->db_onedev->query($sql);
                           //echo $this->db_onedev->last_query();
                        }
                     }
                  }
               }
            }
         }


         $result = array("total" => 1, "records" => array());
         $this->sys_ok($result);
      } catch (Exception $exc) {
         $message = $exc->getMessage();
         $this->sys_error($message);
      }
   }
}
