<?php

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

require_once dirname(__FILE__) . '/Exhibition_Controller.php';

use Google\Client as GoogleClient; 
use Google\Service\Oauth2;

class Login extends Exhibition_Controller {

    public function logout()
	{
		session_unset();
		redirect('login/show_login');
	}

    public function show_login()
	{
		$this->output('login/v_login');
	}

	public function show_login_fail()
	{
		$this->output('login/v_login_fail');
	}

    public function check_login()
	{
		$data['message'] = false;
        $email = $this->input->post('email');
        $password = $this->input->post('password');
		if(strlen($password) > 1){
			$this->load->model('user/M_user', 'user');
			$user = $this->user->check_login($email, md5($password))->result();
			if (count($user) == 1) {
					$_SESSION['first_name'] = $user[0]->first_name;
					$_SESSION['last_name'] = $user[0]->last_name;
					$_SESSION['email'] = $user[0]->email;
					$_SESSION['user_id'] = $user[0]->user_id;
					$_SESSION['role'] = $user[0]->role;
					if($user[0]->role == 1){
						$data['type'] = 1;
					}
					else if($user[0]->role == 2){
						$data['type'] = 2;
					}
				$data['message'] = true;
			}
		}
        echo json_encode($data);
	}


	public function login_google(){
		$client = new GoogleClient();
			$client->setApplicationName('Online Exhibition');
			$client->setClientId('916442378358-fd6q5fubouldl7mghapjqsf5cnoh6lvg.apps.googleusercontent.com');
			$client->setClientSecret('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');
			$client->setRedirectUri('http://localhost/exhi/index.php/Login/login_google');
			$client->addScope(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
			if($code = $this->input->get('code')){
				$token = $client->fetchAccessTokenWithAuthCode($code);
				$client->setAccessToken($token);
				$oauth = new Oauth2($client);
				$user_info = $oauth->userinfo->get();
				$data['name'] = $user_info->name;
				$data['email'] = $user_info->email;
				$data['image'] = $user_info->picture;
				$this->load->model('user/M_user', 'user');
				$data['message'] = true;
				if($user = $this->user->get_user_by_email($user_info->email)->row()){
					$_SESSION['first_name'] = $user->first_name;
					$_SESSION['last_name'] = $user->last_name;
					$_SESSION['email'] = $user->email;
					$_SESSION['user_id'] = $user->user_id;
					$_SESSION['role'] = $user->role;
					$_SESSION['student_id'] = $user->student_id;
					if($user->role == 1){
						$data['type'] = 1;
						redirect('Project/show_project_manage_user');
					}else if($user->role == 2){
						$data['type'] = 2;
						redirect('User/show_user_manage');
					}
				}else{
					$data['message'] = false;
					redirect('login/show_login_fail');
				}
				
			}else{
				$url = $client->createAuthUrl();
				header('Location:'.filter_var($url,FILTER_SANITIZE_URL));
			}
	}
}



