<?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\Core\Configure;
use Cake\View\Helper\HtmlHelper;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Routing\Router;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\TableRegistry;
/**
 * Static content controller
 *
 * This controller will render views from Template/Pages/
 *
 * @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
 */
class UsersController extends AppController
{

    /**
     * Displays a view
     *
     * @return void|\Cake\Network\Response
     * @throws \Cake\Network\Exception\NotFoundException When the view file could not
     *   be found or \Cake\View\Exception\MissingTemplateException in debug mode.
     */
    public function signup()
    {
        $this->viewBuilder()->layout('pages');
        $layoutTitle = 'Freedom Giving:: Signup';
		$url = Router::url('/', true);
		$breadcum = [
					 'Title' => 'SIGN IN/SIGN UP',
					 'URL'=>[
							   'Home' => $url,
							   'Sign in/Sign up' => $url.'contact'
							]
					 ];
		if($this->request->session()->read('FreedomUsers.role') == 'Member'){
			return $this->redirect(['controller' => 'Users', 'action' => 'dashboard']); 
		}
        if($this->request->data){
			$this->loadModel('Users');
			$usr = $this->Users->find()->where(['Users.email' => $this->request->data('email')])->first();
			
			if(!empty($usr)){
				echo '<span class="contactresponse" style="color:red">Your email address already registered.</span>';
			}else{
				$users = $this->Users->newEntity();
				$users = $this->Users->patchEntity($users, $this->request->data, ['validate' => false]);            
				$users['created'] = date('Y-m-d H:i:s');
				$users['username'] = $this->request->data('email');
				$users['status'] = '1';
				$users['role'] = 'Member';
				
				//$path = WWW_ROOT . 'img/uploads/feature/original/';
				if ($this->Users->save($users)) {
					echo '<span class="contactresponse" style="color:green">You registered successfully.</span>';
				}
			}
			die;
		}
		$this->set(compact('layoutTitle', 'breadcum'));
    }
    
    public function login($slug=NULL)
    {
        $this->viewBuilder()->layout('pages');
        
        if($this->request->data){
			//pr($this->request->data); die;
			$this->loadModel('Users');
			$usr = $this->Users->find()->where(['Users.email' => $this->request->data('email')])->first();
			if(!empty($usr)){
				$check = (new DefaultPasswordHasher)->check($this->request->data('password'), $usr->password);
				if($check && $usr->status == 1){
					$userdetail['FreedomUsers'] = $usr;
					$this->request->session()->write($userdetail);
					echo "success";
				}else{
					echo '<span class="loginResponse" style="color:red">Username or password is wrong.</span>';
				}
			}else{
				echo '<span class="loginResponse" style="color:red">Username or password is wrong.</span>';
			}
			die;
		}
    }
	
	function dashboard(){
		$this->viewBuilder()->layout('pages');
		$layoutTitle = 'Freedom Giving:: Dashboard';
		$url = Router::url('/', true);
		$breadcum = [
			'Title' => 'DASHBOARD',
			'URL'=>[
					  'Home' => $url,
					  'DASHBOARD' => $url.'dashboard'
				   ]
			];
		if($this->request->session()->read('FreedomUsers.role') == 'Member'){
			$this->loadModel('Users');
			$users = $this->Users->find()->Where(['Users.id' => $this->request->session()->read('FreedomUsers.id')])->first();
			
			
		}else{
			return $this->redirect(['controller' => 'Users', 'action' => 'signup']); 
		}
		
		$this->set(compact('layoutTitle', 'breadcum', 'users'));
	}
    
	
	function editprofile(){
		$this->viewBuilder()->layout('pages');
		$layoutTitle = 'Freedom Giving:: Edit Profile';
		$url = Router::url('/', true);
		$breadcum = [
			'Title' => 'EDIT PROFILE',
			'URL'=>[
					  'Home' => $url,
					  'Dashboard' => $url.'dashboard',
					  'EDIT PROFILE' => $url.'editprofile'
				   ]
			];
		if($this->request->session()->read('FreedomUsers.role') != 'Member'){
			return $this->redirect(['controller' => 'Users', 'action' => 'signup']);
		}
		$this->loadModel('Users');
		if($this->request->data){
			//pr($this->request->data);die;
			$articles = TableRegistry::get('Users');
			$query = $articles->query();
			$query->update()
				->set(['fullName' => $this->request->data('fullName'), 'dob' => $this->request->data('dob'), 'address' => $this->request->data('address'), 'contactNumber'=>$this->request->data('contactNumber')])
				->where(['id' => $this->request->session()->read('FreedomUsers.id')])
				->execute();
			echo '<span class="contactresponse" style="color:green">Profile updated successfully.</span>';
			die;
		}
		$users = $this->Users->find()->Where(['Users.id' => $this->request->session()->read('FreedomUsers.id')])->first();
		
		$this->set(compact('layoutTitle', 'breadcum', 'users'));
	}
	
	function changepassword(){
		$this->viewBuilder()->layout('pages');
		$layoutTitle = 'Freedom Giving:: Change password';
		$url = Router::url('/', true);
		$breadcum = [
			'Title' => 'CHANGE PASSWORD',
			'URL'=>[
					  'Home' => $url,
					  'Dashboard' => $url.'dashboard',
					  'Change Password' => $url.'editprofile'
				   ]
			];
		if($this->request->session()->read('FreedomUsers.role') != 'Member'){
			return $this->redirect(['controller' => 'Users', 'action' => 'signup']);
		}
		$this->loadModel('Users');
		$users = $this->Users->find()->Where(['Users.id' => $this->request->session()->read('FreedomUsers.id')])->first();
		if($this->request->data){
			//pr($this->request->data);die;
			$check = (new DefaultPasswordHasher)->check($this->request->data('oldpassword'), $users->password);
			if($check){
				$users = $this->Users->patchEntity($users, ['password'=> $this->request->data('confirmpassword')],['validate' => false]);
				$this->Users->save($users);
				echo '<span class="contactresponse" style="color:green">Password updated successfully.</span>';
				die;
			}else{
				echo '<span class="contactresponse" style="color:red">Current password does not match.</span>';
				die;
			}
			
		}
		$this->set(compact('layoutTitle', 'breadcum', 'users'));
	}
	
	
	function logout(){
		$this->request->session()->delete('FreedomUsers');
        return $this->redirect(['controller' => 'Users', 'action' => 'signup']);
	}
   
}