<?php
defined ( 'BASEPATH' ) OR exit ( 'No direct script access allowed' );

class Auth extends CI_Controller {
	public function __construct () {
		parent::__construct ();
		$this->load->model ( 'admin/auth_model', 'auth_model' );
		$this->load->library ( 'functions' );
	}
	
	// Home index function
	public function index () {
		if ( $this->session->has_userdata ( 'admin_id' ) ) {
			redirect ( 'dashboard' );
		} else {
			redirect ( 'admin/auth/login' );
		}
	}
	
	// Login function
	public function login () {
		if ( $this->input->post ( 'submit' ) ) {
			$this->form_validation->set_rules ( 'email', 'Email', 'trim|required' );
			$this->form_validation->set_rules ( 'password', 'Password', 'trim|required' );

			if ( $this->form_validation->run () == FALSE ) {
				$this->load->view ( 'admin/auth/login' );
			} else {
				$data = array (
					'email'		=> $this->input->post ( 'email' ),
					'password'	=> $this->input->post ( 'password' )
				);

				$result = $this->auth_model->login ( $data );
				
				if ( $result ) {
					$admin_data = array (
						'admin_id'	    => $result['id'],
						'email'	        => $result['email'],
						//'role'		    => $result['role']
					);
					$this->session->set_userdata ( $admin_data );
					
					if(!empty($this->input->post("remember"))) {
                        setcookie ( "email", $data['email'], time() + ( 10 * 365 * 24 * 60 * 60 ) );  
                        setcookie ( "password", $data['password'],  time() + ( 10 * 365 * 24 * 60 * 60 ) );
                    } else {
                        setcookie ( "email", "" );
                        setcookie ( "password", "" );
                    }
					
					redirect ( base_url ( 'admin/dashboard' ), 'refresh' );
				} else {
				    $this->session->set_flashdata ( 'error', 'Invalid Username or Password!' );
					$this->load->view ( 'admin/auth/login', $data );
				}
			}
		} else {
			$this->load->view ( 'admin/auth/login' );
		}
	}
    
    // Logout function
	public function logout () {
		$this->session->sess_destroy ();
		redirect ( base_url ( 'admin/auth/login' ), 'refresh' );
	}
	
	// Forgot password function
	public function forgot_password () {
	    if ( $this->session->has_userdata ( 'admin_id' ) ) {
			redirect ( 'dashboard' );
		}
		$data = array();

		if ( $this->input->post ( 'submit' ) ) {
			
			$this->form_validation->set_rules ( 'email', 'email', 'trim|required|valid_email' );

			if ( $this->form_validation->run () != FALSE ) {
				$email = $this->input->post ('email');
				$admin = $this->auth_model->admin_email_exists ( $email );
				if ( ! empty ( $admin ) ) {
					$seed = str_split('abcdefghijklmnopqrstuvwxyz'.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789');
					shuffle($seed);
					$rand = '';
					foreach (array_rand($seed, 30) as $k) $rand .= $seed[$k];
					
					$save_user = array(); 
					$save_user['id'] = $admin['id'];
					$save_user['email_token'] = $rand;
					$this->auth_model->update_admin ( $save_user );
						
					$link = base_url ( 'admin/auth/reset_password/'.$admin["id"].'/'.$rand );
					$search_arr = array(
						'{name}' => $admin['full_name'],
						'{link}' => '<a href="'.$link.'">Reset Password</a>'
					);
					$temp_id = 2;
					$this->functions->send_email( $email, $temp_id, $search_arr );
				
					$this->session->set_flashdata( 'success', 'Change password link is sent to your email. If you do not receive the email please check your spam.' );

				} else {
					$this->session->set_flashdata( 'error', 'Email not found.' );
				}
			}
		}
		$this->load->view ( 'admin/auth/forgot_password', $data );
	}
	
	// Reset password function
	function reset_password ( $id=false, $email_token=false ) {

		if( empty( $id )  && empty( $email_token ) ) {
			$this->session->set_flashdata ( 'error', 'Permission denied!' );
			redirect ( 'admin/auth/login' );
		}
				
		if ( $this->input->post ( 'submit' ) ) {
			$this->form_validation->set_rules ( 'password', 'Password', 'trim|required|min_length[8]' );
			$this->form_validation->set_rules ( 'cpassword', 'Confirm Password', 'trim|required|matches[password]');
			if ( $this->form_validation->run () != FALSE ) {
				
				$user = $this->auth_model->get_admin_detail ( $id );
				if( ! empty ( $user ) ) {
					if( $user['email_token'] == $email_token ) {
						$save_user = array(); 
						$save_user['id'] = $user['id'];
						$save_user['password'] = md5 ( $this->input->post ( 'password' ) );
						$save_user['email_token'] = '';
						$this->auth_model->update_admin ( $save_user );
						$this->session->set_flashdata ( 'success', 'Password changed successfully.' );
						redirect ( 'admin/auth/login' );
					} else {
						$this->session->set_flashdata ( 'error', 'Invalid/expired secret token!' );
					}
				} else {
					$this->session->set_flashdata ( 'error', 'Invalid user!' );
				}
			}
		}
		$data['form_url']	    = base_url ( 'admin/auth/reset_password/'.$id.'/'.$email_token );
		$data['email_token']	= $email_token;
		$data['view']	        = 'admin/auth/reset_password';
		$this->load->view ( 'admin/auth/reset_password', $data );
	}
		
}
?>