<?php
require_once __DIR__.'/../config/config.php';require_once __DIR__.'/../config/database.php';require_once __DIR__.'/../includes/functions.php';require_once __DIR__.'/../includes/viral_functions.php';require_once __DIR__.'/../includes/oauth_functions.php';
$cfg=(require __DIR__.'/../config/oauth.php')['google'];
try{
 if(!isset($_GET['state'])||!hash_equals((string)($_SESSION['oauth_google_state']??''),(string)$_GET['state']))throw new RuntimeException('Estado OAuth inválido.');unset($_SESSION['oauth_google_state']);
 if(empty($_GET['code']))throw new RuntimeException('Autorização cancelada.');
 $token=httpPostForm('https://oauth2.googleapis.com/token',['code'=>$_GET['code'],'client_id'=>$cfg['client_id'],'client_secret'=>$cfg['client_secret'],'redirect_uri'=>$cfg['redirect_uri'],'grant_type'=>'authorization_code']);
 $info=httpGetJson('https://openidconnect.googleapis.com/v1/userinfo',['Authorization: Bearer '.$token['access_token']]);
 if(empty($info['sub'])||empty($info['email'])||empty($info['email_verified']))throw new RuntimeException('Conta Google sem e-mail verificado.');
 $stExist=$pdo->prepare('SELECT id FROM af_usuarios WHERE email=? LIMIT 1');$stExist->execute([(string)$info['email']]);$jaExistia=(bool)$stExist->fetchColumn();
 $u=criarOuVincularUsuarioSocial($pdo,'google',(string)$info['sub'],(string)$info['email'],(string)($info['name']??'Aura Farmer'),$info['picture']??null);
 if(!$jaExistia)afRegistrarCadastroIndicado($pdo,(int)$u['id']);criarSessaoAutenticada($pdo,$u,true);recarregarSessaoUsuario($pdo,(int)$u['id']);$dest=(string)($_SESSION['af_after_login']??'/pages/home.php');unset($_SESSION['af_after_login']);if(!afResumoIdade($pdo,(int)$u['id'])['completo']){$_SESSION['af_after_age']=$dest;header('Location: '.SITE_URL.'/pages/verificar-idade.php');exit;}header('Location: '.SITE_URL.$dest);exit;
}catch(Throwable $e){setFlash('error',APP_DEBUG?$e->getMessage():'Não foi possível entrar com Google.');header('Location: '.SITE_URL.'/auth/login.php');exit;}
