<?php

namespace Dashboard\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Dashboard\Form\MasterModuleForm;
use Application\Controller\RestAPIClientController;
use Zend\Json\Json;
use Zend\Debug\Debug;
use Zend\Session\Container;
use Zend\View\Model\JsonModel;
use Dashboard\Model\Role;

class MasterModuleController extends RestAPIClientController {

    public function __construct() {
        $sessionContainer = new Container('userlogin');
        $this->userId = $sessionContainer->user_id;
        $this->roleModel = new Role();
    }

    /**
     * Index
     * @return ViewModel
     */
    public function indexAction() {
        $modulelisting = '';
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new MasterModuleForm();
        $val='{"order": "menu_order ASC"}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/module-manager?&filter=" . $val;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        if ((!empty($JsonData))) {
            $modulelisting = $JsonData;
        }

        $viewModel = new ViewModel(['modulelisting' => $modulelisting]);
        return $viewModel;
    }

    public function AddModuleAction() {

        $dashboard_module = $this->roleModel->MasterModules();
        //echo'<pre>';print_r($dashboard_module);die();
        /*if (!empty($dashboard_module)) {
            $optionArr = [];
            foreach ($dashboard_module as $key => $val) {
                $module_id = $val['module_id'];
                $parent_module = $val['module_name'];
                $optionArr[$parent_module]['label'] = $parent_module;
                $optionArr[$parent_module]['options'] = [];
                if (!empty($val['submenu'])) {
                    $submenuArr = [];
                    foreach ($val['submenu'] as $submenu) {
                        if ($module_id == $submenu['parent_id']) {
                            $optionArr[$parent_module]['options'][$submenu['module_id']] = $submenu['module_name'];
                        }
                    }
                }
            }
        }

         MasterModuleForm::$moduleOptions = $optionArr;
        $form = new MasterModuleForm();

                  */

        if (!empty($dashboard_module)) {
            $optionArr = [];
            foreach ($dashboard_module as $key => $val) {
                $module_id = $val['module_id'];
                $parent_module = $val['module_name'];
                $optionArr[$val['module_id']] = $val['module_name'];
                if (!empty($val['submenu'])) {
                    $submenuArr = [];
                    foreach ($val['submenu'] as $submenu) {
                        if ($module_id == $submenu['parent_id']) {
                            $optionArr[$submenu['module_id']] = '  ----'.$submenu['module_name'];
                        }
                    }
                }
            }
        }

        MasterModuleForm::$moduleOptions = $optionArr;
        $form = new MasterModuleForm();
        $request = $this->getRequest();
        $moduleId = $this->params()->fromQuery('id');
        if ($moduleId > 0) {
            $moduleDetails = $this->roleModel->getAllMasterModuleById($moduleId);
            $form->setData($moduleDetails);
            $form->get('parent_module')->setValue($moduleDetails['module_id']);
            $form->get('controller_name')->setValue($moduleDetails['controller']);
            $form->get('order')->setValue($moduleDetails['menu_order']);
            $form->get('namespace')->setValue($moduleDetails['namespace']);
        }

        if ($request->isPost()) {
            $form->setData($request->getPost());
            $postData = $request->getPost()->toArray();
            if (!empty($postData['module_id'])) {
                $form->getInputFilter()->get('parent_module')->setRequired(false);
            }

            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'parent_id' => ($postData['parent_module'] > 0) ? $postData['parent_module'] : 0,
                    'module_name' => $postData['module_name'],
                    'controller' => $postData['controller_name'],
                    'menu_order' => $postData['order'],
                    'action' => $postData['action'],
                    'url' => $postData['url'],
                    'icon_class' => $postData['icon_class'],
                    'status' => $postData['status'],
                ];
                if (empty($postData['module_id'])) {
                    $finalData['created_by'] = $this->userId;
                    $finalData['created_date'] = date('Y-m-d h:i:s');
                } else {
                    $finalData['modified_by'] = $this->userId;
                }

                if (empty($postData['module_id'])) {
                    $url = $this->apiUrl() . "/module-manager";
                    $msg = "Module details Added Successfully..";
                } else {
                    $val = '{"module_id": "' . $postData['module_id'] . '"}';
                    $val = rawurlencode($val);
                    $url = $this->apiUrl() . "/module-manager/update?where=" . $val;
                    $msg = "Module details Updated Successfully..";
                }
                //echo '<pre>';print_r($finalData);die();
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $this->redirect()->toRoute('master-module', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $this->redirect()->toRoute('master-module', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'moduleId' => $moduleId]);
        return $viewModel;
    }

    public function tabPositionAction() {
        $result = [];
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $res = json_decode($postData['data']);
            $readbleArray = $this->parseJsonArray($res);
            //echo'<pre>';print_r($readbleArray); die();
            $i=0;
            $finalData=[];
            foreach($readbleArray as $val){
             $i++;
            $finalData = [
                    'parent_id' => ($val['parentID'] > 0) ? $val['parentID'] : 0,
                    'menu_order' => $i,
                    'module_id' => $val['id'],
            ];
            $val = '{"module_id": "' . $val['id'] . '"}';
            $val = rawurlencode($val);
            //echo '<pre>';print_r($finalData);//die();
            $url = $this->apiUrl() . "/module-manager/update?where=" . $val;//die;
            $val = $this->post($url, $finalData);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);
            }
            if ($JsonData['count']>0) {
                $result = ["status" => true];
            } else {
                $result = ["status" => false];
            }
            $view = new JsonModel($result);
            return $view;
        }
    }

    public function tabPosition1Action() {
        $request = $this->getRequest();
        if ($request->isPost()) {

            $postData = $request->getPost()->toArray();
            $res = json_decode($postData['data']);
            $readbleArray = $this->parseJsonArray($res);
            echo'<pre>';print_r($readbleArray); die();


        }

        $viewModel = new ViewModel();
        return $viewModel;
    }

   public function parseJsonArray($jsonArray, $parentID = 0) {

        $return = array();
        foreach ($jsonArray as $subArray) {
            $returnSubSubArray = array();
            if (isset($subArray->children)) {
                $returnSubSubArray = $this->parseJsonArray($subArray->children, $subArray->id);
            }

            $return[] = array('id' => $subArray->id, 'parentID' => $parentID);
            $return = array_merge($return, $returnSubSubArray);
        }
        return $return;
    }

}
