<?php
/**
 * Zoho CRM Setup Helper
 * 
 * Run this script from command line to help set up Zoho credentials
 * Usage: php setup-helper.php
 */

// Check if running from command line
if (php_sapi_name() !== 'cli') {
    die('This script must be run from the command line.');
}

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

// Step 1: Get Client Credentials
echo "Step 1: Enter your Zoho OAuth Client details\n";
echo "----------------------------------------\n";
echo "Client ID: ";
$client_id = trim(fgets(STDIN));

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

echo "Redirect URI (default: http://localhost:8080/callback): ";
$redirect_uri = trim(fgets(STDIN));
if (empty($redirect_uri)) {
    $redirect_uri = 'http://localhost:8080/callback';
}

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

echo "\nStep 2: Authorize the application\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=AUTH_CODE\n\n";
echo "Enter the authorization code: ";
$auth_code = trim(fgets(STDIN));

// Step 3: 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
];

$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, false);

$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);
}

echo "Success! Tokens received.\n\n";

// Step 4: Get Organization ID
echo "Step 4: Getting organization ID...\n";
echo "--------------------------------\n";

$org_url = 'https://www.zohoapis.com/crm/v2/org';
$ch = curl_init($org_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Zoho-oauthtoken ' . $token_data['access_token']
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$org_response = curl_exec($ch);
$org_data = json_decode($org_response, true);
curl_close($ch);

$org_id = isset($org_data['org'][0]['id']) ? $org_data['org'][0]['id'] : 'NOT_FOUND';

// Step 5: Generate config file
echo "\nStep 5: Generating configuration\n";
echo "-------------------------------\n";

$config_content = "<?php
/**
 * Zoho CRM Configuration
 * Generated on: " . date('Y-m-d H:i:s') . "
 * 
 * DO NOT commit this file to version control!
 */

// Zoho OAuth Credentials
define('ZOHO_CLIENT_ID', '$client_id');
define('ZOHO_CLIENT_SECRET', '$client_secret');
define('ZOHO_REFRESH_TOKEN', '{$token_data['refresh_token']}');
define('ZOHO_REDIRECT_URI', '$redirect_uri');

// Zoho API Settings
define('ZOHO_API_BASE_URL', 'https://www.zohoapis.com');
define('ZOHO_ACCOUNTS_URL', 'https://accounts.zoho.com');
define('ZOHO_ORGANIZATION_ID', '$org_id');

// API Scopes
define('ZOHO_SCOPES', '$scopes');

// Development/Production flag
define('ZOHO_ENVIRONMENT', 'development');

// Error logging
define('ZOHO_DEBUG_MODE', true);
define('ZOHO_LOG_FILE', WP_CONTENT_DIR . '/zoho-crm-debug.log');
";

// Save config file
$config_file = __DIR__ . '/zoho-config.php';
file_put_contents($config_file, $config_content);

echo "Configuration saved to: $config_file\n\n";
echo "=== Setup Complete! ===\n";
echo "Your Zoho CRM integration is ready to use.\n";
echo "Refresh token: {$token_data['refresh_token']}\n";
echo "Organization ID: $org_id\n\n";

echo "Next steps:\n";
echo "1. The config file has been created at: $config_file\n";
echo "2. Make sure to keep this file secure and never commit it to version control\n";
echo "3. You can now use the Zoho CRM integration in your WordPress plugin\n\n";