<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//$Id: RolesModel.php, v 1.0 2013/03/14 14:14:14
class RolesModel extends Model {
    //FUNCTION  TO GET USER TYPE DETAILS 
    public function getUserTypeDetails($userTypeID) {
        $sql = "
		SELECT 
			* 
		FROM 
			" . DB_PREFIX . "admin_user_type 
		WHERE 
			userTypeID='" . $userTypeID . "'
			AND userTypeStatus!='Deleted'";
        return $this->ObjDatabase->readValue($sql);
    }
    //END OF FUNCTION
    //FUNCTION  TO LIST USER TYPES
    public function listUserTypes($limitFrom = 0, $limitTo = "") {
        $sql = "SELECT ";
        if ($limitTo) {
            $sql .= " SQL_CALC_FOUND_ROWS ";
        }
        $sql .= " * 
		FROM 
			" . DB_PREFIX . "admin_user_type  
		WHERE 
			userTypeStatus!='Deleted'
		GROUP BY 
			userTypeID ORDER BY userTypeName ASC";
        if ($limitTo)
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . "";
        return $this->ObjDatabase->readValues($sql);
    }
    //END OF FUNCTION
    //FUNCTION TO CHANGE USER TYPE STATUS
    public function changeUserTypeStatus($userTypeIDs, $userTypeStatus, $deleteprivilage = '') {
        $usedIDs          = '';
        $userTypeIDString = implode(',', $userTypeIDs);
        $resListUserID    = $this->checkUserRole();
        foreach ($resListUserID as $resListUserID) {
            $usedIDs .= $resListUserID[0] . ",";
            $UserIDArray[] = $resListUserID[0];
        }
        $usedIDs       = substr($usedIDs, 0, -1);
        $commomUserIDs = array_intersect($userTypeIDs, $UserIDArray);
        if ($userTypeStatus == 'Deleted' && $deleteprivilage)
            $userTypeStatus = $userTypeStatus;
        else if ($userTypeStatus != 'Deleted')
            $userTypeStatus = $userTypeStatus;
        else
            $userTypeStatus = 'Active';
        $sql = "
		UPDATE  
			" . DB_PREFIX . "admin_user_type 
		SET 
			userTypeStatus='" . $userTypeStatus . "' ";
        if ($userTypeStatus == 'Deleted') {
            $sql .= "
		WHERE 
			userTypeID IN (" . $userTypeIDString . ") AND userTypeID NOT IN (" . $usedIDs . ")";
        } else {
            $sql .= "WHERE userTypeID IN (" . $userTypeIDString . ")";
        }
        $resUpdateRolesModules = $this->ObjDatabase->setQuery($sql);
        $userRole              = $this->getUserRole($commomUserIDs);
        return $userRole;
    }
    //END OF FUNCTION
    //FUNCTION TO CHECK USER ROLE
    function checkUserRole() {
        $sql = "
		SELECT 
			admUsr.userTypeID AS roleCount  
		FROM 
			" . DB_PREFIX . "admin_users admUsr 
		INNER JOIN 
			" . DB_PREFIX . "admin_user_type admUsrTyp 
			ON
			(
				admUsr.userTypeID=admUsrTyp.userTypeID 
				AND admUsr.adminUserStatus !='Deleted'
			)
		GROUP BY admUsr.userTypeID";
        return $this->ObjDatabase->readValues($sql, MYSQLI_NUM);
    }
    //END OF FUNCTION
    //FUNCTION TO GET USER ROLE
    function getUserRole($commomUserIDs) {
        $userRole       = '';
        $commomUserIDs  = implode(',', $commomUserIDs);
        $sql            = "SELECT 
								userTypeName 
							FROM 
								" . DB_PREFIX . "admin_user_type 
							WHERE 
								userTypeID IN(" . $commomUserIDs . ")";
        $resGetUserRole = $this->ObjDatabase->readValues($sql, MYSQLI_NUM);
        foreach ($resGetUserRole as $GetUserRole) {
            $userRole .= $GetUserRole[0] . ",";
        }
        $userRole = substr($userRole, 0, -1);
        return $userRole;
    }
    //END OF FUNCTION
    //FUNCTION TO GET USER TYPE ID
    function getUserTypeID($manageUserID) {
        $sql = "
		SELECT 
			admUsr.userTypeID,
			admUsrTyp.userTypeName 
		FROM 
			`" . DB_PREFIX . "admin_users` admUsr 
		LEFT JOIN 
			`" . DB_PREFIX . "admin_user_type` admUsrTyp
			ON admUsr.userTypeID=admUsrTyp.userTypeID
		WHERE 
			admUsr.adminUserID='" . $manageUserID . "'";
        return $this->ObjDatabase->readVALUE($sql);
    }
    //END OF FUNCTION
    //FUNCTION TO CHANGE USER TYPE STATUS
    public function changeRoleStatus($userTypeIDs, $userTypeStatus) {
        $sql = "
		UPDATE  
			" . DB_PREFIX . "admin_user_type 
		SET 
			userTypeStatus='" . $userTypeStatus . "' 
		WHERE 
			userTypeID =" . (int) $userTypeIDs . "
		LIMIT 1";
        return $this->ObjDatabase->setQuery($sql);
    }
    //END OF FUNCTION
    public function optgroupUserTypes($purpose = '') {
        $sql = "
				SELECT					
					admUsrTyp.userTypeID,
					admUsrTyp.userTypeName,
					CONCAT(adminUserFirstName,' ',adminUserLastName) AS adminname,
					admUsr.adminUserID,
					admUsr.adminUserStatus
				FROM
					" . DB_PREFIX . "admin_user_type AS admUsrTyp
				LEFT JOIN
					" . DB_PREFIX . "admin_users AS admUsr
					ON admUsr.userTypeID=admUsrTyp.userTypeID
				WHERE
					admUsrTyp.userTypeStatus!='Deleted'
					AND admUsr.adminUserStatus!='Deleted'";
        if ($purpose == 'content') {
            $sql .= "
					AND admUsr.adminUserStatus ='Active'";
        }
        $resUserTypes       = $this->ObjDatabase->readvalues($sql);
        $resSelectUserTypes = array();
        foreach ($resUserTypes as $resUserType) {
            $userTypeID  = $resUserType['userTypeID'];
            $adminUserID = $resUserType['adminUserID'];
            if (empty($resSelectUserTypes[$userTypeID])) {
                $resSelectUserTypes[$userTypeID]['userTypeID']   = $resUserType['userTypeID'];
                $resSelectUserTypes[$userTypeID]['userTypeName'] = $resUserType['userTypeName'];
            }
            $resSelectUserTypes[$userTypeID]['users'][] = $resUserType;
        }
        return $resSelectUserTypes;
    }
    //Save User Roles
    public function saveUserRoles() {
        //Roles Schema
        $schemaRoles    = $this->includeRolesSchema();
        $userTypeName   = $this->escape($_POST['userTypeName']);
        $userTypeID     = $this->escape($_POST['userTypeID']);
        $userTypeStatus = $_POST['userTypeStatus'];
        //Update/Insert into db
        if ($userTypeID > 0) {
            $sql = "
						UPDATE  
							" . DB_PREFIX . "admin_user_type 
						SET 
							userTypeName='" . $userTypeName . "',
							userTypeStatus='" . $userTypeStatus . "'
						WHERE
							userTypeID='" . $userTypeID . "'";
            $this->ObjDatabase->setQuery($sql);
        } else {
            $sql = "
						INSERT INTO 
							" . DB_PREFIX . "admin_user_type
							(
								userTypeName,
								userTypeStatus
							)
							VALUES
							(
								'" . $userTypeName . "',
								'" . $userTypeStatus . "'
							)";
            $this->ObjDatabase->setQuery($sql);
            $userTypeID = $this->ObjDatabase->getInsertId();
        }
        if ($userTypeID > 1) {
            $moduleIDs       = $_POST['moduleIDs'];
            //Writing to XML
            $arrayPrivilages = '<?xml version="1.0" encoding="ISO-8859-1"?>';
            $arrayPrivilages .= '<roles>';
            foreach ($moduleIDs as $moduleUrls) {
                if ($moduleUrls != '') {
                    $subModules = explode("~*", $moduleUrls);
                    $arrayPrivilages .= "<value>" . implode("</value><value>", $subModules) . "</value>";
                }
            }
            $arrayPrivilages .= '</roles>';
            $fileName = $this->encodeString($userTypeID);
            $Handle   = fopen(__CORE_PUBLIC_CACHE_PATH . "/roles/" . $fileName . ".xml", "w");
            fwrite($Handle, "" . $arrayPrivilages . "");
            fclose($Handle);
        }
    }
    //Get Privilage File 
    public function getPrivilageFile($userTypeID) {
        $fileNameKey    = $this->encodeString($userTypeID);
        $privilageArray = array();
        $fileName       = __CORE_PUBLIC_CACHE_PATH . "/roles/" . $fileNameKey . ".xml";
        if (file_exists($fileName)) {
            $xml = simplexml_load_file($fileName);
            $i   = 0;
            foreach ($xml->value as $value) {
                $urlKeyString     = $this->escape($xml->value[$i]);
                $privilageArray[] = htmlentities($urlKeyString);
                $i++;
            }
        }
        //print_r($privilageArray);exit;
        return $privilageArray;
    }
    //Include Roles Schema File
    public function includeRolesSchema() {
        //Roles Schema
        include_once(__CORE_PUBLIC_SCHEMA_PATH . '/roles.php');
        return $GLOBALS["ROLES_SCHEMA"];
    }
}