<?php
// ============================================================
//  ONE-OFF: Exchange Zoho authorization code for refresh token
// ============================================================
//  Upload this to /buylocal/zoho-exchange.php
//  Visit it ONCE in your browser
//  It will print the refresh token (and access token)
//  Copy the refresh_token value into includes/config.php
//  Then DELETE this file from the server.
//
//  ⚠ Run this within 10 minutes of generating the auth code,
//  or the code will have expired (Zoho's rule, not ours).
// ============================================================

header('Content-Type: text/plain; charset=utf-8');

$client_id     = '1000.VRW9MXM7U3K04HVLN8SORZQC2JFVUL';
$client_secret = 'e825aa5789fca73e8b65f476ff5f5bff36751ce876';
$auth_code     = '1000.dafbde6eb679ddb6420d36caee69e76b.3cb1c2feaed5fd2041a4fcefac0a7a8a';

$ch = curl_init('https://accounts.zoho.com/oauth/v2/token');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS     => http_build_query([
        'grant_type'    => 'authorization_code',
        'client_id'     => $client_id,
        'client_secret' => $client_secret,
        'code'          => $auth_code,
    ]),
    CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_SSL_VERIFYPEER => true,
]);

$response  = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err       = curl_error($ch);
curl_close($ch);

echo "HTTP Status: $http_code\n";
echo "================================\n";

if ($response === false) {
    echo "cURL error: $err\n";
    exit;
}

$data = json_decode($response, true);
if (!is_array($data)) {
    echo "Could not parse response:\n$response\n";
    exit;
}

if (isset($data['error'])) {
    echo "❌ Zoho returned an error:\n";
    print_r($data);
    echo "\nLikely causes:\n";
    echo "- Auth code expired (10-min limit)\n";
    echo "- Auth code already used (single-use)\n";
    echo "- Wrong client_id / secret\n";
    echo "- Wrong data center (this script targets accounts.zoho.com — change if you're on .eu / .in / etc.)\n";
    exit;
}

echo "✅ Success!\n\n";
echo "REFRESH TOKEN  (save to config — this is permanent):\n";
echo "    {$data['refresh_token']}\n\n";
echo "ACCESS TOKEN   (short-lived, our code will auto-refresh):\n";
echo "    {$data['access_token']}\n\n";
echo "API DOMAIN:    {$data['api_domain']}\n";
echo "EXPIRES IN:    {$data['expires_in']} seconds (1 hour)\n";
echo "TOKEN TYPE:    {$data['token_type']}\n";
echo "\n";
echo "================================\n";
echo "NEXT STEPS:\n";
echo "1. Copy the REFRESH TOKEN above\n";
echo "2. Paste it into includes/config.php as ZOHO_REFRESH_TOKEN\n";
echo "3. DELETE this file (zoho-exchange.php) from the server\n";