<?php
// auth/google-login.php — Initiates Google OAuth flow
session_start();
require_once __DIR__ . '/../config.php';

// ── Capture originating page for post-login redirect ──
// Priority: 1) explicit ?redirect= param, 2) HTTP_REFERER, 3) dashboard fallback
$redirect = '';
if (!empty($_GET['redirect'])) {
    $redirect = filter_var($_GET['redirect'], FILTER_SANITIZE_URL);
} elseif (!empty($_SERVER['HTTP_REFERER'])) {
    $parsed = parse_url($_SERVER['HTTP_REFERER']);
    // Only keep referer if it's on our own domain
    if (!empty($parsed['host']) && $parsed['host'] === ($_SERVER['HTTP_HOST'] ?? '')) {
        $redirect = $_SERVER['HTTP_REFERER'];
    }
}
if ($redirect) {
    $_SESSION['login_redirect'] = $redirect;
}

// Generate CSRF state token
$state = bin2hex(random_bytes(16));
$_SESSION['google_oauth_state'] = $state;

// Build Google authorization URL
$params = http_build_query([
    'client_id' => GOOGLE_CLIENT_ID,
    'redirect_uri' => GOOGLE_REDIRECT_URI,
    'response_type' => 'code',
    'scope' => 'openid email profile',
    'access_type' => 'online',
    'state' => $state,
    'prompt' => 'select_account'
]);

header("Location: https://accounts.google.com/o/oauth2/v2/auth?$params");
exit;
