<?php

require_once 'config.php';

if (isset($_GET['code'])) {
    $token = $google_client->fetchAccessTokenWithAuthCode($_GET['code']);
    
    if (!isset($token['error'])) {
        $google_client->setAccessToken($token['access_token']);
        
        $google_service = new Google_Service_Oauth2($google_client);
        $data = $google_service->userinfo->get();
        
        $nama_lengkap = $data['name'];
        $email = $data['email'];
        $google_id = $data['id'];

        $query = $conn->prepare("SELECT * FROM user WHERE email = ?");
        $query->bind_param("s", $email);
        $query->execute();
        $result = $query->get_result();

        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_nama'] = $user['nama_lengkap'];
            
            header('Location: dashboard.php');
            exit();
        
        } else {
            header('Location: index.php?sso_error=not_registered');
            exit();
        }

    }
}

header('Location: index.php');
exit();
?>