<?php
/**
 * auth/google.php — Step 1 of Google sign-in.
 * Sends the user to Google's consent screen. Google then returns them to
 * auth/google_callback.php with an authorization code.
 *
 * Optional: pass ?redirect=somepage.php to control where the user lands
 * after a successful sign-in (defaults to dashboard.php).
 */
session_start();
require_once __DIR__ . '/../config/oauth.php';

if (GOOGLE_CLIENT_ID === '') {
    http_response_code(503);
    exit('Google sign-in is not configured yet. See auth/GOOGLE_SIGNIN_SETUP.md.');
}

// CSRF guard: a random state we re-check on the way back.
$state = bin2hex(random_bytes(16));
$_SESSION['oauth_state'] = $state;

// Remember an optional post-login destination.
if (!empty($_GET['redirect'])) {
    $_SESSION['login_redirect'] = $_GET['redirect'];
}

$authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
    'client_id'     => GOOGLE_CLIENT_ID,
    'redirect_uri'  => dabil_google_redirect_uri(),
    'response_type' => 'code',
    'scope'         => 'openid email profile',
    'state'         => $state,
    'access_type'   => 'online',
    'prompt'        => 'select_account',
]);

header('Location: ' . $authUrl);
exit;
