<?php
/**
 * Zoho CRM Diagnostics Tool
 *
 * A standalone script to diagnose Zoho CRM integration issues
 *
 * To use: Add the following line to wp-config.php:
 * define('ZOHO_DIAGNOSTICS_ENABLED', true);
 *
 * Then access: /wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php
 *
 * @package HVACCommunityEvents
 */

// Security check to prevent direct access unless diagnostics are enabled
if (!defined('ABSPATH')) {
    // Check if this is a direct access with the diagnostics parameter
    if (!isset($_GET['run_diagnostics']) || $_GET['run_diagnostics'] !== 'true') {
        die('Access denied.');
    }
    
    // Bootstrap WordPress
    $wp_load_path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/wp-load.php';
    if (file_exists($wp_load_path)) {
        require_once $wp_load_path;
    } else {
        die('WordPress not found. Please run diagnostics from the WordPress installation directory.');
    }
    
    // Check if diagnostics are enabled
    if (!defined('ZOHO_DIAGNOSTICS_ENABLED') || !ZOHO_DIAGNOSTICS_ENABLED) {
        die('Zoho diagnostics are not enabled. Add define("ZOHO_DIAGNOSTICS_ENABLED", true); to wp-config.php');
    }
    
    // Check if user is logged in and has appropriate capabilities
    if (!current_user_can('manage_options')) {
        die('You do not have permission to run diagnostics.');
    }
}

// Set up error reporting and logging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Create a log directory if it doesn't exist
$log_dir = dirname(dirname(__FILE__)) . '/logs';
if (!file_exists($log_dir)) {
    mkdir($log_dir, 0755, true);
}

// Define log file constants
if (!defined('ZOHO_LOG_FILE')) {
    define('ZOHO_LOG_FILE', $log_dir . '/zoho-diagnostics.log');
}

if (!defined('ZOHO_DEBUG_MODE')) {
    define('ZOHO_DEBUG_MODE', true);
}

// Function to log diagnostic messages
function diagnostics_log($message, $type = 'INFO') {
    $log_message = '[' . date('Y-m-d H:i:s') . '] ' . $type . ': ' . $message . PHP_EOL;
    error_log($log_message, 3, ZOHO_LOG_FILE);
    
    // Also output to screen if this is a direct access
    if (!defined('ABSPATH')) {
        echo $log_message . "<br>\n";
    }
}

// Start diagnostics
diagnostics_log('Starting Zoho CRM diagnostics');

// Check for required files
$required_files = array(
    'class-zoho-crm-auth.php' => dirname(__FILE__) . '/class-zoho-crm-auth.php',
    'zoho-config.php' => dirname(__FILE__) . '/zoho-config.php',
);

$missing_files = array();
foreach ($required_files as $name => $path) {
    if (!file_exists($path)) {
        $missing_files[] = $name;
        diagnostics_log("Missing required file: $name", 'ERROR');
    } else {
        diagnostics_log("Found required file: $name");
    }
}

if (!empty($missing_files)) {
    diagnostics_log('Diagnostics failed due to missing files', 'ERROR');
    die('Missing required files: ' . implode(', ', $missing_files));
}

// Check for config constants
require_once $required_files['zoho-config.php'];
$required_constants = array(
    'ZOHO_CLIENT_ID',
    'ZOHO_CLIENT_SECRET',
    'ZOHO_REFRESH_TOKEN',
    'ZOHO_ACCOUNTS_URL',
    'ZOHO_API_BASE_URL',
);

$missing_constants = array();
$empty_constants = array();
foreach ($required_constants as $constant) {
    if (!defined($constant)) {
        $missing_constants[] = $constant;
        diagnostics_log("Missing required constant: $constant", 'ERROR');
    } else {
        $value = constant($constant);
        if (empty($value)) {
            $empty_constants[] = $constant;
            diagnostics_log("Constant is empty: $constant", 'WARNING');
        } else {
            // Mask the actual value for security
            $masked_value = $constant === 'ZOHO_CLIENT_ID' ? substr($value, 0, 4) . '...' : '[MASKED]';
            diagnostics_log("Found constant: $constant = $masked_value");
        }
    }
}

if (!empty($missing_constants)) {
    diagnostics_log('Diagnostics found missing constants', 'ERROR');
    echo 'Missing required constants: ' . implode(', ', $missing_constants) . "<br>\n";
}

