<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */


namespace App\Controller;


use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Core\Configure;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Mailer\Email;
use DateTimeZone;

//use Cake\Controller\Controller\Component\AuthComponent;



/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash'); 
        $this->loadModel('Notify');
         $this->set('base_url',Router::url('/', true));
       

         $this->loadComponent('Auth', [
           'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'username',]
                ]
            ],
            'loginRedirect' => [
                'controller' => 'users',
                'action'     => 'dashboard'
            ],
            'logoutRedirect' => [
                'controller' => 'users',
                'action'     => 'login'
            ],
            
            'storage' => 'Session'
        ]);

        /*
         * Enable the following components for recommended CakePHP security settings.
         * see http://book.cakephp.org/3.0/en/controllers/components/security.html
         */
        //$this->loadComponent('Security');
        //$this->loadComponent('Csrf');
    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Network\Response|null|void
     */

    /*public function json($data){
      $this->RequestHandler->respondAs('json');
      $this->response->type('application/json');
      $this->autoRender = false;
      echo json_encode($data);
    }*/


     public function checkuserpermission($menuID,$userid,$checkaction,$current_action_name){
      $this->loadModel('UserRights');
      if($userid!=''){
          if($menuID=='' && !$this->request->is('ajax')){
            $this->redirect(array('controller' => 'Users', 'action' => 'notauthenticate'));
          }
      }
      $userright_arr = $this->UserRights->find('all', array('conditions' => array('UserRights.menu_id' => $menuID, 'UserRights.user_id' => $userid)))->toArray();     
   
       $checkdefaultaction=array('add','edit','index','view','delete');
       $allowactionarr=array();
       if ($userright_arr) {
            if (in_array($current_action_name, $checkdefaultaction)) {
                if ($userright_arr[0]['add_r']) {
                    $allowactionarr[] = 'add';
                }
                if ($userright_arr[0]['edit']) {
                    $allowactionarr[] = 'edit';
                }
                if ($userright_arr[0]['delete_r']) {
                    $allowactionarr[] = 'delete';
                }
                if ($userright_arr[0]['details_r']) {                  
                    $allowactionarr[] = 'view';
                } 
                if ($userright_arr[0]['view_r']) {                  
                    $allowactionarr[] = 'index';
                }
               
                if (!in_array($current_action_name, $allowactionarr)) {                   
                    $this->redirect(array('controller' => 'Users', 'action' => 'notauthenticate'));                      
                }
             }
             
             return $userright_arr;
         }
     }
     public function beforeFilter(Event $event) {
        

        $this->Auth->allow('login', 'Apicalls', 'ApiManufacturing');
        $this->response->disableCache();        
        $this->loadModel('Menus');
        $this->loadModel('Ipallocation');
        $this->loadModel('User');
                  
        $userid = $this->Auth->user('id');  
        $username = $this->Auth->user('username');
        $controller_name =$this->name;
        $userright_arr=array();
        $menuCondition = array();
        $menuCondition['UserRights.user_id'] = $userid;
        $menuCondition['UserRights.view_r'] = 1;
        $sideBarMenus = $this->Menus->find('all')
                                ->join([
                                      'UserRights' => [
                                          'table' => 'user_rights',
                                          'type' => 'INNER',
                                          'conditions' => 'UserRights.menu_id = Menus.id'
                                      ]
                                  ])
                                ->where($menuCondition)
                                ->order('Menus.sort')
                                ->toArray();
           
        $menuID =  $this->searchForId($controller_name,$sideBarMenus);

        $current_action_name = $this->request->params['action'];
        $check = $controller_name . '/' . $current_action_name;
        
        $allowurltermp = array('Users/notauthenticate', 'Users/logout', 'Users/login','Users/dashboard');
        
        if (in_array($check, $allowurltermp)) {
            
        } else {               
            $permissondata = $this->checkuserpermission($menuID, $userid, $check, $current_action_name);              
            $userright_arr = $permissondata;                
        }    

        #static variables
        $s3url = 'https://assignmentfile.s3.eu-west-2.amazonaws.com/workolics/';
        $services = [
            'Assignment | Coursework | Term Paper',
            'Plagiarism Report',
            'Case Study | Report Writing',
            'Essay',
            'Dissertation & PHD Thesis',
            'Business Plan',
            'Online Exam | Question based test Papers',
            'Multiple Choice Questions',
            'Editing | Proofreading | Paraphrasing',
            'PowerPoint Presentation',
            'Poster',
            'Leaflet',
            'Summary Writing',
            'Portfolio',
            'Resume / CV Services'
        ];

        $website = ['GAH', 'GAH_AU', 'IAH', 'IAH_AU', 'AP', 'AD'];

        // $role = [1 => "Admin", 2 => "Lead manager", 3 => "SEO Admin", 4 => "SEO User"];

        $timezone = DateTimeZone::listIdentifiers(DateTimeZone::ALL);

        $website = ['GAH', 'GAH_AU', 'IAH', 'IAH_AU', 'AP', 'AD','Other'];

        $role[] = TableRegistry::get('Role')->find('list')->toArray();
        
        // $role = [1 => "Admin", 2 => "Lead manager", 3 => "SEO Admin", 4 => "SEO User"];
        
        $degree = ["BA","MA","BBA","MBA","M.Tech","B.Tech","Other"];

        $category = TableRegistry::get('Category')->find('list')->where(['status'=>1])->toArray();
        $category[0]='Both';
        
        $chatNotify = TableRegistry::get('Chats')->find('all')->contain(['Projects','Freelancers'])->where(['Chats.view'=>0,'Chats.from_id'=>0])->order('Chats.id desc')->toArray();
        $country  =array(
            '+91' => 'India',
            '+44' => 'United Kingdom',
            '+1' => 'United States',
            '+1' => 'Canada',
            '+61' => 'Australia',
            '+64' => 'New Zealand',
            '+60' => 'Malaysia',
            '+971' => 'United Arab Emirates',
            '+93' => 'Afghanistan',
            '+355' => 'Albania',
            '+213' => 'Algeria',
            '+1-684' => 'American Samoa',
            '+376' => 'Andorra',
            '+244' => 'Angola',
            '+1-264' => 'Anguilla',
            '+672' => 'Antarctica',
            '+1-268' => 'Antigua and Barbuda',
            '+54' => 'Argentina',
            '+374' => 'Armenia',
            '+297' => 'Aruba',
            '+43' => 'Austria',
            '+994' => 'Azerbaijan',
            '+1-242' => 'Bahamas',
            '+973' => 'Bahrain',
            '+880' => 'Bangladesh',
            '+1-246' => 'Barbados',
            '+375' => 'Belarus',
            '+32' => 'Belgium',
            '+501' => 'Belize',
            '+229' => 'Benin',
            '+1-441' => 'Bermuda',
            '+975' => 'Bhutan',
            '+591' => 'Bolivia',
            '+387' => 'Bosnia and Herzegovina',
            '+267' => 'Botswana',
            '+47' => 'Bouvet Island',
            '+55' => 'Brazil',
            '+246' => 'British Indian Ocean Territory',
            '+673' => 'Brunei Darussalam',
            '+359' => 'Bulgaria',
            '+226' => 'Burkina Faso',
            '+257' => 'Burundi',
            '+855' => 'Cambodia',
            '+237' => 'Cameroon',
            '+238' => 'Cape Verde',
            '+1-345'=> 'Cayman Islands',
            '+236' => 'Central African Republic',
            '+235' => 'Chad',
            '+56' => 'Chile',
            '+86' => 'China',
            '+61' => 'Christmas Island',
            '+61' => 'Cocos (Keeling) Islands',
            '+57' => 'Colombia',
            '+269' => 'Comoros',
            '+242' => 'Congo',
            '+682' => 'Cook Islands',
            '+506' => 'Costa Rica',
            '+225' => 'Cote D\'Ivoire',
            '+385' => 'Croatia',
            '+53' => 'Cuba',
            '+357' => 'Cyprus',
            '+420' => 'Czech Republic',
            '+45' => 'Denmark',
            '+253' => 'Djibouti',
            '+1-767' => 'Dominica',
            '+1-809' => 'Dominican Republic(1-809)',
            '+1-829' => 'Dominican Republic(1-829)',
            '+1-849' => 'Dominican Republic(1-849',
            '+670' => 'East Timor',
            '+593' => 'Ecuador',
            '+20' => 'Egypt',
            '+503' => 'El Salvador',
            '+240' => 'Equatorial Guinea',
            '+291' => 'Eritrea',
            '+372' => 'Estonia',
            '+251' => 'Ethiopia',
            '+500' => 'Falkland Islands (Malvinas)',
            '+298' => 'Faroe Islands',
            '+679' => 'Fiji',
            '+358' => 'Finland',
            '+33' => 'France (Metropolitan)',
            '+594' => 'French Guiana',
            '+689' => 'French Polynesia',
            '+262' => 'French Southern Territories',
            '+241' => 'Gabon',
            '+220' => 'Gambia',
            '+995' => 'Georgia',
            '+49' => 'Germany',
            '+233' => 'Ghana',
            '+350' => 'Gibraltar',
            '+30' => 'Greece',
            '+299' => 'Greenland',
            '+1-473' => 'Grenada',
            '+590' => 'Guadeloupe',
            '+1-671' => 'Guam',
            '+502' => 'Guatemala',
            '+224' => 'Guinea',
            '+245' => 'Guinea-Bissau',
            '+592' => 'Guyana',
            '+509' => 'Haiti',
            '+672' => 'Heard and Mc Donald Islands',
            '+504' => 'Honduras',
            '+852' => 'Hong Kong',
            '+36' => 'Hungary',
            '+354' => 'Iceland',
            '+62' => 'Indonesia',
            '+98' => 'Iran',
            '+964' => 'Iraq',
            '+353' => 'Ireland',
            '+972' => 'Israel',
            '+39' => 'Italy',
            '+1-876' => 'Jamaica',
            '+81' => 'Japan',
            '+962' => 'Jordan',
            '+7' => 'Kazakhstan',
            '+254' => 'Kenya',
            '+686' => 'Kiribati',
            '+850' => 'North Korea',
            '+82' => 'Republic of Korea',
            '+965' => 'Kuwait',
            '+996' => 'Kyrgyzstan',
            '+856' => 'Laos',
            '+371' => 'Latvia',
            '+961' => 'Lebanon',
            '+266' => 'Lesotho',
            '+231' => 'Liberia',
            '+218' => 'Libyan Arab Jamahiriya',
            '+423' => 'Liechtenstein',
            '+370' => 'Lithuania',
            '+352' => 'Luxembourg',
            '+853' => 'Macau',
            '+389' => 'FYROM',
            '+261' => 'Madagascar',
            '+265' => 'Malawi',
            '+960' => 'Maldives',
            '+223' => 'Mali',
            '+356' => 'Malta',
            '+692' => 'Marshall Islands',
            '+596' => 'Martinique',
            '+222' => 'Mauritania',
            '+230' => 'Mauritius',
            '+262' => 'Mayotte',
            '+52' => 'Mexico',
            '+691' => 'Federated States of Micronesia',
            '+373' => 'Republic of Moldova',
            '+377' => 'Monaco',
            '+976' => 'Mongolia',
            '+1-664' => 'Montserrat',
            '+212' => 'Morocco',
            '+258' => 'Mozambique',
            '+95' => 'Myanmar',
            '+264' => 'Namibia',
            '+674' => 'Nauru',
            '+977' => 'Nepal',
            '+31' => 'Netherlands',
            '+599' => 'Netherlands Antilles',
            '+687' => 'New Caledonia',
            '+505' => 'Nicaragua',
            '+227' => 'Niger',
            '+234' => 'Nigeria',
            '+683' => 'Niue',
            '+672' => 'Norfolk Island',
            '+1-670' => 'Northern Mariana Islands',
            '+47' => 'Norway',
            '+968' => 'Oman',
            '+92' => 'Pakistan',
            '+680' => 'Palau',
            '+507' => 'Panama',
            '+675' => 'Papua New Guinea',
            '+595' => 'Paraguay',
            '+51' => 'Peru',
            '+63' => 'Philippines',
            '+64' => 'Pitcairn',
            '+48' => 'Poland',
            '+351' => 'Portugal',
            '+1-787' => 'Puerto Rico(1-787)',
            '+1-939' => 'Puerto Rico(1-939)',
            '+974' => 'Qatar',
            '+262' => 'Reunion',
            '+40' => 'Romania',
            '+7' => 'Russian Federation',
            '+250' => 'Rwanda',
            '+1-869' => 'Saint Kitts and Nevis',
            '+1-758' => 'Saint Lucia',
            '+1-784' => 'Saint Vincent and the Grenadines',
            '+685' => 'Samoa',
            '+378' => 'San Marino',
            '+239' => 'Sao Tome and Principe',
            '+966' => 'Saudi Arabia',
            '+221' => 'Senegal',
            '+248' => 'Seychelles',
            '+232' => 'Sierra Leone',
            '+65' => 'Singapore',
            '+421' => 'Slovak Republic',
            '+386' => 'Slovenia',
            '+677' => 'Solomon Islands',
            '+252' => 'Somalia',
            '+27' => 'South Africa',
            '+500' => 'South Georgia & South Sandwich Islands',
            '+34' => 'Spain',
            '+94' => 'Sri Lanka',
            '+290' => 'St. Helena',
            '+508' => 'St. Pierre and Miquelon',
            '+249' => 'Sudan',
            '+597' => 'Suriname',
            '+47' => 'Svalbard and Jan Mayen Islands',
            '+268' => 'Swaziland',
            '+46' => 'Sweden',
            '+41' => 'Switzerland',
            '+963' => 'Syrian Arab Republic',
            '+886' => 'Taiwan',
            '+992' => 'Tajikistan',
            '+255' => 'Tanzania',
            '+66' => 'Thailand',
            '+228' => 'Togo',
            '+690' => 'Tokelau',
            '+676' => 'Tonga',
            '+1-868' => 'Trinidad and Tobago',
            '+216' => 'Tunisia',
            '+90' => 'Turkey',
            '+993' => 'Turkmenistan',
            '+1-649' => 'Turks and Caicos Islands',
            '+688' => 'Tuvalu',
            '+256' => 'Uganda',
            '+380' => 'Ukraine',
            '+1-340' => 'United States Minor Outlying Islands',
            '+598' => 'Uruguay',
            '+998' => 'Uzbekistan',
            '+678' => 'Vanuatu',
            '+379' => 'Vatican City State (Holy See)',
            '+58' => 'Venezuela',
            '+84' => 'Viet Nam',
            '+1-284' => 'Virgin Islands British',
            '+1-340' => 'Virgin Islands U.S',
            '+681' => 'Wallis and Futuna Islands',
            '+212' => 'Western Sahara',
            '+967' => 'Yemen',
            '+243' => 'Democratic Republic of Congo',
            '+260' => 'Zambia',
            '+263' => 'Zimbabwe',
            '+44-1534' => 'Jersey','code',
            '+44-1481' => 'Guernsey',
            '+382' => 'Montenegro' ,
            '+381' => 'Serbia',
            '+358' => 'Aaland Islands',
            '+599' => 'Bonaire, Sint Eustatius and Saba',
            '+358' => 'Curacao',
            '+970' => 'Palestinian Territory, Occupied',
            '+211' => 'South Sudan',
            '+590' => 'St. Barthelemy',
            '+590' => 'St. Martin (French part)',
            '+34' => 'Canary Islands',
        );
        
        // S3
        // define('awsAccessKey', 'AKIAJUVAD3BUXJLTVH3A');
        define('awsAccessKey', 'AKIA35CHMFFCFIRKBNPM');
        // define('awsSecretKey', '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');
        define('awsSecretKey', 'vwlao3CXT7vtAqBm2329YsBKH5jZcAfkrEGlD9ZB');
        define('bucketName', 'assignmentfile');
        define('s3url', 'https://assignmentfile.s3.eu-west-2.amazonaws.com/workolics/');
        define('region', 'eu-west-2');
        
        // $projectStatus = [
        //     'Disable','RTA','Allotted','In process','Clarification','Draft','Feedback','Accepted','Delivered','Cancelled'
        // ];
        $projectStatus= TableRegistry::get('ProjectStatus')->find('list')->toArray();
    
        $this->set(compact('userright_arr','sideBarMenus','username','s3url','services','website','role','country','degree','category','timezone','projectStatus','chatNotify'));
    }

    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) && in_array($this->response->type(), ['application/json', 'application/xml'])) {
            $this->set('_serialize', true);
        }
    }
     public function searchForId($controller, $array) {
      
        foreach ($array as $key => $val) {
                 if ($val['controller'] === $controller && $val['name']!=='Dashboard') {
                        return $val['id'];
                 }
        }
        return null;
    }
}
