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

require APPPATH . '/libraries/BaseController.php';

class Googlelogin extends CI_Controller {

    public function __construct()
    {
     parent::__construct();
     $this->load->model('user_model');
    }
   
    function login()
    {
        require FCPATH . 'vendor/autoload.php';
   
     $google_client = new Google_Client();
   
     $google_client->setClientId('1010374949518-5imsnu9l4d5nupo77hr4ak0933c6mgum.apps.googleusercontent.com'); //Define your ClientID
   
     $google_client->setClientSecret('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'); //Define your Client Secret Key
   
     $google_client->setRedirectUri('https://buzzwaretech.com/dentifyduser/googlelogin/login'); //Define your Redirect Uri
   
     $google_client->addScope('email');
   
     $google_client->addScope('profile');
   
     if(isset($_GET["code"]))
     {
      $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
   
      if(!isset($token["error"]))
      {
       $google_client->setAccessToken($token['access_token']);
   
       $this->session->set_userdata('access_token', $token['access_token']);
   
       $google_service = new Google_Service_Oauth2($google_client);
   
       $data = $google_service->userinfo->get();
   
   
       if($this->user_model->Is_already_register($data['id']))
       {
        //update data
        $user_data = array(
         'name' => $data['given_name']." ".$data['family_name'],
         'email' => $data['email'],
         'image'=> $data['picture'],
        );
   
        $this->user_model->Update_user_data($user_data, $data['id']);
        $result = $this->user_model->getUserInfoByUid($data['id']);

        $sessionArray = array(
            'userId'=>$result->id,
            'name'=>$result->name,
            'email'=>$result->email,
            'role'=>$result->role,
            'isLoggedIn' => TRUE
        );

       }
       else
       {
        //insert data
        $user_data = array(
         'login_oauth_uid' => $data['id'],
         'name' => $data['given_name']." ".$data['family_name'],
         'email' => $data['email'],
         'image'=> $data['picture'],
         'role'  => 'user'
        );
   
        $userId = $this->user_model->Insert_user_data($user_data);
        $sessionArray = array(
            'userId'=>$userId,
            'name'=>$data['given_name']." ".$data['family_name'],
            'email'=>$data['email'],
            'role'=>'user',
            'isLoggedIn' => TRUE
        );
       }
       $this->session->set_userdata($sessionArray);
       redirect(base_url('site'));
      }
     }else{
        $this->session->set_flashdata('error', 'Google authentication error');
        redirect(base_url('login'));
     }
     
    }
    
}
?>