<?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: RolesController.php, v 1.0 2011/06/14 20:52:11
//
class RolesController extends Controller {
    //LISTING ROLES
    public function indexAction() {
        $ObjRoles = new RolesModel();
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('roles/edit/'));
        $deletePrivilege = $this->ObjCommon->hasPrivilege('roles/destroy/');
        $this->ObjView->assign("deletePrivilege", $deletePrivilege);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $resListUserTypes = $ObjRoles->listUserTypes($limitFrom, $limitTo);
        $resPagesCount    = $this->setPagesCount($key = 'page');
        if (isset($_POST['userTypeStatus'])) {
            if (($checkMainAdmin = array_search('1', $_POST['userTypeIDs'])) !== false) {
                //Remove if main admin typeid is present
                unset($_POST['userTypeIDs'][$checkMainAdmin]);
            }
            //Check current loggedin Admin typeidid 
            if (($checkCurrentAdmin = array_search($this->ObjCommon->mangeUserTypeID, $_POST['userTypeIDs'])) !== false) {
                //Remove if current admin id is present
                unset($_POST['userTypeIDs'][$checkCurrentAdmin]);
            }
            if (!empty($_POST['userTypeIDs'])) {
                $resUserTypeStatus = $ObjRoles->changeUserTypeStatus($_POST['userTypeIDs'], $_POST['userTypeStatus'], $deletePrivilege);
                if ($_POST['userTypeStatus'] == "Deleted") {
                    if ($resUserTypeStatus) {
                        $msgRoleNoDeleteMultiple = $this->getLanguageValue("msgRoleNoDeleteMultiple");
                        $msgRoleNoDeleteMultiple = $resUserTypeStatus . " " . $msgRoleNoDeleteMultiple;
                        $this->setMessage($msgRoleNoDeleteMultiple, "message_success");
                    } else {
                        $this->setMessage("language.msgRolesDelete", "message_success");
                    }
                } else {
                    $this->setMessage("language.msgRolesUpdateStatus", "message_success");
                }
            }
            $PreviousURL = $this->getPreviousURL();
            $this->setRedirect($PreviousURL);
        }
        $this->ObjView->assign("curr_page", $this->getRequestValue('page'));
        $this->ObjView->assign("resListUserTypes", $resListUserTypes);
        $this->ObjView->display('Roles.tpl');
    }
    //ADD ROLES
    public function newAction() {
        $ObjRoles    = new RolesModel();
        $languageIDs = $this->ObjView->languageIDs;
        $userTypeID  = $this->getRequestValue("id");
        $this->ObjView->assign('PreviousURL', $this->getPreviousURL());
        if ($this->ObjForm->isValid('formRoles', 'submitRoles')) {
            $ObjRoles->saveUserRoles();
            $objCache = new Cache("file");
            foreach ($languageIDs['All'] as $langIds) {
                $objCache->delete('m_menu_list_' . $userTypeID . '_' . $langIds);
            }
            $this->setMessage("language.msgAdminRoleAdd", "message_success");
            $this->setRedirect("/roles/index/");
        }
        $resTreeRolesModules = $this->listRolesData();
        $this->ObjView->assign("resTreeRolesModules", $resTreeRolesModules);
        $this->ObjView->display('RolesAdd.tpl');
    }
    //EDIT ROLES
    public function editAction() {
        $ObjRoles    = new RolesModel();
        $languageIDs = $this->ObjView->languageIDs;
        $userTypeID  = $this->getRequestValue("id");
        $this->ObjView->assign("userTypeID", $userTypeID);
        $resUserTypeDetails = $ObjRoles->getUserTypeDetails($userTypeID);
        if (empty($resUserTypeDetails)) {
            $this->setRedirect("/roles/index/");
        }
        //Restriction Admin User type & Current user edit
        if (($userTypeID != 1 && $userTypeID == $this->ObjCommon->mangeUserTypeID) || ($userTypeID == 1 && $this->ObjCommon->mangeUserTypeID != 1)) {
            $this->setRedirect("/roles/index/");
        }
        $this->ObjView->assign('PreviousURL', $this->getPreviousURL());
        if ($this->ObjForm->isValid('formRoles', 'submitRoles')) {
            if ($userTypeID == 1 || $userTypeID == $this->ObjCommon->mangeUserTypeID) {
                if ($userTypeID == 1)
                    $_POST['adminMode'] = 'Administrator';
                $_POST['userTypeStatus'] = 'Active';
            }
            $_POST['userTypeID'] = $userTypeID;
            $ObjRoles->saveUserRoles();
            if ($userTypeID > 1) {
                $objCache = new Cache("file");
                foreach ($languageIDs['All'] as $langIds) {
                    $objCache->delete('m_menu_list_' . $userTypeID . '_' . $langIds);
                }
            }
            $this->setMessage("language.msgAdminRoleUpdate", "message_success");
            $this->setRedirect("/roles/index/");
        }
        if ($userTypeID > 1) {
            $resPrivileges       = $ObjRoles->getPrivilageFile($resUserTypeDetails['userTypeID']);
            $params              = array(
                'privilegeData' => $resPrivileges
            );
            $resTreeRolesModules = $this->listRolesData($params);
            $this->ObjView->assign("resTreeRolesModules", $resTreeRolesModules);
            $this->ObjView->assign("resPrivileges", json_encode($resPrivileges));
        }
        $this->ObjView->assignValues($resUserTypeDetails);
        $this->ObjView->assign("userTypeID", $userTypeID);
        $this->ObjView->display('RolesAdd.tpl');
    }
    //DELETE ROLES
    public function destroyAction() {
        $ObjRoles   = new RolesModel();
        $userTypeID = $this->getRequestValue("id");
        if ($userTypeID > 1 && $userTypeID != $this->ObjCommon->mangeUserTypeID) {
            $resUserTypeStatus = $ObjRoles->changeUserTypeStatus(array(
                $userTypeID
            ), $userTypeStatus = "Deleted", $this->ObjCommon->hasPrivilege('roles/destroy/'));
            if ($resUserTypeStatus) {
                $msgRoleNoDeleteMultiple = $this->getLanguageValue("msgRoleNoDeleteMultiple");
                $msgRoleNoDeleteMultiple = $resUserTypeStatus . " " . $msgRoleNoDeleteMultiple;
                $this->setMessage($msgRoleNoDeleteMultiple, "message_success");
            } else {
                $this->setMessage("language.msgRolesDelete", "message_success");
            }
        }
        $this->setRedirect($this->getPreviousURL());
    }
    //FUNCTION to change the status of user type
    public function ajaxstatusAction() {
        $ObjRoles             = new RolesModel();
        $POST['changeStatus'] = $_POST['newstatus'];
        if ($_POST['id'] > 1 && $_POST['id'] != $this->ObjCommon->mangeUserTypeID) {
            $changestatus = $ObjRoles->changeRoleStatus($_POST['id'], $POST['changeStatus']);
            $this->setMessage("language.msgStatus", "message_success");
            if ($changestatus)
                echo 1;
        }
    }
    //END of function 		
    function checkRoleSelect() {
        if ($this->ObjCommon->mangeUserTypeID > 1 && empty($_POST['moduleIDs']))
            return false;
        return true;
    }
    //List Roles Data
    public function listRolesData($params = array()) {
        extract($params);
        $ObjRoles    = new RolesModel();
        //Roles Schema
        $schemaRoles = $ObjRoles->includeRolesSchema();
        $params      = array(
            'schemaData' => $schemaRoles['permissions'],
            'languageXml' => $this->ObjView->_languageXML,
            'treeString' => '',
            'treeLevel' => 0,
            'parent' => 0,
            'parents' => array(),
            'privilegeData' => (!empty($privilegeData)) ? $privilegeData : array()
        );
        return $this->listRolesItems($params);
    }
    //List Roles Items
    private function listRolesItems($params) {
        extract($params);
        if ($treeLevel == 0) {
            $treeString = '<ul class="roles_listing treeview" id="tree">';
        } else {
            $treeString = '<ul style="display: none;">';
        }
        $treeLevel++;
        if (!empty($schemaData)) {
            foreach ($schemaData as $arrayKey => $schema) {
                $currMenuURL            = $schema['adminModuleURLKey'];
                $currAdminModuleLabel   = $schema['adminModuleLabel'];
                $currRootLevel          = isset($schema['rootLevel']) ? $schema['rootLevel'] : '';
                $currAdminSectionKey    = $schema['adminSectionKey'];
                $inputType              = isset($schema['inputType']) ? $schema['inputType'] : '';
                $subText                = isset($schema['subText']) ? $schema['subText'] : '';
                $adminModuleStatus      = $schema['adminModuleStatus'];
                $xmlLabel               = isset($languageXml[$currAdminModuleLabel]) ? $languageXml[$currAdminModuleLabel] : '';
                $currAdminModuleCaption = ($xmlLabel != '') ? $xmlLabel : $currAdminModuleLabel;
                $currAdminModuleCaption = $xmlLabel;
                $schema['adminSubMenu'] = (!empty($schema['adminSubMenu'])) ? $schema['adminSubMenu'] : array();
                $resSubRolesCount       = count($schema['adminSubMenu']);
                $checked                = '';
                //Checking Addon Module
                if ($currAdminSectionKey != '' && !constant($currAdminSectionKey)) {
                    continue;
                }
                //Checking Status
                if ($adminModuleStatus != 'Active') {
                    continue;
                }
                if (!empty($privilegeData) && $resSubRolesCount == 0 && in_array($currMenuURL, $privilegeData)) {
                    $checked = 'checked';
                }
                if ($resSubRolesCount > 0) {
                    $treeString .= '<li>';
                    $checkboxClass = "module_parent";
                } else {
                    //For the last Element
                    $schemaCountCheck = count($schema) - 1;
                    if (isset($schema[$schemaCountCheck]) && $schema == $schema[$schemaCountCheck]) {
                        $treeString .= '<li class="last">';
                    } else {
                        $treeString .= '<li>';
                    }
                    $checkboxClass = "module_child";
                }
                if (!in_array("roleID_" . $parent, $parents)) {
                    $parents[] = "roleID_" . $parent;
                }
                if ($inputType == '') {
                    $inputField = "checkbox";
                } elseif ($inputType == 'radio') {
                    $inputField = "radio";
                }
                $treeString .= '<input class="moduleGroupClass_all ' . $checkboxClass . '" parents="' . implode(",", $parents) . '" id="roleID_' . $parent . "_" . $arrayKey . '" name="moduleIDs[]" type="checkbox" attrtype="' . $inputField . '" value="' . $currMenuURL . '"' . $checked . '/>';
                $treeString .= '&nbsp;' . $currAdminModuleCaption . '';
                if ($subText) {
                    if ($resSubRolesCount > 0) {
                        $treeString .= '[ ' . $languageXml[$subText] . ' ]';
                    } else {
                        $treeString .= '<span class="sub-text">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;( ' . $languageXml[$subText] . ' )</span>';
                    }
                }
                if ($resSubRolesCount > 0) {
                    $params = array(
                        'schemaData' => $schema['adminSubMenu'],
                        'treeString' => $treeString,
                        'treeLevel' => $treeLevel,
                        'languageXml' => $languageXml,
                        'campignEnable' => isset($campignEnable) ? $campignEnable : '',
                        'parent' => $parent . "_" . $arrayKey,
                        'parents' => $parents,
                        'privilegeData' => $privilegeData
                    );
                    $treeString .= $this->listRolesItems($params);
                    //$parent = $arrayKey;
                }
                $treeString .= '</li>';
            }
        }
        $treeString .= '</ul>';
        return $treeString;
    }
}