<?php
namespace App\Controller\Admin;
use App\Controller\Admin\Component\ImgComponent;
use Cake\Event\Event;
use Cake\Core\Configure;
use App\Controller\Admin\AppController;
use Cake\ORM\TableRegistry;
use Cake\View\Helper\HtmlHelper;
use Cake\View\Helper\FormHelper;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Auth\DefaultPasswordHasher;

/******************************************************************************
*File Name:	 AdminsController
*Creation Date: [09-02-2016]
*Modification Date: [09-02-2016]
*Author: [Raushan Suri]
*Author: [Modified By Girish Kumar sinha]
*Description: [This controller consist of function related to Admin.]
******************************************************************************/
class AdminsController extends AppController {

	//var $name = 'Admins';
	//public $components = array('Paginator','Email','Session','Auth','General');

	/********************************************************************************
	Function Name: beforeFilter
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: This function called before each function of the controller.
	*********************************************************************************/
	public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow(['login','logout', 'forgotpassword', 'reset']);
    }

	
	/********************************************************************************
	Function Name: login
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function for login action.
	*********************************************************************************/
	public function login() {
     $this->loadModel('Users');
		$this->viewBuilder()->layout('Admin/adminlogin');
        $this->set('layoutTitle', 'JBG APP::Admin Pannel');
        if($this->Auth->user('AnnuityAdmin.role') == 'Admin'){
            return $this->redirect($this->Auth->redirectUrl(['controller'=>'Admins', 'action'=>'dashboard']));
        }else{
            if($this->request->data){            
                $user = $this->Auth->identify();
                //echo "<pre>"; print_r($user); die('ddd');
                if (@$user['role'] =='Admin' || @$user['subAdmin'] == 1) {
                    $user1['AnnuityAdmin'] = $user;
                    $detail['AnnuityAdmin'] = $this->Users->get($user['id']);
                    $this->request->session()->write($detail);
                    
                    $articles = TableRegistry::get('Users');
                    $query = $articles->query();
                    $query->update()
                        ->set(['lastLogin' => date('Y-m-d H:i:s')])
                        ->where(['id' => 1])
                        ->execute();   
                    $this->Auth->setUser($user1);
                    $this->redirect(['controller'=>'Admins', 'action'=>'dashboard']);
                }else{
                    $this->Flash->error(__('Invalid username or password, try again'));    
                }
            } 
        }        
	}
    
    
    /********************************************************************************
	Function Name: login
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function for logout admin.
	*********************************************************************************/
    public function logout()
    {
        $this->request->session()->delete('AnnuityAdmin');
        return $this->redirect($this->Auth->logout());
    }
    
    
	/********************************************************************************
	Function Name: Dashboard
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to load admin dashboard.
	*********************************************************************************/
	public function dashboard() {
		$this->viewBuilder()->layout('Admin/admin');
        $layoutTitle = 'Dashboard';
        $this->set(compact('layoutTitle'));
        //if($this->Auth->user('SNSAdmin.role') != 'Admin' && empty($this->Auth->user('SNSAdmin.role'))){
        //    return $this->redirect($this->Auth->logout());
        //}
		if($this->Auth->user('AnnuityAdmin.role') != 'Admin' && $this->Auth->user('AnnuityAdmin.role') == ''){
            return $this->redirect($this->Auth->logout());
        }
        $this->loadModel('Categories');

        $Total_banner = $this->Categories->find('all')->count();
       
        $this->set(compact('Total_banner'));
        $this->set('layoutTitle', 'JBG APP::Admin Dashboard');
	}

	
    /********************************************************************************
	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 Admin detail.
	*********************************************************************************/
    public function edit($id = null)
     {
        //pr($this->Auth->user());
        $id = 1;
        $this->loadModel('Users');
        $layoutTitle = 'JBG APP :: Edit Admin Info';
        $this->set(compact('layoutTitle'));
        $this->viewBuilder()->layout('Admin/admin');
        $users = $this->Users->find()->where(['id' => $id])->first();
        if ($this->request->is(['patch', 'post', 'put'])) {
            $userimage = $this->request->data['profile_picture'];
												unset($this->request->data['profile_picture']);
            if(!empty($userimage['name'])){
														$filename = time() . $userimage['name'];
														$this->request->data['profile_picture'] = $filename;
												}	
            $users = $this->Users->patchEntity($users, $this->request->data,['validate' => 'edit']);
            $old_data = $this->Users->get($id);
												if(!empty($filename)){
													$oldfilename = $old_data->profile_picture;
												}
												$path = WWW_ROOT . 'img/uploads/users/original/';
            if ($this->Users->save($users)) {
                if (!empty($userimage) && $userimage['name'] != '') {	
                    @unlink(WWW_ROOT . 'img/uploads/users/original/'.$oldfilename);
                    @unlink(WWW_ROOT . 'img/uploads/users/thumb/'.$oldfilename);
                    move_uploaded_file($userimage['tmp_name'], $path.$filename);
                    $MyImageCom = new ImgComponent();
                    $MyImageCom->prepare("img/uploads/users/original/".$filename);
                    $MyImageCom->resize(150,100);
                    $MyImageCom->save("img/uploads/users/thumb/".$filename);	
                    $this->request->session()->write('AnnuityAdmin.profile_picture', $filename);
												}
                $this->request->session()->write('AnnuityAdmin.fullName', $this->request->data['fullName']);
                $this->request->session()->write('AnnuityAdmin.email', $this->request->data['email']);
                $this->Flash->success(__('The admin details has been updated.'));
                return $this->redirect(['controller' => 'Admins', 'action' => 'edit']);
            } else {                
                $this->Flash->error(__('The admin details could not be updated. Please, try again.'));
            }
        }
        $this->set(compact('users'));
    }

	
	
	/********************************************************************************
	Function Name: changepassword
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to change admin login password.
	*********************************************************************************/
	public function changepassword() {
		$this->loadModel('Users');
        $users = $this->Users->find()->where(['id' => $this->Auth->user('AnnuityAdmin.id')])->first();
        //if($this->Auth->user('SNSAdmin.role') != 'Admin' && empty($this->Auth->user('SNSAdmin.role'))){
        //    return $this->redirect($this->Auth->logout());
        //}
		if($this->Auth->user('AnnuityAdmin.role') != 'Admin' && $this->Auth->user('AnnuityAdmin.role') == ''){
            return $this->redirect($this->Auth->logout());
        }
		if(!empty($this->request->data)){
            $users = $this->Users->patchEntity($users, [
                    'old_password'  => $this->request->data['old_password'],
                    'password'      => $this->request->data['password1'],
                    'password1'     => $this->request->data['password1'],
                    'password2'     => $this->request->data['password2']
                ],
                ['validate' => 'password']
            );
            if ($this->Users->save($users)) {
                $this->Flash->success('Password has been changed successfully');
                $this->redirect('/admin/changepassword');
            }else{
                $this->Flash->error(__('Invalid old password entered.'));
            }
		}
        $this->viewBuilder()->layout('Admin/admin');
								$layoutTitle = 'JBG APP :: Change Password';
        $this->set(compact('layoutTitle'));
        $this->set(compact('users'));
	}

	/********************************************************************************
	Function Name: forgotpassword
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to send admin forget password mail.
	*********************************************************************************/
	public function forgotpassword() {
		$this->viewBuilder()->layout('Admin/adminlogin');
        //die('ddd');
		$this->loadModel('Users');
		//$this->User->recursive=-1;
		if(!empty($this->request->data)) {			
			$user = $this->Users->find()->where(['Users.email' => $this->request->data['email'], 'Users.role'=>'Admin'])->first();            
            if(empty($user))
			{
				$this->Flash->error(__('Email address does not exist.'));
			}else {
                //pr($user); die;
                    $token = $this->random_password(50);
                    $url = Configure::read('App.siteurl').'admin/Admins/reset/'.$token;
                    $url=wordwrap($url,1000);
                    //die;
                    $articles = TableRegistry::get('Users');
                    $query = $articles->query();
                    $query->update()
                        ->set(['reset_password_token' => $token])
                        ->where(['id' => 1])
                        ->execute();
                
                    $path = Configure::read('App.siteurl');
                    $click = '<a href="'.$url.'">click here</a>';
                    // $Email_variables = [
                    //     'fullname' => $user->firstname,
                    //     'click_here' => $click,
                    //     'link' => $url,
                    //     'templatemail' => Configure::read('App.adminEmail'),
                    //     'layoutTitle' => 'Admin forgotpassword',
                    //     'imagepath' => $path
                    // ];
                    // $mail_template='admin_forgotpassword';
                    // $mailto = $user->email;
                    // //$mailto ='Raushan Suri.kumar.newmediaguru@gmail.com';
                    // $subject ='JBG APP - Reset Password';
                    // $this->sendmail($Email_variables, $mail_template, $mailto, $subject, $mailcc = '');

                    $to = $user->email;
                    $to = 'raushan@mailinator.com';
                    $subject = 'JBG APP - Reset Password';
                    $message="Dear Admin";
                    $message.="<br><br> Hi let's reset password. Click the below link";
                    $message.='<br>: '.$click;
                    $message.='<br>';
                    $this->phpemail($to,$subject,$message);

                    $this->Flash->success(__('Reset password link has been successfully sent on your registered email.'));
                    $this->redirect(['controller' => 'Admins', 'action' => 'forgotpassword']);
			}
		}
        
        $layoutTitle = 'JBG APP :: Forget Password';
        $this->set(compact('layoutTitle'));
	}

	/********************************************************************************
	Function Name: reset
	*Type: Public function used as action of the controller
	*Input: No input
	*Author: Raushan Suri
	*Modified By: Raushan Suri
	*Output: Function to reset user login password.
	*********************************************************************************/
	public function reset($token=null){
        $this->loadModel('Users');
		$this->viewBuilder()->layout('Admin/adminlogin');
        //die('ddd');\
        //$token = '';
		if(!empty($token)){
			$this->set('token',$token);
            if($this->request->data){
                if($this->request->data['password1'] != $this->request->data['password2']){
                    $this->Flash->error(__('Confirm password does not match.'));
                    //$this->redirect(['controller' => 'Admins', 'action' => 'logout']);
                }elseif(strlen($this->request->data['password1']) < 5){
                    $this->Flash->error(__('Password length minmun 6 character.'));
                }else{
                    $users = $this->Users->find()->where(['Users.reset_password_token' => $token, 'Users.role' => 'Admin'])->first();
                    if(!empty($users)){
                        $password = (new DefaultPasswordHasher)->hash($this->request->data['password1']);
                            
                            $articles = TableRegistry::get('Users');
                            $query = $articles->query();
                            $query->update()
                                ->set(['password' => $password, 'reset_password_token' => ''])
                                ->where(['id' => $users->id])
                                ->execute();
                        $this->Flash->success(__('Password reset successfully.'));
                        $this->redirect(['controller' => 'Admins', 'action' => 'login']);
                    }else{
                        $this->Flash->error(__('This reset token has been expired.'));
                    }
                }
            }
		}else{
            $this->Flash->error(__('This reset token has been expired.'));
            $this->redirect(['controller' => 'Admins', 'action' => 'logout']);
        }
         $layoutTitle = 'JBG APP :: Reset Password';
        $this->set(compact('layoutTitle'));
	}
//end controller
}
