<?php
/**
 * Zoho CRM Credentials Setup Script
 * 
 * This script helps you generate the Zoho CRM credentials needed for the integration.
 * Run this script on your staging server to complete the OAuth flow and obtain a refresh token.
 * 
 * Usage: php setup-zoho-credentials.php
 */

echo "\n=== Zoho CRM Credentials Setup ===\n\n";

// Get user input
echo "Step 1: Enter your Zoho CRM OAuth Application details\n";
echo "------------------------------------------------\n";
echo "These can be created at https://api-console.zoho.com/\n\n";

echo "Enter your Client ID: ";
$client_id = trim(fgets(STDIN));

echo "Enter your Client Secret: ";
$client_secret = trim(fgets(STDIN));

// Validate input
if (empty($client_id) || empty($client_secret)) {
    die("Error: Client ID and Client Secret are required.\n");
}

// Set staging server redirect URI
$staging_url = "https://wordpress-974670-5399585.cloudwaysapps.com";
$redirect_uri = "$staging_url/oauth/callback";

echo "\nUsing redirect URI: $redirect_uri\n";
echo "Make sure this URL is added to your Zoho OAuth application's authorized redirect URIs.\n";

// Generate authorization URL
$auth_url = "https://accounts.zoho.com/oauth/v2/auth?" . http_build_query([
    'scope' => 'ZohoCRM.settings.all,ZohoCRM.modules.all,ZohoCRM.users.all,ZohoCRM.org.all',
    'client_id' => $client_id,
    'response_type' => 'code',
    'access_type' => 'offline',
    'redirect_uri' => $redirect_uri,
    'prompt' => 'consent'
]);

echo "\nStep 2: Authorization\n";
echo "-------------------\n";
echo "Open this URL in your browser:\n\n";
echo "$auth_url\n\n";
echo "After authorization, you'll be redirected to:\n";
echo "$redirect_uri?code=YOUR_AUTH_CODE\n\n";

echo "Enter the authorization code from the URL: ";
$auth_code = trim(fgets(STDIN));

if (empty($auth_code)) {
    die("Error: Authorization code is required.\n");
}

// Exchange code for tokens
echo "\nStep 3: Exchanging code for tokens...\n";
echo "-----------------------------------\n";

$token_url = 'https://accounts.zoho.com/oauth/v2/token';
$token_params = [
    'grant_type' => 'authorization_code',
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri,
    'code' => $auth_code
];

// Use cURL to make the request
$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code !== 200) {
    echo "Error: Failed to get tokens (HTTP $http_code)\n";
    echo "Response: " . $response . "\n";
    exit(1);
}

$token_data = json_decode($response, true);

if (!isset($token_data['access_token']) || !isset($token_data['refresh_token'])) {
    echo "Error: Invalid token response\n";
    echo "Response: " . $response . "\n";
    exit(1);
}

// Success! Display the values
echo "✓ Tokens received successfully!\n\n";
echo "Here are your Zoho CRM credentials:\n";
echo "--------------------------------\n";
echo "Client ID: $client_id\n";
echo "Client Secret: $client_secret\n";
echo "Refresh Token: " . $token_data['refresh_token'] . "\n\n";

// Generate wp-config.php code
echo "Add these lines to your wp-config.php file:\n";
echo "----------------------------------------\n";
echo "define('ZOHO_CLIENT_ID', '$client_id');\n";
echo "define('ZOHO_CLIENT_SECRET', '$client_secret');\n";
echo "define('ZOHO_REFRESH_TOKEN', '" . $token_data['refresh_token'] . "');\n";
echo "define('ZOHO_DIAGNOSTICS_ENABLED', true);\n\n";

// Generate environment variables setup
echo "Or set these environment variables in your .env file:\n";
echo "-----------------------------------------------\n";
echo "ZOHO_CLIENT_ID=$client_id\n";
echo "ZOHO_CLIENT_SECRET=$client_secret\n";
echo "ZOHO_REFRESH_TOKEN=" . $token_data['refresh_token'] . "\n\n";

echo "To verify your setup, run the diagnostics script:\n";
echo "--------------------------------------------\n";
echo "$staging_url/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true\n\n";

echo "=== Setup Complete! ===\n";