<?php

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Session\Container;
use Application\Controller\RestAPIClientController;

class Module {

    public function onBootstrap(MvcEvent $e) {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);



        $eventManager->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($event) {
            $hostname = $_SERVER['HTTP_HOST'];        
            //$validLicense = $this->validDomainLicense($event,$hostname);
            /*if($validLicense){                
                $response = $event->getResponse();
                $response->getHeaders()->addHeaderLine('Location', '/contact-us');
                  $response->setStatusCode(302);
                
                 exit();
               //return $controller->redirect()->toUrl('/contact-us');
            }*/
            $controller = $event->getTarget();
            $controllerName = get_class($controller);
           // echo $action = $this->params('action');die;
            $moduleNamespace = substr($controllerName, 0, strpos($controllerName, '\\'));

            if(in_array($moduleNamespace, array('Dashboard'))){
                $configs = $event->getApplication()->getServiceManager()->get('config');
                $session = new Container('userlogin');
                $user_id = isset($session->userData['user_id']) ? $session->userData['user_id'] : '';
                $roleId = isset($session->userData['role_id']) ? $session->userData['role_id'] : '';
                $usertypeId = isset($session->userData['user_type_id']) ? $session->userData['user_type_id'] : '';
                if ($user_id == '') {
                    $response = $event->getResponse();
                    $response->setStatusCode(302);
                    $response->getHeaders()->addHeaderLine('Location', '/');
                } else {
                    // Check user module access authtication //
                    $accessFilter = $this->moduleAuthication($event, $usertypeId, $controllerName);

                    if (!$accessFilter) {
                        //$response = $event->getResponse();
                        //$response->setStatusCode(302);
                        //$response->getHeaders()->addHeaderLine('Location', '/dashboard');
                    }
                }
            }


            if (isset($configs['moduleLayouts'][$moduleNamespace])) {
                $controller->layout($configs['moduleLayouts'][$moduleNamespace]);
                $controller->layout()->user_id = $user_id;
            }
        }, 100);
    }


    public function getConfig() {
        return include __DIR__ . '/../config/module.config.php';
    }


    public function moduleAuthication($event,$roleId,$controllerName){
        if($roleId!=''){
            $api = new RestAPIClientController();
            $configs = $event->getApplication()->getServiceManager()->get('config');
            $apiUrl = $configs['api']['url'];
            $url = $apiUrl . '/role-assign-module/getAssignModuleByusertypeid?&user_type_id='. $roleId;
            $resp = $api->get($url);

            $menuData = json_decode($resp->getBody(),true);
            if (isset($menuData) && !empty($menuData['responsedata']))
            {
                $accessControllerName = array_column($menuData['responsedata'],'namespace');
                //echo '<pre>';print_r($controllerName);die();
                if(!in_array($controllerName,$accessControllerName)){
                    return false;
                }else{
                    return true;
                }
            }
        }
    }
    
    /* Get Domain Name Valid License */
    public function validDomainLicense($event,$hostname){        
        $api = new RestAPIClientController();
        $configs = $event->getApplication()->getServiceManager()->get('config');
        $apiUrl = $configs['api']['url'];
        $url = $apiUrl . '/license/getDomainLicenseKey?domain_name='.$hostname;           
        $resp = $api->get($url);
        $domain_details = json_decode($resp->getBody(),true);
        if($domain_details['responsedata']['status']=='success'){
            $result =  $domain_details['responsedata']['data'][0];            
            if($result['license_start_date'] <= date('Y-m-d') && $result['license_end_date'] >= date('Y-m-d')){               
                return true;
            }else{               
                return false;
            }            
        }
    }
    

}