<?php
/**
 * Test Zoho CRM Integration
 * 
 * Run this script to test the Zoho integration and complete the setup
 * Usage: php test-integration.php
 */

// Load environment variables
$env_file = '/Users/ben/dev/upskill-event-manager/wordpress-dev/.env';
if (file_exists($env_file)) {
    $lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
            list($key, $value) = explode('=', $line, 2);
            putenv(trim($key) . '=' . trim($value));
        }
    }
} else {
    die("Error: .env file not found at $env_file\n");
}

// 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 Integration Test ===\n\n";

// Get credentials from environment
$client_id = getenv('ZOHO_CLIENT_ID');
$client_secret = getenv('ZOHO_CLIENT_SECRET');

if (!$client_id || !$client_secret) {
    die("Error: ZOHO_CLIENT_ID and ZOHO_CLIENT_SECRET not found in environment variables.\n");
}

echo "✓ Credentials loaded from .env file\n";
echo "Client ID: " . substr($client_id, 0, 20) . "...\n\n";

// Set redirect URI
$redirect_uri = 'http://localhost:8080/callback';

// Step 1: 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 "Step 1: Authorization\n";
echo "--------------------\n";
echo "Please 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 from the URL: ";
$auth_code = trim(fgets(STDIN));

// Step 2: Exchange code for tokens
echo "\nStep 2: 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 "✓ Tokens received successfully\n";
echo "Access Token: " . substr($token_data['access_token'], 0, 20) . "...\n";
echo "Refresh Token: " . substr($token_data['refresh_token'], 0, 20) . "...\n\n";

// Step 3: Get Organization Info
echo "Step 3: Getting organization information...\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);

if (isset($org_data['org'][0])) {
    $org = $org_data['org'][0];
    echo "✓ Organization found\n";
    echo "Name: " . $org['company_name'] . "\n";
    echo "ID: " . $org['id'] . "\n";
    echo "Time Zone: " . $org['time_zone'] . "\n\n";
} else {
    echo "Error: Could not get organization info\n";
    echo "Response: " . $org_response . "\n";
}

// Step 4: Test Module Access
echo "Step 4: Testing module access...\n";
echo "-------------------------------\n";

$modules = ['Campaigns', 'Contacts', 'Invoices'];
foreach ($modules as $module) {
    $module_url = "https://www.zohoapis.com/crm/v2/settings/modules/$module";
    $ch = curl_init($module_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);
    
    $module_response = curl_exec($ch);
    $module_data = json_decode($module_response, true);
    curl_close($ch);
    
    if (isset($module_data['modules'][0])) {
        echo "✓ $module module accessible\n";
    } else {
        echo "✗ $module module not accessible\n";
    }
}

// Step 5: Create configuration file
echo "\nStep 5: Creating configuration file...\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', '" . (isset($org['id']) ? $org['id'] : 'NOT_FOUND') . "');

// 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');
";

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

echo "✓ Configuration file created: $config_file\n\n";

// Step 6: Update .env file with refresh token
echo "Step 6: Updating .env file...\n";
echo "----------------------------\n";

$env_content = file_get_contents($env_file);
if (strpos($env_content, 'ZOHO_REFRESH_TOKEN') === false) {
    // Add refresh token to .env
    $env_content .= "\n# Zoho refresh token (auto-generated)\n";
    $env_content .= "ZOHO_REFRESH_TOKEN=" . $token_data['refresh_token'] . "\n";
    $env_content .= "ZOHO_ORGANIZATION_ID=" . (isset($org['id']) ? $org['id'] : 'NOT_FOUND') . "\n";
    file_put_contents($env_file, $env_content);
    echo "✓ Added refresh token to .env file\n";
} else {
    echo "ℹ Refresh token already exists in .env file\n";
}

echo "\n=== Integration Test Complete! ===\n";
echo "Your Zoho CRM integration is ready to use.\n";
echo "Next steps:\n";
echo "1. The system will automatically create custom fields in Zoho\n";
echo "2. You can start syncing events, contacts, and invoices\n";
echo "3. Check the WordPress admin for integration status\n\n";