<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/oauth.php';

$state = bin2hex(random_bytes(16));
$_SESSION['oauth_state'] = $state;
$next = isset($_GET['next']) ? $_GET['next'] : '/WATCHING/index.php';
$_SESSION['oauth_next'] = $next;

$params = [
  'client_id' => GOOGLE_CLIENT_ID,
  'redirect_uri' => GOOGLE_REDIRECT_URI,
  'response_type' => 'code',
  'scope' => 'openid email profile',
  'access_type' => 'offline',
  'include_granted_scopes' => 'true',
  'prompt' => 'consent', // ensures refresh token on localhost
  'state' => $state,
];
$authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query($params);
header('Location: ' . $authUrl);
exit;