<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "admin/UserGroupClass.php");

class UserGroup extends GLBase {
	private $type = "" ;
	private $clsgroup ;
	private $clsright ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
        $this->clsgroup = new UserGroupClass($this->db) ;
		$this->clsright = new UserRight() ;
	}
	function __destruct() {
		unset($this->db) ;
        unset($this->clsgroup) ;
		unset($this->clsright) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}

			switch ($this->type) {
				case Command::UserGroupView:
					$this->getView($params) ;
					break ;
                case Command::UserGroupListView:
                    $this->getUserGroupList($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params);
                    break;
                case REQ_DELETE:
                    $this->deleteUserGroupRecord($params);
                    break;
                // //AUTO SEARCH
                // case "CUSTOMER_CODE_SEARCH_SALES_QUOTATION":
                //     $this->getCustomerSearchList($params);
                //     break;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function getRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$row = $this->clsgroup->getRecord($id) ;
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid user group id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
				$datas['id'] = $id ;
				$datas['code'] = $row[UserGroupTable::C_CODE];
				$datas['name'] = $row[UserGroupTable::C_NAME];
				if (is_null($row[UserGroupTable::C_RIGHTS]))
					$this->clsright->initRights();
				else
					$this->clsright->toRights($row[UserGroupTable::C_RIGHTS]); ;

				$datas['admin'] = $this->getAdminRights($this->clsright->getAdminRights()) ;
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
				
			}
		} else {
			$this->sendJsonResponse(Status::Error,"Missing user group id. Please try again.","",$this->type);
		}
	}

	private function getView($params) {
		ob_start() ;
		include (PATH_VIEWS . "admin/usergroup/UserGroupView.php") ;

		$action_menu = '<section class="content-header" id="main-header" style="padding-left: 230px;">' .

						'</section>';

        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn=[];
		$dataReturn['htmlContent'] = $var_screen;
		$dataReturn['action_menu'] = $action_menu;
        $dataReturn['headTitle']  = "User Group" ;
		$this->sendJsonResponse(Status::Ok,"User Group Info",$dataReturn,$this->type);
		return;
	}
	public function getOption() {
		$cls = new UserGroupClass($this->db);
		$rows = $cls->getAllOption();
		$lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
				if (is_null($row[UserGroupTable::C_RIGHTS]))
					$this->clsright->initRights();
				else
					$this->clsright->toRights($row[UserGroupTable::C_RIGHTS]);
                $list = [
                    "id" => $row[UserGroupTable::C_ID],
                    "code" => htmlentities($row[UserGroupTable::C_CODE]),
                    "name" => htmlentities($row[UserGroupTable::C_NAME]),
					"admin" => $this->getAdminRights($this->clsright->getAdminRights()),
                ];
                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);
		return $lists;
	}	
    private function getUserGroupList($params) {
        $cls  = new UserGroupClass($this->db);
		$sorts = $params['sorts'];
		$orderby = "";
		$sort = array();
        
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_code":
                    $orderby = UserGroupTable::C_CODE . " " . $sort[1];
                    break;
                case "col_name":
                    $orderby = UserGroupTable::C_NAME . " " . $sort[1];
                    break;
                default:
                    $orderby = UserGroupTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = UserGroupTable::C_NAME . " asc";
        }

        $status = "";
        if (isset($params['status'])) {
            $status = $params['status'];
        } else {
            $status = "all";
        }

        $rows = $cls->getUserGroupList("", $status, $orderby);

        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id" => $row[UserGroupTable::C_ID],
                    "code" => htmlentities($row[UserGroupTable::C_CODE]),
                    "name" => htmlentities($row[UserGroupTable::C_NAME]),
                ];

                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);

        $this->sendJsonResponse(Status::Ok, "", $lists, $this->type);
    }
    private function addRecord($params) {
		$cls = new UserGroupClass($this->db);

		$datas = array() ;
		$orgid = $_SESSION[SE_ORGID] ;
		$modifyby = $_SESSION[SE_USERID] ;
		$modifydate = date_create('now')->format('Y-m-d H:i:s') ;
		$ws = $_SESSION[SE_REMOTE_IP];
		$datas[] = $this->db->fieldValue(UserGroupTable::C_CODE,$this->getParam($params,'code',"")) ;
		$datas[] = $this->db->fieldValue(UserGroupTable::C_NAME,$this->getParam($params,"name","")) ;
		$datas[] = $this->db->fieldValue(UserGroupTable::C_RIGHTS,$this->convertRights($params)) ;

		// $datas[] = $this->db->fieldValue(UserGroupTable::C_WS_ID,$ws) ;
		// $datas[] = $this->db->fieldValue(UserGroupTable::C_MODIFY_BY,$modifyby) ;
		// $datas[] = $this->db->fieldValue(UserGroupTable::C_CREATE_BY,$modifyby) ;
		// $datas[] = $this->db->fieldValue(UserGroupTable::C_MODIFY_DATE,$modifydate) ;
		// $datas[] = $this->db->fieldValue(UserGroupTable::C_CREATE_DATE,$modifydate) ;
		// $datas[] = $this->db->fieldValue(UserGroupTable::C_ORG_ID,$orgid) ;
		
		try {
			$this->db->beginTran();

			$id = $this->clsgroup->addRecord($datas) ;
			if ($id > 0) {
				$this->db->commitTran();
				$this->sendJsonResponse(Status::Ok,"User group successfully added to the system.",$id,$this->type);
				
			} else {
				$this->db->rollbackTran();
				$this->sendJsonResponse(Status::Error,"1Sorry, there is a error in adding new user group to the system.",$id, $this->type) ;
			} 
		} catch (Exception $e) {
			$this->db->rollbackTran();
			$this->sendJsonResponse(Status::Error,"2Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
    }
	private function updateRecord($params) {
		$cls = new UserGroupClass($this->db);
		if (isset($params['id'])) {
			$id = $params['id'];
			$cls = new UserGroupClass($this->db);
			$datas = array();

			$modifyby = $_SESSION[SE_USERID];
			$modifydate = date_create('now')->format('Y-m-d H:i:s');
			$ws = $_SESSION[SE_REMOTE_IP];

			$datas[] = $this->db->fieldValue(UserGroupTable::C_CODE,$this->getParam($params,'code',"")) ;
			$datas[] = $this->db->fieldValue(UserGroupTable::C_NAME,$this->getParam($params,"name","")) ;
			$datas[] = $this->db->fieldValue(UserGroupTable::C_RIGHTS,$this->convertRights($params));

			try {
				$this->db->beginTran();
				$mesg = "";
				$result = "";
				$exist = $cls->getExistingRecords($this->getParam($params,'code',""), $id);
				if (!is_null($exist)) {
					$this->sendJsonResponse(Status::Error,"User Group code already exist.","", $this->type) ;
				} else {
					$cls->updateRecord($id,$datas);
					
					$mesg = "User Group successfully updated to the system.";

					$this->db->commitTran();
					$this->sendJsonResponse(Status::Ok,$mesg,$result,$this->type);
					
				}
			} catch (Exception $e) {
				$this->db->rollbackTran();
				$this->sendJsonResponse(Status::Error,"3Sorry, there is a error in updating user group detail to the system.","", $this->type) ;
			}
			unset($cls);
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the user group id you wish to update. Please try agian.","", $this->type);
		}
	}
	private function deleteUserGroupRecord($params) {
		$cls = new UserGroupClass($this->db);
		$id = $this->getParamInt($params,'id',0);
		if ($id == 0) {
			$this->sendJsonResponse(Status::Error,"Invalid ID.","",$this->type);
			return;
		}
		try {
			$this->db->beginTran();
			$cls->deleteRecord($id);
			$this->db->commitTran();

			$this->sendJsonResponse(Status::Ok,"Successfully delete user group from system.","",$this->type);
			return;
		} catch (Exception $e) {
			$this->db->rollbackTran();
			if($e->getMessage() == Message::DB_ERR_DELETE_USED) {
				$this->sendJsonResponse(Status::Error, Message::DB_ERR_DELETE_USED,"",$this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"4Sorry, there is a error in deleting user group from the system.","",$this->type);
			}
			return;
		}
		unset($cls);
	}

    private function convertRights($params) {
		$this->clsright->initRights() ;
		if (isset($params['admin'])) {
			$r = array() ;
			$rs = $params['admin'] ;
			if (isset($rs['marketing_entity']))
				$r[UserRight::C_MARKETING_ENTITY] = $this->clsright->bin2Access(str_repeat($rs['marketing_entity'],6)) ;
			if(isset($rs['marketing_view_others']))
				$r[UserRight::C_MARKETING_VIEW_OTHERS] = $this->clsright->bin2Access(str_repeat($rs['marketing_view_others'],6)) ;
			if (isset($rs['marketing_edit_others']))
				$r[UserRight::C_MARKETING_EDIT_OTHERS] = $this->clsright->bin2Access(str_repeat($rs['marketing_edit_others'],6)) ;
			if (isset($rs['sales_account']))
				$r[UserRight::C_SALES_ACCOUNT] = $this->clsright->bin2Access(str_repeat($rs['sales_account'],6)) ;
			if (isset($rs['sales_suspect']))
				$r[UserRight::C_SALES_SUSPECT] = $this->clsright->bin2Access(str_repeat($rs['sales_suspect'],6)) ;
			if (isset($rs['sales_prospect']))
				$r[UserRight::C_SALES_PROSPECT] = $this->clsright->bin2Access(str_repeat($rs['sales_prospect'],6)) ;
			if (isset($rs['sales_opportunity']))
				$r[UserRight::C_SALES_OPPORTUNITY] = $this->clsright->bin2Access(str_repeat($rs['sales_opportunity'],6)) ;
			if(isset($rs['sales_view_others']))
				$r[UserRight::C_SALES_VIEW_OTHERS] = $this->clsright->bin2Access(str_repeat($rs['sales_view_others'],6)) ;
			if (isset($rs['sales_edit_others']))
				$r[UserRight::C_SALES_EDIT_OTHERS] = $this->clsright->bin2Access(str_repeat($rs['sales_edit_others'],6)) ;
			if (isset($rs['integration_customer']))
				$r[UserRight::C_INTEGRATION_CUSTOMER] = $this->clsright->bin2Access(str_repeat($rs['integration_customer'],6)) ;
			if (isset($rs['integration_prospect']))
				$r[UserRight::C_INTEGRATION_PROSPECT] = $this->clsright->bin2Access(str_repeat($rs['integration_prospect'],6)) ;
			if (isset($rs['integration_export_data']))
				$r[UserRight::C_INTEGRATION_EXPORT_DATA] = $this->clsright->bin2Access(str_repeat($rs['integration_export_data'],6)) ;
			if (isset($rs['integration_destination_master']))
				$r[UserRight::C_INTEGRATION_DESTINATION_MASTER] = $this->clsright->bin2Access(str_repeat($rs['integration_destination_master'],6)) ;
			if (isset($rs['admin_user']))
				$r[UserRight::C_ADMIN_USER] = $this->clsright->bin2Access(str_repeat($rs['admin_user'],6)) ;
			if (isset($rs['admin_user_group']))
				$r[UserRight::C_ADMIN_USER_GROUP] = $this->clsright->bin2Access(str_repeat($rs['admin_user_group'],6)) ;
			if (isset($rs['admin_industry']))
				$r[UserRight::C_ADMIN_INDUSTRY] = $this->clsright->bin2Access(str_repeat($rs['admin_industry'],6)) ;
			if (isset($rs['admin_business_sector']))
				$r[UserRight::C_ADMIN_BUSINESS_SECTOR] = $this->clsright->bin2Access(str_repeat($rs['admin_business_sector'],6)) ;
			if (isset($rs['admin_business_nature']))
				$r[UserRight::C_ADMIN_BUSINESS_NATURE] = $this->clsright->bin2Access(str_repeat($rs['admin_business_nature'],6)) ;
			if (isset($rs['admin_software']))
				$r[UserRight::C_ADMIN_SOFTWARE] = $this->clsright->bin2Access(str_repeat($rs['admin_software'],6)) ;
			if (isset($rs['admin_department']))
				$r[UserRight::C_ADMIN_DEPARTMENT] = $this->clsright->bin2Access(str_repeat($rs['admin_department'],6)) ;
			if (isset($rs['report_contact']))
				$r[UserRight::C_REPORT_CUSTOMER_CONTACT_LISTING] = $this->clsright->bin2Access(str_repeat($rs['report_contact'],6)) ;
			if (isset($rs['report_summary']))
				$r[UserRight::C_REPORT_CORPORATE_GIFT_SUMMARY] = $this->clsright->bin2Access(str_repeat($rs['report_summary'],6)) ;
			if (isset($rs['report_inquiry']))
				$r[UserRight::C_REPORT_CORPORATE_GIFT_INQUIRY] = $this->clsright->bin2Access(str_repeat($rs['report_inquiry'],6)) ;
			if (isset($rs['report_history']))
				$r[UserRight::C_REPORT_CORPORATE_GIFT_HISTORY] = $this->clsright->bin2Access(str_repeat($rs['report_history'],6)) ;
			if (isset($rs['gift_company']))
				$r[UserRight::C_CORPORATE_GIFT_COMPANY_PROFILE] = $this->clsright->bin2Access(str_repeat($rs['gift_company'],6)) ;
			if (isset($rs['gift_listing']))
				$r[UserRight::C_CORPORATE_GIFT_LIST] = $this->clsright->bin2Access(str_repeat($rs['gift_listing'],6)) ;
			if (isset($rs['gift_master']))
				$r[UserRight::C_CORPORATE_GIFT_MASTER] = $this->clsright->bin2Access(str_repeat($rs['gift_master'],6)) ;
			if (isset($rs['campaign_company']))
				$r[UserRight::C_CAMPAIGN_COMPANY_PROFILE] = $this->clsright->bin2Access(str_repeat($rs['campaign_company'],6)) ;
			if (isset($rs['campaign_listing']))
				$r[UserRight::C_CAMPAIGN_LIST] = $this->clsright->bin2Access(str_repeat($rs['campaign_listing'],6)) ;
			if (isset($rs['campaign_master']))
				$r[UserRight::C_CAMPAIGN_MASTER] = $this->clsright->bin2Access(str_repeat($rs['campaign_master'],6)) ;
			if (isset($rs['report_conversation']))
				$r[UserRight::C_REPORT_CONVERSATION] = $this->clsright->bin2Access(str_repeat($rs['report_conversation'],6)) ;
			if (isset($rs['report_all_account']))
				$r[UserRight::C_REPORT_ALL_ACCOUNT] = $this->clsright->bin2Access(str_repeat($rs['report_all_account'],6)) ;

			$this->clsright->setAdminRights($r) ;
		}	
		return $this->clsright->toString();
	}
    
	public function getAdminRights($rights) {
		$arr = array() ;
		$arr['marketing_entity']				= $rights[UserRight::C_MARKETING_ENTITY][UserRight::C_ENABLE];
		$arr['marketing_view_others']			= $rights[UserRight::C_MARKETING_VIEW_OTHERS][UserRight::C_ENABLE];
		$arr['marketing_edit_others']			= $rights[UserRight::C_MARKETING_EDIT_OTHERS][UserRight::C_ENABLE];
		$arr['sales_account']					= $rights[UserRight::C_SALES_ACCOUNT][UserRight::C_ENABLE];
		$arr['sales_suspect']					= $rights[UserRight::C_SALES_SUSPECT][UserRight::C_ENABLE];
		$arr['sales_prospect']					= $rights[UserRight::C_SALES_PROSPECT][UserRight::C_ENABLE];
		$arr['sales_opportunity']				= $rights[UserRight::C_SALES_OPPORTUNITY][UserRight::C_ENABLE];
		$arr['sales_view_others']				= $rights[UserRight::C_SALES_VIEW_OTHERS][UserRight::C_ENABLE];
		$arr['sales_edit_others']				= $rights[UserRight::C_SALES_EDIT_OTHERS][UserRight::C_ENABLE];
		$arr['integration_customer']			= $rights[UserRight::C_INTEGRATION_CUSTOMER][UserRight::C_ENABLE];
		$arr['integration_prospect']			= $rights[UserRight::C_INTEGRATION_PROSPECT][UserRight::C_ENABLE];
		$arr['integration_export_data']			= $rights[UserRight::C_INTEGRATION_EXPORT_DATA][UserRight::C_ENABLE];
		$arr['integration_destination_master']	= $rights[UserRight::C_INTEGRATION_DESTINATION_MASTER][UserRight::C_ENABLE];
		$arr['admin_user']            			= $rights[UserRight::C_ADMIN_USER][UserRight::C_ENABLE];
		$arr['admin_user_group']      			= $rights[UserRight::C_ADMIN_USER_GROUP][UserRight::C_ENABLE];
		$arr['admin_industry'] 					= $rights[UserRight::C_ADMIN_INDUSTRY][UserRight::C_ENABLE];
		$arr['admin_business_sector'] 			= $rights[UserRight::C_ADMIN_BUSINESS_SECTOR][UserRight::C_ENABLE];
		$arr['admin_business_nature'] 			= $rights[UserRight::C_ADMIN_BUSINESS_NATURE][UserRight::C_ENABLE];
		$arr['admin_software'] 					= $rights[UserRight::C_ADMIN_SOFTWARE][UserRight::C_ENABLE];
		$arr['admin_department'] 				= $rights[UserRight::C_ADMIN_DEPARTMENT][UserRight::C_ENABLE];
		$arr['gift_company']          			= $rights[UserRight::C_CORPORATE_GIFT_COMPANY_PROFILE][UserRight::C_ENABLE];
		$arr['gift_listing'] 					= $rights[UserRight::C_CORPORATE_GIFT_LIST][UserRight::C_ENABLE];
		$arr['gift_master'] 					= $rights[UserRight::C_CORPORATE_GIFT_MASTER][UserRight::C_ENABLE];
		$arr['campaign_company'] 	       		= $rights[UserRight::C_CAMPAIGN_COMPANY_PROFILE][UserRight::C_ENABLE];
		$arr['campaign_listing'] 				= $rights[UserRight::C_CAMPAIGN_LIST][UserRight::C_ENABLE];
		$arr['campaign_master'] 				= $rights[UserRight::C_CAMPAIGN_MASTER][UserRight::C_ENABLE];
		$arr['report_contact']        			= $rights[UserRight::C_REPORT_CUSTOMER_CONTACT_LISTING][UserRight::C_ENABLE];
		$arr['report_summary']        			= $rights[UserRight::C_REPORT_CORPORATE_GIFT_SUMMARY][UserRight::C_ENABLE];
		$arr['report_inquiry']        			= $rights[UserRight::C_REPORT_CORPORATE_GIFT_INQUIRY][UserRight::C_ENABLE];
		$arr['report_history']        			= $rights[UserRight::C_REPORT_CORPORATE_GIFT_HISTORY][UserRight::C_ENABLE];
		$arr['report_conversation']     		= $rights[UserRight::C_REPORT_CONVERSATION][UserRight::C_ENABLE];
		$arr['report_all_account']      		= $rights[UserRight::C_REPORT_ALL_ACCOUNT][UserRight::C_ENABLE];
		return $arr ;
	}

}
?>