if (!empty($empty_constants)) {
    diagnostics_log('Diagnostics found empty constants', 'WARNING');
    echo 'Empty constants: ' . implode(', ', $empty_constants) . "<br>\n";
}

// Initialize Zoho CRM Auth
require_once $required_files['class-zoho-crm-auth.php'];
$auth = new HVAC_Zoho_CRM_Auth();

// Check the configuration status
$config_status = $auth->get_configuration_status();
diagnostics_log('Configuration status: ' . json_encode($config_status));

foreach ($config_status as $key => $value) {
    $status = $value ? 'OK' : 'FAIL';
    $type = $value ? 'INFO' : 'ERROR';
    diagnostics_log("$key: $status", $type);
    
    echo "$key: " . ($value ? '✅' : '❌') . "<br>\n";
}

// Test getting an access token
try {
    diagnostics_log('Testing access token retrieval');
    $access_token = $auth->get_access_token();
    
    if ($access_token) {
        diagnostics_log('Successfully retrieved access token');
        echo "Access token retrieval: ✅<br>\n";
    } else {
        diagnostics_log('Failed to retrieve access token', 'ERROR');
        echo "Access token retrieval: ❌<br>\n";
    }
} catch (Exception $e) {
    diagnostics_log('Exception while retrieving access token: ' . $e->getMessage(), 'ERROR');
    echo "Access token retrieval exception: " . $e->getMessage() . "<br>\n";
}

// Test API connection
try {
    diagnostics_log('Testing API connection');
    $response = $auth->make_api_request('/settings/modules', 'GET');
    
    if (is_wp_error($response)) {
        diagnostics_log('API connection failed: ' . $response->get_error_message(), 'ERROR');
        echo "API connection: ❌ - " . $response->get_error_message() . "<br>\n";
    } else if (isset($response['modules'])) {
        $module_count = count($response['modules']);
        diagnostics_log("API connection successful. Found $module_count modules.");
        echo "API connection: ✅ - Found $module_count modules<br>\n";
        
        // List first few modules
        echo "<strong>Available Modules:</strong><br>\n";
        echo "<ul>\n";
        $count = 0;
        foreach ($response['modules'] as $module) {
            if ($count++ < 5) {
                echo "<li>" . $module['api_name'] . " (" . $module['plural_label'] . ")</li>\n";
            }
        }
        if ($module_count > 5) {
            echo "<li>... and " . ($module_count - 5) . " more</li>\n";
        }
        echo "</ul>\n";
    } else {
        diagnostics_log('API connection failed: ' . json_encode($response), 'ERROR');
        echo "API connection: ❌ - Error response<br>\n";
        echo "<pre>" . json_encode($response, JSON_PRETTY_PRINT) . "</pre>\n";
    }
} catch (Exception $e) {
    diagnostics_log('Exception while testing API connection: ' . $e->getMessage(), 'ERROR');
    echo "API connection exception: " . $e->getMessage() . "<br>\n";
}

// Environment information
echo "<h3>Environment Information</h3>\n";
echo "<ul>\n";
echo "<li>PHP Version: " . phpversion() . "</li>\n";
echo "<li>WordPress Version: " . get_bloginfo('version') . "</li>\n";
echo "<li>Site URL: " . get_site_url() . "</li>\n";
echo "<li>Staging Mode: " . (strpos(get_site_url(), 'upskillhvac.com') === false ? 'Yes' : 'No') . "</li>\n";
echo "<li>Zoho Debug Mode: " . (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE ? 'Enabled' : 'Disabled') . "</li>\n";
echo "<li>Diagnostic Log: " . ZOHO_LOG_FILE . "</li>\n";
echo "</ul>\n";

// Final diagnostics message
diagnostics_log('Zoho CRM diagnostics completed');
echo "<p><strong>Diagnostics completed.</strong> Check the log file for more details: " . ZOHO_LOG_FILE . "</p>\n";

// Include a simple CSS for better presentation
echo "<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; line-height: 1.4; padding: 20px; max-width: 800px; margin: 0 auto; }
h1, h2, h3 { color: #23282d; }
pre { background: #f0f0f0; padding: 15px; border-radius: 3px; overflow: auto; }
ul { margin-left: 20px; }
</style>\n";