<?php
class Auth extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		if ($this->session->level) {
			redirect($this->session->level, 'refresh');
		}

		$this->form_validation->set_rules('username', 'Username', 'required|trim');
		$this->form_validation->set_rules('password', 'Password', 'required|trim');


		if ($this->form_validation->run() == false) {
			$data['title'] = "Login";
			// $this->load->view('templates/header', $data);
			$this->load->view('login', $data);
			// $this->load->view('templates/footer', $data);
		} else {
			$this->_login();
		}
	}

	private function _login()
	{
		$username = $this->input->post('username');
		$password = $this->input->post('password');

		$cek_username = $this->db->get_where('user', ['username' => $username])->row_array();

		if ($cek_username) {
			$data = ['password' => $cek_username['password']];

			if ($cek_username['status'] == 1) {
				if ($data['password'] == sha1($password)) {
					$userdata = [
						'id_user' => $cek_username['id_user'],
						'username' => $cek_username['username'],
						'level' => 'Peminjam',
						'nama_lengkap' => $cek_username['nama_lengkap']
					];
					if ($cek_username['level'] == 'Admin') {
						$userdata = [
							'id_user' => $cek_username['id_user'],
							'username' => $cek_username['username'],
							'level' => 'Admin',
							'nama_lengkap' => $cek_username['nama_lengkap']
						];
						$this->session->set_userdata($userdata);
						redirect('admin');
					} elseif ($cek_username['level'] == 'Kepala Sekolah') {
						$userdata = [
							'id_user' => $cek_username['id_user'],
							'username' => $cek_username['username'],
							'level' => 'Kepala Sekolah',
							'nama_lengkap' => $cek_username['nama_lengkap']
						];
						$this->session->set_userdata($userdata);
						redirect('kepalasekolah');
					}
					$this->session->set_userdata($userdata);
					redirect(strtolower($cek_username['level']));
				} else {
					$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Password salah untuk username ' . $username . '!</div>');
					redirect('auth');
				}
			} else {
				$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">User ' . $username . ' belum aktif! silahkan hubungi admin</div>');
				redirect('auth');
			}
		} else {
			$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">User tidak terdaftar!</div>');
			redirect('auth');
		}
	}

	public function daftar()
	{	
		$data['root'] = ('mendaftar');
		$this->load->view('mendaftar', $data);
	}
	public function mendaftar()
		{
			$this->load->library('form_validation');
			
			$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
			$this->form_validation->set_rules('username', 'Username', 'required|alpha_numeric|min_length[6]|max_length[20]|is_unique[user.username]', 
				array(
					'required' => 'Harap masukkan %s.',
					'alpha_numeric' => '%s hanya boleh terdiri dari huruf dan angka.',
					'min_length' => '%s minimal terdiri dari 6 karakter.',
					'max_length' => '%s tidak boleh lebih dari 20 karakter.',
					'is_unique' => '%s sudah terdaftar, silahkan masukkan username yang lain.'
				)
			);
			$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/]',
				array(
					'required' => 'Harap masukkan %s.',
					'min_length' => '%s minimal terdiri dari 8 karakter.',
					'regex_match' => '%s harus terdiri dari huruf besar, huruf kecil, angka, dan karakter khusus.'
				)
			);

			$this->form_validation->set_rules('password2', 'Konfirmasi Password', 'required|matches[password]',
			array (
				'required' => 'Harap masukkan %s.',
				'matches' => 'Salah Memasukan  %s.',

			)

			);
			$this->form_validation->set_rules('nip', 'NIP', 'required|numeric|is_unique[user.nip]', 
				array(
					'required' => 'Harap masukkan %s.',
					'numeric' => '%s hanya boleh terdiri dari angka.',
					
					'is_unique' => '%s sudah terdaftar, silahkan masukkan NIP yang lain.'
				)
			);

			if ($this->form_validation->run() == FALSE) {
				$data['title'] = 'User Daftar';
            	$this->load->view('mendaftar');
			} else {
				$nama_lengkap = htmlspecialchars($this->input->post('nama_lengkap'));
				$username = htmlspecialchars($this->input->post('username'));
				$password = htmlspecialchars($this->input->post('password'));
				$nip = htmlspecialchars($this->input->post('nip'));

				$array = [
					'id_user' => null,
					'nama_lengkap' => $nama_lengkap,
					'bio' => '',
					'username' => $username,
					'nip' => $nip,
					'no_telp' => '',
					'password' => sha1($password),
					'level' => 'Peminjam',
					'image' => '',
					'status' => 0
				];

				$this->m_siplabs->add_data('user', $array);
				$this->session->set_flashdata('message', '<div class="alert alert-success alert-dismissible">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h5><i class="icon fas fa-check"></i> Mendaftar berhasil!</h5>
					<span>Harap tunggu konfirmasi admin untuk aktivasi</span></div>');
				redirect('auth');
			}
		}

	public function logout()
	{
		$this->session->unset_userdata('id_user');
		$this->session->unset_userdata('username');
		$this->session->unset_userdata('level');
		$this->session->unset_userdata('nama_lengkap');
		$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Logout berhasil!</div>');
		redirect('auth');
	}

	public function lupapassword(){
		$this->form_validation->set_rules('username', 'Username', 'required|trim');
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
		if ($this->form_validation->run() == FALSE) {
			$data['root'] = ('Lupa Password');
			$this->load->view('lupapassword', $data);
		}else {
			$username = $this->input->post('username');
			$email = $this->input->post('email');
			$cek = $this->db->get_where('user',['username => $username'])->row_array();

			if ($cek) {
				$token = base64_encode(random_bytes(32));
				$usertoken = [
					'email' => $email,
					'token'	=> $token,
				];

				$this->db->insert('user_token' , $usertoken);
				$this->_sendemail($token);
				$this->session->set_flashdata('message', '<div class="alert alert-success alert-dismissible">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h7> harap check email anda untuk mengubah password</h7></div>');
				redirect('auth/lupapassword');
			}else {
				$this->session->set_flashdata('message', '<div class="alert alert-danger alert-dismissible">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h7> Username Belum terdaftar!</h7></div>');
				redirect('auth/lupapassword');
			}
		}
	}

	private function _sendemail($token){
		
		$config = [
			'protocol'	=> 'smtp',
			'smtp_host'	=> 'smtp.gmail.com',
			'smtp_user'	=> 'sisteminfomasi565@gmail.com',
			'smtp_pass'	=> 'afzscbuxjppzulyg',
			'smtp_port'	=> 465,
			'smtp_crypto' => 'ssl',
			'mailtype'	=> 'html',
			'charset'	=> 'utf-8',
			'wordwrap' => TRUE
		];
		$this->load->library('email', $config);
		$this->email->initialize($config);
		$this->email->set_newline("\r\n");
		$this->email->from('sisteminfomasi565@gmail.com', 'Reset Your Password');
		$this->email->to($this->input->post('email'));
		
		$this->email->subject('Reset Password');
		$this->email->message('untuk mereset password klik disini : <a href="' . base_url() . 'auth/verify?username=' . $this->input->post('username') . '&token' . urlencode($token) . '">reset password</a>');
		if ($this->email->send()) {
            echo 'Your Email has successfully been sent.';
        } else {
            show_error($this->email->print_debugger());
        }
	}

	public function verify(){
		$username = $this->input->get('username');
		$token = $this->input->get('token');

		$user = $this->db->get_where('user',['username' => $username])->row_array();

		if ($user) {
			$user_token = $this->db->get_where('user_token',['token' => $token]);
			if ($user_token) {
				$this->session->set_userdata('reset_password', $username);
				
				$this->rubahpassword();

			}else {
				// $this->session->set_flashdata('message', '<div class="alert alert-danger alert-dismissible">
				// 	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				// 	<h7> Token Anda Salah!</h7></div>');
				// redirect('auth');
			}
		}else{
			$this->session->set_flashdata('message', '<div class="alert alert-danger alert-dismissible">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h7> Reset Password Gagal!</h7></div>');
				redirect('auth');
		}
		
	}

	public function	rubahpassword(){

		$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/]',
				array(
					'required' => 'Harap masukkan %s.',
					'min_length' => '%s minimal terdiri dari 8 karakter.',
					'regex_match' => '%s harus terdiri dari huruf besar, huruf kecil, angka, dan karakter khusus.'
				)
			);

			$this->form_validation->set_rules('password2', 'Konfirmasi Password', 'required|matches[password]',
			array (
				'required' => 'Harap masukkan %s.',
				'matches' => 'Salah Memasukan  %s.',

			)

			);
		if ($this->form_validation->run() == FALSE) {
			$data['root'] = ('Lupa Password');
			$this->load->view('rubahpassword', $data);
		}else {
			$password = htmlspecialchars($this->input->post('password'));
			$username = $this->session->userdata('reset_password');
			
			$sha1 = sha1($password);
			$this->db->set('password', $sha1);
			$this->db->where('username', $username);
			$this->db->update('user');
			$this->db->where('usert_token');
			$this->db->delete('user_token');
			$this->session->set_flashdata('message', '<div class="alert alert-success alert-dismissible">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h7> Password Anda Berhasil Dirubah!! Silahkan Login</h7></div>');
				redirect('auth');

				$this->session->unset_userdata('reset_password');
		}
		
	}
}
