<?php

namespace Dashboard\Controller;

//use Zend\Mvc\Controller\AbstractActionController;
use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Dashboard\Form\UserRoleManagerForm;
use Dashboard\Form\UserDepartmentManagerForm;
use Zend\Session\Container;
use Zend\Json\Json;
use Zend\Debug\Debug;

class UserRoleManagerController extends RestAPIClientController {
    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        //write code here...
        $roleManagerListing=[];
        $form = new UserRoleManagerForm();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        $roleManagerListing=$this->roleManagerListing($userId);
        $viewModel = new ViewModel(['rolemanagerListing' => $roleManagerListing]);
        return $viewModel;
    }


    public function addUserRoleAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        $form = new UserRoleManagerForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();

            $form->setData($postData);
            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'role_name'=>$postData['title'],
                    'description'=>$postData['description'],
                    //'moduleids'=>implode(',',$postData['modulenameid']),
                    'created_by'=>$userId,
                    'status'=>$postData['status'],
                    'created_date'=>date('Y-m-d')
                  ];

                $url = $this->apiUrl() . "/role-assign-module/addroleassignmodule";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
               

                 if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "User Added Successfully..";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else {
                    $msg = "User Could Not Added!..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }

        }
        else{
             $msg = $form->getMessages();

        }

            }
        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }
     public function editUserRoleAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new UserRoleManagerForm();
        $roleId = $this->params()->fromQuery('id');

        if ($roleId != '' && $userId != '') {
            $url = $this->apiUrl() . "/role-assign-module/getAllRole?user_id=" . $userId."&id=".$roleId;
            $val = $this->get($url);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);

            $roles =[];
            if ((!empty($JsonData['responsedata']))) {
                $roles = $JsonData['responsedata'];

            }
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();

            $form->setData($postData);
            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'role_id'=>$postData['role_id'],
                    'role_name'=>$postData['title'],
                    'description'=>$postData['description'],
                   // 'moduleids'=>implode(',',$postData['modulenameid']),
                    'created_by'=>$userId,
                    'created_date'=>date('Y-m-d'),
                    'modified_by'=>$userId,
                    'status'=>$postData['status']
                  ];

                $url = $this->apiUrl() . "/role-assign-module/updateRoleAssignModule";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "Role Updated Successfully..";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else {
                    $msg = "Role Not Updated Successfully..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }

        }
        else{
             //$msg = $form->getMessages();

        }

            }




        $viewModel = new ViewModel(['form' => $form,'roleData'=>$roles,'roleId'=>$roleId]);
        return $viewModel;
    }


    public function departmentAction() {
        $data=[];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        
        $data = $this->getAllDepartmentList();
        $viewModel = new ViewModel(['data' => $data]);

        return $viewModel;
    }

    public function addDepartmentAction() {
        $msg = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;


        $form = new UserDepartmentManagerForm();
        $request = $this->getRequest();


        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();

            $form->setData($request->getPost());

            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'department_name' => $postData['department_name'],
                    'description' => $postData['description'],
                    'created_by' => $userId,
                    'status' => $postData['status'],
                    'created_date' => date('Y-m-d H:i:s')
                ];

                $jsonData = Json::encode($finalData);
                $url = $this->apiUrl() . "/department";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ((!empty($JsonData)) && (!isset($JsonData['error']))) {

                    $msg = "Department Details Added Successfully";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Department Details Could Not Added Successfully";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }

        }



        $viewModel = new ViewModel(['form' => $form]);

        return $viewModel;
    }

    public function editDepartmentAction() {
        $msg = "";
        $form = new UserDepartmentManagerForm();

        $depid = $this->params()->fromQuery('id');
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $getdata = '{"where": {"id": "' . $depid . '"}}';
        $getdata = rawurlencode($getdata);
        $url = $this->apiUrl() . "/department?&filter=" . $getdata;
        $val = $this->get($url);

        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);

        if ((!empty($JsonData))) {
            $form->setData($JsonData[0]);
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'id' => $postData['id'],
                    'department_name' => $postData['department_name'],
                    'description' => $postData['description'],
                    'status' => $postData['status'],
                    'modified_by' => $userId,
                    'modified_date' => date('Y-m-d H:i:s')
                ];
                $val = '{"id": "' . $postData['id'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/department/upsertWithWhere?where=" . $val;

                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "Department details Updated Successfully..";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Department Details Not Updated Successfully..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
        }


        $viewModel = new ViewModel(['form' => $form]);

        return $viewModel;
    }

    public function departmentStatusAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $dep_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'dept_status' => $dep_status];
        $this->departmentstatus($data);
        $depListing = $this->getAllDepartmentList();
        $viewModel = new ViewModel(['data' => $depListing]);
        $viewModel->setTemplate('dashboard/user-role-manager/department-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    public function departmentstatus($data){
        $response=[];
        $url = $this->apiUrl() ."/department/updateStatus";
        $val = $this->put($url,$data);
        $JsonData = $val->getBody();
        $response = Json::decode($JsonData, true);
        return $response;
    }
    
    public function deleteDepartmentAction(){
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $id = $this->params()->fromQuery('data');  
        if(!empty($id)){
        $data = ['user_id' => $user_id, 'id' => $id, 'dept_status' => 2];
        $result= $this->departmentstatus($data);
        
        if ($result['response']['status']=='success') {
                    $msg = "Data Deleted Successfully..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else{
                    $msg = "Could Not Deleted..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
        }
    }


    public function getAllDepartmentList() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $getdata = '{"where":{"and": [{"created_by": "'.$userId.'"},{"status": {"neq": 2}}]}}';
        $getdata = rawurlencode($getdata);
        $url = $this->apiUrl() . "/department?&filter=" . $getdata;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        return $JsonData;
    }

    
    public function roleManagerListing ($userId)
    {
        $response=[];
        $url = $this->apiUrl() ."/role-assign-module/getAllRole?user_id=".$userId;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        if ((!empty($JsonData))) {
           $response = $JsonData['responsedata'];
        }
        return $response;
    }
    
     public function rollStatusAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $roll_status = $data['status'];
        $data = ['user_id' => $userId, 'id' => $id, 'role_assign_status' => $roll_status];
        $rollStatus= $this->updateRollStatus($data);
        
        $roleManagerListing=$this->roleManagerListing($userId);
        $viewModel = new ViewModel(['rolemanagerListing' => $roleManagerListing]);
        $viewModel->setTemplate('/dashboard/user-role-manager/user-role-manager-listing');
        $viewModel->setTerminal(true);
        
        return $viewModel;
    }
    public function updateRollStatus($data) {
        $response=[];
        $url = $this->apiUrl() . "/role-assign-module/updateStatus";
        $resp = $this->put($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }
    public function deleteManagerRoleAction()
    {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        
        $id = $this->params()->fromQuery('data');
        
        if(isset($id)){
        $data = ['user_id' => $userId, 'id' => $id, 'role_assign_status' => 2];
        $rollStatus= $this->updateRollStatus($data);
         
        if ($rollStatus['response']['affectedRows']==1) {
                    $msg = "Data Deleted Successfully..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else{
                    $msg = "Could Not Deleted..";
                    $this->redirect()->toRoute('userrolemanager', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
        }
        
        $viewModel = new ViewModel();

        return $viewModel;
    }
   

}

