<?php
namespace App\Controller\Admin;
use App\Controller\Admin\Component\ImgComponent;

use App\Controller\Admin\AppController;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
use Cake\Core\Configure;
use Cake\I18n\Time;
use Cake\View\Helper\TimeHelper;
use Cake\Datasource\ConnectionManager;

/******************************************************************************
Below two line to send the notification
******************************************************************************/
// echo "<pre>";
// print_r($_SERVER); die;
require '/home/demo4ev/public_html/jbgapp/webroot/google/vendor/autoload.php';
use Google\Auth\OAuth2;

/******************************************************************************
*File Name:	 DepartmentsController
*Creation Date: [11-02-2016]
*Modification Date: [11-02-2016]
*Author: [Raushan Suri]
*Author: [Modified By Raushan Suri]
*Description: [This controller consist of function related to Department.]
******************************************************************************/
class CategoriesController extends AppController
{

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow(['showprofile']);
    }

    
    /********************************************************************************
	Function Name: index
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to view all member list and search.
	*********************************************************************************/
    public function index()
    {
        $layoutTitle = 'JBG APP :: Manage Banner';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
        $limit = 30;//Configure::read('App.adminPageLimit');
        
        $this->paginate = [
            'limit' => $limit,
            'order' => [
                'Categories.created' => 'DESC'
            ],
        ];        
        $keyword = $this->request->query('keyword');
		$condition[] = ['Categories.id >'=>0];
		
        if($keyword != ''){
			$condition[] = [
				'OR' => [
					["Categories.name LIKE '%".$keyword."%'"],
					["Categories.link LIKE '%".$keyword."%'"],
				]				
			];
		}        
        $query = $this->Categories->find('all')->where($condition);       
        $categories = $this->paginate($query);
        $categories = $categories->toArray();
		//pr($categories);die;
        $this->set(compact('categories', 'limit'));
    }

	public function notificationlist()
    {
        $layoutTitle = 'JBG APP :: Manage Notification';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
        $limit = 30;//Configure::read('App.adminPageLimit');
        $this->loadModel('Notifications');
        $this->paginate = [
            'limit' => $limit,
            'order' => ['Notifications.created' => 'DESC'],
        ];        
        $keyword = $this->request->query('keyword');
		$condition[] = ['Notifications.id >'=>0];
		
        if($keyword != ''){
			$condition[] = [
				'OR' => [
					["Notifications.message LIKE '%".$keyword."%'"],
					["Notifications.userid LIKE '%".$keyword."%'"],
				]				
			];
		}        
        $query = $this->Notifications->find('all')->where($condition);       
        $notificationlist = $this->paginate($query);
        $notificationlists = $categories->toArray();
		//pr($categories);die;
        $this->set(compact('notificationlists', 'limit'));
    }

      
    /********************************************************************************
	Function Name: add
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to add hours.
	*********************************************************************************/
    public function add()
    {
        $this->loadModel('Partyworkers');
        $layoutTitle = 'JBG APP ::  Add Banner';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
		$this->loadModel('Users');
		
        $categories = $this->Categories->newEntity();        
        $parentClientList = $this->Categories->find('list', ['keyField' => 'id', 'valueField' => ['name', 'parentId']])
						//->where(['Categories.parentId'=>'0'])
                        ->order(['Categories.name'=>'ASC'])->toArray();
        
        $regex = "/;[1-9]*/";
        $replacement = " (Sub)";
        $fff = str_replace(";0", " (Main)", $parentClientList);
        
        $parentClientList = preg_replace($regex, $replacement, $fff);

        //pr($parentClientList);
        //die;
        if ($this->request->is('post')) {
            //pr($this->request->data); die;
			$userImage = @$this->request->data['image'];	
			unset($this->request->data['image']);			
			if(!empty($userImage['name'])){
				$filename = time() .'_'. $userImage['name'];
				$this->request->data['image'] = $filename;
			}
			
			$search  = array(' ', '.', '(', ')', '[', ']');
			$replace = array('-', '', '', '', '', '');
			$subject = $this->request->data('name');
			$STR = str_replace($search, $replace, $subject);
			$URL = strtolower($STR);
			$URL = $URL.'.html';
			
			
			$categories = $this->Categories->patchEntity($categories, $this->request->data, ['validate' => 'customer']);            
			$categories['created']  = date('Y-m-d H:i:s');
            $categories['status']   = 1;
            $categories['url']  = $URL;
			
			if ($this->Categories->save($categories)) {
				if(!empty($userImage) && $userImage['name'] != '') {
					$path = WWW_ROOT . 'img/uploads/category/';	                    
					move_uploaded_file($userImage['tmp_name'], $path.$filename);
					@chmod($path.$filename, 0777);
				}
				$this->Flash->success(__('Banner added successfully.'));
				return $this->redirect(['action' => 'index']);	
			}else{
				$this->Flash->error(__('Unable to add new banner, Please try fill all details.'));
			}
		}
        $this->set(compact('categories'));
    }
    
    
    
    
    /********************************************************************************
	Function Name: edit
	*Type: Public function used as action of the controller
	*Input: Member id
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to edit hours.
	*********************************************************************************/
    public function edit($id)
    {
        $layoutTitle = 'JBG APP :: Edit Category';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
		$this->loadModel('Users');
		
         $categories = $this->Categories->newEntity();        
        $parentClientList = $this->Categories->find('list', ['keyField' => 'id', 'valueField' => ['name', 'parentId']])
						->where(['Categories.id <>'=>$id])
                        ->order(['Categories.name'=>'ASC'])->toArray();               
		
        $regex = "/;[1-9]*/";
        $replacement = " (Sub)";
        $fff = str_replace(";0", " (Main)", $parentClientList);
        
        $parentClientList = preg_replace($regex, $replacement, $fff);
        
        
        $categories = $this->Categories->find()->where(['Categories.id' => $id])->first();//fields name in contain[] with coma
       
        if ($this->request->is(['patch', 'post', 'put'])) {
            if($this->request->data('parentClientYESNO') == 1){
                $this->request->data['parentId'] = '0';
            }
			
			//**************ICON Image Process Start**************************
			$userImage = @$this->request->data['image'];	
			unset($this->request->data['image']);
			unset($categories['image']);
			
			$old_data = $this->Categories->get($id);            			
			if(!empty($userImage['name'])){
				$filename = time() .'_'. $userImage['name'];
				$categories['profile_picture'] = $filename;
				$this->request->data['image'] = $filename;
			}
			//**************ICON Image Process End**************************
			
			//**************ICON Image Process Start**************************
			$userImage2 = @$this->request->data['bigImage'];	
			unset($this->request->data['bigImage']);
			unset($categories['bigImage']);
			
			if(!empty($userImage2['name'])){
				$filename2 = time() .'_'. $userImage2['name'];
				$this->request->data['bigImage'] = $filename2;
			}
			//**************ICON Image Process End**************************
			
			$search  = array(' ', '.', '(', ')', '[', ']');
			$replace = array('-', '', '', '', '', '');
			$subject = $this->request->data('name');
			$STR = str_replace($search, $replace, $subject);
			$URL = strtolower($STR);
			$URL = $URL.'.html';

			$categories = $this->Categories->patchEntity($categories, $this->request->data, ['validate' => 'customer']);
			//$categories['parentId']  = ($this->request->data('parentId') == '') ? 0 : $this->request->data('parentId');
			$categories['url']  = $URL;
			if ($this->Categories->save($categories)) {
				if (!empty($userImage) && $userImage['name'] != '') {
					$path = WWW_ROOT . 'img/uploads/category/';	
					@unlink(WWW_ROOT . 'img/uploads/category/'.$old_data->image);
					move_uploaded_file($userImage['tmp_name'], $path.$filename);
					@chmod($path.$filename, 0777);
					
				}
				if (!empty($userImage2) && $userImage2['name'] != '') {
					$path = WWW_ROOT . 'img/uploads/category/';	
					@unlink(WWW_ROOT . 'img/uploads/category/'.$old_data->bigImage);
					move_uploaded_file($userImage2['tmp_name'], $path.$filename2);
					@chmod($path.$filename2, 0777);
					
				}
				$this->Flash->success(__('The Categories information updated successfully.'));
				return $this->redirect(['action' => 'index']);
			} else {
				$users['profile_picture'] = $old_data->image;
				$this->Flash->error(__('Categories information could not be saved. Please try again later.'));
			}
        }
				
        $this->set(compact('categories', 'parentClientList'));
    }
    
    
    /********************************************************************************
	Function Name: edit
	*Type: Public function used as action of the controller
	*Input: Member id
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to delete hours permanently.
	*********************************************************************************/
    public function delete($id = null)
    {
        $users = $this->Categories->get($id);
        if ($this->Categories->delete($users)) {
			@unlink(WWW_ROOT . 'img/uploads/category/'.$users->image);
            $this->Flash->success(__('Category has been deleted.'));
        } else {
            $this->Flash->error(__('Category could not be deleted. Please, try again.'));
        }
        return $this->redirect(['controller' => 'Categories', 'action' => 'index']);
    }
    
    /********************************************************************************
	Function Name: deleteall
	*Type: Public function used as action of the controller
	*Input: by Post Methods
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to delete all record which you have been send
	*********************************************************************************/
    public function deleteall()
    {
        $this->Categories->deleteAll(['Categories.id IN' => $this->request->data]);
        $this->Flash->success(__('Categories has been deleted.'));
        return $this->redirect(['controller' => 'Categories', 'action' => 'index']);
    }
    
    /********************************************************************************
	Function Name: status
	*Type: Public function used as action of the controller
	*Input: Member id
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to update hours status.
	*********************************************************************************/
    public function status($id){
		$users = $this->Categories->get($id);
		$status = '1';
		$msg = 'activated';
		if($users->status == '1'){
			$status = '0';
			$msg = 'deactivated';
		}
		
		$articles = TableRegistry::get('Categories');
		$query = $articles->query();
		$query->update()
			->set(['status' => $status])
			->where(['id' => $id])
			->execute();
		$this->Flash->success(__('Categories has been '.$msg.' successfully.'));
		return $this->redirect(['controller' => 'Categories', 'action' => 'index']);
	}
    
    
    /********************************************************************************
	Function Name: details
	*Type: Public function used as action of the controller
	*Input: Member id
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to view hours information.
	*********************************************************************************/
    public function details($id){
        $layoutTitle = 'JBG APP ::  Category Details';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');       
		$details = $this->Categories->find()->where(['Categories.id' => $id])->contain(['ParentCategory'])->first();
        if(!empty($details)){
            $this->set(compact('details'));
        }else{
            $this->Flash->error(__('Category doesnot exist.'));
            return $this->redirect(['controller' => 'Categories', 'action' => 'index']);
        }
	}
	
    
    /********************************************************************************
	Function Name: details
	*Type: Public function used as action of the controller
	*Input: Member id
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to view hours information.
	*********************************************************************************/
    public function noofitems($id){
        $layoutTitle = 'JBG APP ::  Party items';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('');        
		$this->loadModel('Partyworkers');
        $serviceListStatus = $this->Partyworkers->find('list', ['keyField' => 'serviceName', 'valueField' => ['servicepackesCompleteStatus']])
            ->where(['Partyworkers.partyDate'=> date('Y-m-d')])
            ->order(['Partyworkers.servicepackesCompleteStatus'=>'DESC'])->toArray();
        $this->set(compact('serviceListStatus'));
        
	}


	public function sendnotification(){

        $layoutTitle = 'JBG APP-Send Notification';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
		$this->loadModel('Users');
       
        if ($this->request->is('post')) {
            
			echo "<pre>"; print_r($this->request->data);
			
			$serviceAccount = json_decode(file_get_contents('/home/demo4ev/public_html/jbgapp/webroot/firebase-service-account.json'), true);
			$projectId = $serviceAccount['project_id'];
			
			// List of device tokens
			$deviceTokens = [
				'cXxfGm6JQqGujm0PE10Xg3:APA91bEvLUMDc5ntrl3zPyCF6q_Ro2-mJLTpgRhD3CLG5fbZPMljW9-Yjbpok6xHF6vjhv-I-RBdMnf2_VvACeVV_86YpBoHa4qnE0yzoAbfM8qVu5PaKeU'
			];
			
			// Set up OAuth2
			$oauth = new OAuth2([
				'audience' => 'https://oauth2.googleapis.com/token',
				'issuer' => $serviceAccount['client_email'],
				'signingAlgorithm' => 'RS256',
				'signingKey' => $serviceAccount['private_key'],
				'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
			]);
			
			$accessToken = $oauth->fetchAuthToken()['access_token'];
			$url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";
			$headers = [
				'Authorization: Bearer ' . $accessToken,
				'Content-Type: application/json',
			];
			die;
			// // Notification content
			// $notification = [
			// 	'title' => 'Hello Users',
			// 	'body' => 'This is a broadcast notification!',
			// ];

			// // Data payload
			// $dataPayload = [
			// 	'name' => 'Raushan',
			// ];

			// foreach ($deviceTokens as $token) {
			// 	$payload = [
			// 		'message' => [
			// 			'token' => $token,
			// 			'notification' => $notification,
			// 			'data' => $dataPayload,
			// 		]
			// 	];

			// 	$ch = curl_init();
			// 	curl_setopt($ch, CURLOPT_URL, $url);
			// 	curl_setopt($ch, CURLOPT_POST, true);
			// 	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			// 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			// 	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
			// 	$response = curl_exec($ch);
			// 	curl_close($ch);

			// 	echo "Sent to $token:\n$response\n\n";
			//	die;
			//}



			$this->Flash->success(__('Notification sent successfully.'));
			return $this->redirect(['action' => 'sendnotification']);	
		}else{
			//echo "<pre>"; print_r($this->request->data); die;
			//$this->Flash->error(__('Unable to send notification, Please try fill all details.'));
		}
		$categories = [];
        $this->set(compact('categories'));
    }
	
}