<?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')['apple'];
try{
 $state=(string)($_POST['state']??'');if(!$state||!hash_equals((string)($_SESSION['oauth_apple_state']??''),$state))throw new RuntimeException('Estado OAuth inválido.');unset($_SESSION['oauth_apple_state']);
 $code=(string)($_POST['code']??'');if(!$code)throw new RuntimeException('Autorização Apple cancelada.');
 $secret=appleClientSecret($cfg);$token=httpPostForm('https://appleid.apple.com/auth/token',['client_id'=>$cfg['client_id'],'client_secret'=>$secret,'code'=>$code,'grant_type'=>'authorization_code','redirect_uri'=>$cfg['redirect_uri']]);
 $payload=decodeJwtPayload((string)$token['id_token']);
 if(($payload['iss']??'')!=='https://appleid.apple.com'||($payload['aud']??'')!==$cfg['client_id']||($payload['exp']??0)<time())throw new RuntimeException('Token Apple inválido.');
 $email=(string)($payload['email']??'');$sub=(string)($payload['sub']??'');if(!$email||!$sub)throw new RuntimeException('A Apple não forneceu o e-mail.');
 $nome='Aura Farmer';if(!empty($_POST['user'])){$usr=json_decode((string)$_POST['user'],true);$nome=trim(($usr['name']['firstName']??'').' '.($usr['name']['lastName']??''))?:$nome;}
 $stExist=$pdo->prepare('SELECT id FROM af_usuarios WHERE email=? LIMIT 1');$stExist->execute([$email]);$jaExistia=(bool)$stExist->fetchColumn();
 $u=criarOuVincularUsuarioSocial($pdo,'apple',$sub,$email,$nome,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 Apple.');header('Location: '.SITE_URL.'/auth/login.php');exit;}
