<?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 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();

        $url = $this->apiUrl() . "/module-manager";
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        //echo'<pre>';print_r($JsonData);die();
        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();

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

        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $postData = $request->getPost()->toArray();
                $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..";
                }

                $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() {
        $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;
    }

}
