<?php
$clientId = 'd3f1028fe1b8812e74c783e41bf334839233eabb';
$clientSecret = '8f82c37b4afbc3775d7cc55a2c91ef793d7f966523de2555ad3a22da28f0';
$code = '376f968ee35e2f1d27fb8cf143dcfae732accb04';
$tokenUrl = 'https://bling.com.br/Api/v3/oauth/token';

$basicAuth = base64_encode("$clientId:$clientSecret");

echo "=== Trocando CODE por TOKENS ===\n\n";
echo "Code: $code\n";
echo "Basic Auth: " . substr($basicAuth, 0, 40) . "...\n\n";

$ch = curl_init($tokenUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query([
        'grant_type' => 'authorization_code',
        'code' => $code,
    ]),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: 1.0',
        'Authorization: Basic ' . $basicAuth,
    ],
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

echo "HTTP Status: $httpCode\n";

if ($error) {
    echo "❌ Erro cURL: $error\n";
    exit(1);
}

$data = json_decode($response, true);

if ($httpCode === 200 && isset($data['access_token'])) {
    echo "\n✅ TOKENS OBTIDOS COM SUCESSO!\n\n";
    echo "Access Token: " . substr($data['access_token'], 0, 50) . "...\n";
    echo "Refresh Token: " . substr($data['refresh_token'], 0, 50) . "...\n";
    echo "Expires In: " . $data['expires_in'] . " segundos\n\n";
    
    // Salva automaticamente
    $tokenData = [
        'access_token' => $data['access_token'],
        'refresh_token' => $data['refresh_token'],
        'expires_in' => $data['expires_in'],
        'token_type' => $data['token_type'],
        'expires_at' => date('Y-m-d H:i:s', time() + $data['expires_in']),
        'created_at' => date('Y-m-d H:i:s'),
    ];
    
    $tokenFile = __DIR__ . '/bling_auto_token.json';
    file_put_contents($tokenFile, json_encode($tokenData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    echo "💾 Tokens salvos em: $tokenFile\n\n";
    echo "Agora execute:\n";
    echo "  php bling_auto.php test\n";
    echo "  php bling_auto.php produtos\n";
    
} else {
    echo "\n❌ ERRO\n";
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
}
