<?php

session_start();

require __DIR__ . "/vendor/autoload.php";

$client = new Google\Client;

$client->setClientId("");
$client->setClientSecret("");
$client->setRedirectUri('http://localhost:8000/redirect.php');

if (!isset($_GET["code"])) {
    exit("Login Failed: No authorization code received.");
}

try {
    $token = $client->fetchAccessTokenWithAuthCode($_GET["code"]);

    if (isset($token["error"])) {
        exit("Error fetching access token: " . $token["error"]);
    }

    $client->setAccessToken($token["access_token"]);

    $oauth = new Google\Service\Oauth2($client);
    $userinfo = $oauth->userinfo->get();

    if (!$userinfo || !isset($userinfo->email) || !isset($userinfo->name)) {
        exit("Error: Invalid user data.");
    }

    $email = $userinfo->email;
    $username = $userinfo->name;

    require "./connect.php";

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

    if ($result->num_rows > 0) {
        // User already exists
        $user = $result->fetch_assoc();
        $_SESSION['email'] = $email;
        $_SESSION['user_ID'] = $user['user_ID'];
        $_SESSION['is_admin'] = $user['is_admin'];
        header("Location: /Home.php");
    } else {
        // New user
        $username = explode("@", $email)[0]; 
        $password = '';  

        $sql = "INSERT INTO users (email, username, password) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $email, $username, $password);
        $stmt->execute();

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

        $user = $result->fetch_assoc();
        $_SESSION['email'] = $email;
        $_SESSION['user_ID'] = $user['user_ID'];
        $_SESSION['is_admin'] = $user['is_admin'];

        header("Location: /Home.php");
    }

    $conn->close();
} catch (Exception $e) {
    exit("Error: " . $e->getMessage());
}
?>
