<?php
/** Funções OAuth sem dependências externas. */
function httpPostForm(string $url,array $data): array
{
    $ch=curl_init($url);
    curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($data),CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>20,CURLOPT_HTTPHEADER=>['Accept: application/json']]);
    $body=curl_exec($ch);$code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);$err=curl_error($ch);curl_close($ch);
    if($body===false||$code>=400)throw new RuntimeException('Falha OAuth: '.($err?:'HTTP '.$code));
    $json=json_decode($body,true);if(!is_array($json))throw new RuntimeException('Resposta OAuth inválida.');return $json;
}
function httpGetJson(string $url,array $headers=[]): array
{
    $ch=curl_init($url);curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>20,CURLOPT_HTTPHEADER=>array_merge(['Accept: application/json'],$headers)]);
    $body=curl_exec($ch);$code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);$err=curl_error($ch);curl_close($ch);
    if($body===false||$code>=400)throw new RuntimeException('Falha OAuth: '.($err?:'HTTP '.$code));
    $json=json_decode($body,true);if(!is_array($json))throw new RuntimeException('Resposta OAuth inválida.');return $json;
}
function base64UrlEncode(string $data): string { return rtrim(strtr(base64_encode($data),'+/','-_'),'='); }
function decodeJwtPayload(string $jwt): array
{
    $parts=explode('.',$jwt);if(count($parts)!==3)throw new RuntimeException('Token de identidade inválido.');
    $raw=base64_decode(strtr($parts[1],'-_','+/'));$data=json_decode($raw?:'',true);if(!is_array($data))throw new RuntimeException('Payload inválido.');return $data;
}
function appleClientSecret(array $cfg): string
{
    if(!is_file($cfg['private_key']))throw new RuntimeException('Chave privada Apple não encontrada.');
    $header=base64UrlEncode(json_encode(['alg'=>'ES256','kid'=>$cfg['key_id']],JSON_UNESCAPED_SLASHES));
    $now=time();$payload=base64UrlEncode(json_encode(['iss'=>$cfg['team_id'],'iat'=>$now,'exp'=>$now+15777000,'aud'=>'https://appleid.apple.com','sub'=>$cfg['client_id']],JSON_UNESCAPED_SLASHES));
    $data=$header.'.'.$payload;$key=openssl_pkey_get_private(file_get_contents($cfg['private_key']));
    if(!$key||!openssl_sign($data,$der,$key,OPENSSL_ALGO_SHA256))throw new RuntimeException('Não foi possível assinar o login Apple.');
    // Converte assinatura DER ECDSA em formato JOSE R||S (32 bytes cada).
    $offset=2;if(ord($der[1])&0x80)$offset=2+(ord($der[1])&0x7f);
    if(ord($der[$offset])!==0x02)throw new RuntimeException('Assinatura Apple inválida.');
    $rLen=ord($der[$offset+1]);$r=substr($der,$offset+2,$rLen);$offset+=2+$rLen;
    $sLen=ord($der[$offset+1]);$s=substr($der,$offset+2,$sLen);
    $r=str_pad(ltrim($r,"\0"),32,"\0",STR_PAD_LEFT);$s=str_pad(ltrim($s,"\0"),32,"\0",STR_PAD_LEFT);
    return $data.'.'.base64UrlEncode($r.$s);
}
