
<?php
session_start();
require_once 'vendor/autoload.php';
require_once 'db/config.php';

$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URI);
$client->addScope('email');
$client->addScope('profile');

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    $google_oauth = new Google_Service_Oauth2($client);
    $google_account_info = $google_oauth->userinfo->get();

    $email = $google_account_info->email;
    $name = $google_account_info->name;
    $google_id = $google_account_info->id;

    try {
        $pdo = db();

        // Check if user exists
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user) {
            // User exists, log them in
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            if ($user['username'] === ADMIN_USER) {
                $_SESSION['is_admin'] = true;
            }
        } else {
            // User doesn't exist, create a new one
            $username = strtok($email, '@'); // Create a username from email
            $password = password_hash(random_bytes(16), PASSWORD_BCRYPT); // Create a random password

            $stmt = $pdo->prepare("INSERT INTO users (username, email, password, google_id) VALUES (?, ?, ?, ?)");
            $stmt->execute([$username, $email, $password, $google_id]);
            $user_id = $pdo->lastInsertId();

            $_SESSION['user_id'] = $user_id;
            $_SESSION['username'] = $username;
        }

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

    } catch (PDOException $e) {
        die("Database error: " . $e->getMessage());
    }

} else {
    header('Location: login.php');
    exit();
}
