<?php

declare(strict_types=1);

require_once __DIR__ . '/google-lib.php';

auth_session_start();

if (!google_configured()) {
    google_fail_redirect('missing_config');
}

$next = auth_safe_next((string) ($_GET['next'] ?? ($_SESSION['google_oauth_next'] ?? '')));
$_SESSION['google_oauth_next'] = $next;

$state = bin2hex(random_bytes(16));
$_SESSION['google_oauth_state'] = $state;

$cfg = google_config();
$query = http_build_query([
    'client_id' => trim((string) ($cfg['client_id'] ?? '')),
    'redirect_uri' => google_redirect_uri(),
    'response_type' => 'code',
    'scope' => 'openid email profile',
    'state' => $state,
    'prompt' => 'select_account',
]);

header('Location: https://accounts.google.com/o/oauth2/v2/auth?' . $query, true, 302);
exit;
