<?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...
        $form = new UserRoleManagerForm();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
 
        $url = $this->apiUrl() ."/role-assign-module/getAllRole?user_id=".$userId;
//        echo'<pre>';print_r($url);die();
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        if ((!empty($JsonData))) {
            $userrolemanagerListing= $JsonData['responsedata'];
        }

        $viewModel = new ViewModel(['userrolemanagerListing' => $userrolemanagerListing]);
        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;

        $getdata = '{"where": {"created_by": "' . $userId . '"}}';
        $getdata = rawurlencode($getdata);
        $url = $this->apiUrl() . "/department?&filter=" . $getdata;

        $val = $this->get($url);

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

        if ((!empty($JsonData))) {
            $data = $JsonData;
        }

        $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 = "Departement details Updated Successfully..";

                    $this->redirect()->toRoute('userrolemanager', ['action' => 'department']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Departement 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() {

        $finaldata = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $vehicle_status = $data['status'];

        $data = ['user_id' => $user_id, 'id' => $id, 'vehicle_status' => $vehicle_status];

        //$this->updateVehicleStatus($data);
        $vehicleListing = $this->getAllDepartmentList($finaldata);
        $viewModel = new ViewModel(['data' => $vehicleListing]);
        $viewModel->setTemplate('dashboard/role-management/department-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }


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

}
