<?php
/**
 * Zoho Environment Variables Check
 * 
 * This script checks if your .env file is properly set up 
 * with Zoho CRM credentials and if they can be loaded correctly.
 * 
 * Usage: php check-zoho-env.php
 */

echo "=== Zoho Environment Check ===\n\n";

// Find the .env file
$env_file = __DIR__ . '/../.env';

if (!file_exists($env_file)) {
    echo "ERROR: .env file not found at {$env_file}\n";
    exit(1);
}

echo "Found .env file at: {$env_file}\n";

// Read the .env file
$env_content = file_get_contents($env_file);
$lines = explode("\n", $env_content);

// Extract Zoho variables
$zoho_vars = [];
foreach ($lines as $line) {
    if (strpos($line, 'ZOHO_') === 0 && strpos($line, '=') !== false) {
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        $zoho_vars[$name] = $value;
    }
}

// Check required variables
$required_vars = [
    'ZOHO_CLIENT_ID',
    'ZOHO_CLIENT_SECRET',
    'ZOHO_REFRESH_TOKEN'
];

echo "\nChecking Zoho CRM variables in .env file:\n";
$missing_vars = [];

foreach ($required_vars as $var) {
    $status = isset($zoho_vars[$var]) && !empty($zoho_vars[$var]) ? '✅ Found' : '❌ Missing or empty';
    echo "  - {$var}: {$status}\n";
    
    if (!isset($zoho_vars[$var]) || empty($zoho_vars[$var])) {
        $missing_vars[] = $var;
    }
}

// Test loading the variables
echo "\nTesting environment variable loading:\n";

putenv('ZOHO_TEST_VAR=This is a test');
$test_var = getenv('ZOHO_TEST_VAR');

echo "  - Test variable: " . ($test_var === 'This is a test' ? '✅ Working' : '❌ Not working') . "\n";

// Load variables from .env
$loaded_vars = [];
foreach ($zoho_vars as $name => $value) {
    putenv("{$name}={$value}");
    $loaded_vars[$name] = getenv($name);
}

// Verify loaded variables
foreach ($required_vars as $var) {
    if (isset($loaded_vars[$var])) {
        $masked_value = substr($loaded_vars[$var], 0, 5) . '...';
        $status = $loaded_vars[$var] === $zoho_vars[$var] ? '✅ Loaded correctly' : '❌ Loading failed';
        echo "  - {$var}: {$status} ({$masked_value})\n";
    } else {
        echo "  - {$var}: ❌ Not loaded\n";
    }
}

echo "\n";

// Final assessment
if (empty($missing_vars) && $test_var === 'This is a test') {
    echo "✅ Environment setup looks good! Zoho credentials should be loaded correctly.\n";
} else {
    echo "❌ Environment issues detected:\n";
    
    if (!empty($missing_vars)) {
        echo "  - Missing variables: " . implode(', ', $missing_vars) . "\n";
        echo "  - Please add these to your .env file\n";
    }
    
    if ($test_var !== 'This is a test') {
        echo "  - Environment loading isn't working correctly\n";
        echo "  - Check if PHP can access environment variables on your system\n";
    }
}

// Test loading config file
$config_file = __DIR__ . '/../wordpress/wp-content/plugins/hvac-community-events/includes/zoho/zoho-config.php';

echo "\nTesting Zoho config file loading:\n";
echo "Config file path: {$config_file}\n";

if (file_exists($config_file)) {
    echo "Config file: ✅ Found\n";
    
    // Create a test script to include the config
    $test_script = <<<EOT
<?php
// Reset all Zoho constants
if (defined('ZOHO_CLIENT_ID')) {
    echo "Warning: ZOHO_CLIENT_ID already defined\n";
}

// Set up a test environment variable
putenv('ZOHO_TEST_ENV=Test environment value');

// Include the config file
require_once '{$config_file}';

// Check if the constants are defined
echo "Loaded constants:\n";
echo " - ZOHO_CLIENT_ID: " . (defined('ZOHO_CLIENT_ID') ? 'Defined (' . (ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'empty') . ')' : 'Not defined') . "\n";
echo " - ZOHO_CLIENT_SECRET: " . (defined('ZOHO_CLIENT_SECRET') ? 'Defined (' . (ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'empty') . ')' : 'Not defined') . "\n";
echo " - ZOHO_REFRESH_TOKEN: " . (defined('ZOHO_REFRESH_TOKEN') ? 'Defined (' . (ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'empty') . ')' : 'Not defined') . "\n";

// Check if .env loading works
echo "Environment loading:\n";
echo " - .env file loaded: " . (isset(\$env_loaded) ? (\$env_loaded ? 'Yes' : 'No') : 'Unknown') . "\n";
echo " - Test env var loaded: " . (getenv('ZOHO_TEST_ENV') === 'Test environment value' ? 'Yes' : 'No') . "\n";

// Check for log file
echo "Log file:\n";
echo " - ZOHO_LOG_FILE: " . (defined('ZOHO_LOG_FILE') ? ZOHO_LOG_FILE : 'Not defined') . "\n";
echo " - Log directory exists: " . (file_exists(dirname(defined('ZOHO_LOG_FILE') ? ZOHO_LOG_FILE : '')) ? 'Yes' : 'No') . "\n";
echo " - Log directory writable: " . (is_writable(dirname(defined('ZOHO_LOG_FILE') ? ZOHO_LOG_FILE : '')) ? 'Yes' : 'No') . "\n";
EOT;

    $test_file = __DIR__ . '/../test-zoho-config.php';
    file_put_contents($test_file, $test_script);
    
    echo "\nRunning test script...\n";
    echo "---------------------------------\n";
    system("php {$test_file}");
    echo "---------------------------------\n";
    
    // Clean up
    unlink($test_file);
} else {
    echo "Config file: ❌ Not found\n";
}

echo "\n=== Check Complete ===\n";