<?php
/**
 * Zoho CRM File & Permissions Diagnostic Tool
 *
 * This script checks file permissions and directory access
 * that might affect the Zoho CRM integration.
 *
 * Access with: ?run_check=true
 */

// Security check
if (!isset($_GET['run_check']) || $_GET['run_check'] !== 'true') {
    die('Access denied. Use ?run_check=true parameter.');
}

// Set headers
header('Content-Type: text/plain');

echo "=== Zoho CRM File & Permissions Check ===\n\n";
echo "Date: " . date('Y-m-d H:i:s') . "\n";
echo "Server: " . $_SERVER['SERVER_NAME'] . "\n";
echo "PHP Version: " . phpversion() . "\n\n";

// Check plugin directory
$plugin_dir = dirname(dirname(dirname(__FILE__)));
echo "Plugin Directory: $plugin_dir\n";
echo "Exists: " . (file_exists($plugin_dir) ? 'Yes' : 'No') . "\n";
echo "Readable: " . (is_readable($plugin_dir) ? 'Yes' : 'No') . "\n";
echo "Writable: " . (is_writable($plugin_dir) ? 'Yes' : 'No') . "\n";
echo "Permissions: " . substr(sprintf('%o', fileperms($plugin_dir)), -4) . "\n\n";

// Check Zoho directory
$zoho_dir = dirname(__FILE__);
echo "Zoho Directory: $zoho_dir\n";
echo "Exists: " . (file_exists($zoho_dir) ? 'Yes' : 'No') . "\n";
echo "Readable: " . (is_readable($zoho_dir) ? 'Yes' : 'No') . "\n";
echo "Writable: " . (is_writable($zoho_dir) ? 'Yes' : 'No') . "\n";
echo "Permissions: " . substr(sprintf('%o', fileperms($zoho_dir)), -4) . "\n\n";

// Check logs directory
$logs_dir = dirname(dirname(__FILE__)) . '/logs';
echo "Logs Directory: $logs_dir\n";
echo "Exists: " . (file_exists($logs_dir) ? 'Yes' : 'No') . "\n";

// Create logs directory if it doesn't exist
if (!file_exists($logs_dir)) {
    echo "Trying to create logs directory...\n";
    $result = @mkdir($logs_dir, 0755, true);
    echo "Creation result: " . ($result ? 'Success' : 'Failed') . "\n";
    
    if ($result) {
        echo "Readable: " . (is_readable($logs_dir) ? 'Yes' : 'No') . "\n";
        echo "Writable: " . (is_writable($logs_dir) ? 'Yes' : 'No') . "\n";
        echo "Permissions: " . substr(sprintf('%o', fileperms($logs_dir)), -4) . "\n";
    }
} else {
    echo "Readable: " . (is_readable($logs_dir) ? 'Yes' : 'No') . "\n";
    echo "Writable: " . (is_writable($logs_dir) ? 'Yes' : 'No') . "\n";
    echo "Permissions: " . substr(sprintf('%o', fileperms($logs_dir)), -4) . "\n";
}
echo "\n";

// Check zoho-config.php
$config_file = $zoho_dir . '/zoho-config.php';
echo "Config File: $config_file\n";
echo "Exists: " . (file_exists($config_file) ? 'Yes' : 'No') . "\n";
echo "Readable: " . (is_readable($config_file) ? 'Yes' : 'No') . "\n";
echo "Writable: " . (is_writable($config_file) ? 'Yes' : 'No') . "\n";
echo "Size: " . (file_exists($config_file) ? filesize($config_file) . ' bytes' : 'N/A') . "\n";
echo "Permissions: " . (file_exists($config_file) ? substr(sprintf('%o', fileperms($config_file)), -4) : 'N/A') . "\n\n";

// Check class-zoho-crm-auth.php
$auth_file = $zoho_dir . '/class-zoho-crm-auth.php';
echo "Auth Class: $auth_file\n";
echo "Exists: " . (file_exists($auth_file) ? 'Yes' : 'No') . "\n";
echo "Readable: " . (is_readable($auth_file) ? 'Yes' : 'No') . "\n";
echo "Size: " . (file_exists($auth_file) ? filesize($auth_file) . ' bytes' : 'N/A') . "\n";
echo "Permissions: " . (file_exists($auth_file) ? substr(sprintf('%o', fileperms($auth_file)), -4) : 'N/A') . "\n\n";

// Test log file writing
$test_log_file = $logs_dir . '/test-permissions.log';
echo "Testing log file writing: $test_log_file\n";
$write_result = @file_put_contents($test_log_file, date('Y-m-d H:i:s') . " Test log entry\n", FILE_APPEND);
echo "Write result: " . ($write_result !== false ? 'Success (' . $write_result . ' bytes)' : 'Failed') . "\n";
if ($write_result !== false) {
    echo "File exists after write: " . (file_exists($test_log_file) ? 'Yes' : 'No') . "\n";
    echo "File permissions: " . substr(sprintf('%o', fileperms($test_log_file)), -4) . "\n";
}
echo "\n";

// Check if we can load WordPress
echo "Checking WordPress integration...\n";
$loaded_wp = false;

// Try to load WordPress
if (!function_exists('get_option')) {
    // Try to find and load WordPress
    $wp_load_path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/wp-load.php';
    if (file_exists($wp_load_path)) {
        echo "Found wp-load.php at: $wp_load_path\n";
        require_once $wp_load_path;
        $loaded_wp = function_exists('get_option');
        echo "WordPress loaded: " . ($loaded_wp ? 'Yes' : 'No') . "\n";
    } else {
        echo "Could not find wp-load.php\n";
    }
} else {
    $loaded_wp = true;
    echo "WordPress already loaded\n";
}

if ($loaded_wp) {
    // Check if plugin is active
    if (function_exists('is_plugin_active')) {
        $plugin_active = is_plugin_active('hvac-community-events/hvac-community-events.php');
        echo "Plugin active: " . ($plugin_active ? 'Yes' : 'No') . "\n";
    } else {
        echo "Could not check if plugin is active (is_plugin_active function not available)\n";
    }
    
    // Check WordPress options
    echo "\nChecking WordPress options...\n";
    echo "Site URL: " . get_option('siteurl') . "\n";
    echo "Home URL: " . get_option('home') . "\n";
    
    // Check if Zoho credentials are stored in options
    echo "\nChecking Zoho credentials in WordPress options...\n";
    echo "Access token option exists: " . (get_option('hvac_zoho_access_token') !== false ? 'Yes' : 'No') . "\n";
    echo "Refresh token option exists: " . (get_option('hvac_zoho_refresh_token') !== false ? 'Yes' : 'No') . "\n";
    echo "Token expiry option exists: " . (get_option('hvac_zoho_token_expiry') !== false ? 'Yes' : 'No') . "\n";
    
    // Check user capabilities
    echo "\nChecking current user capabilities...\n";
    if (function_exists('current_user_can') && function_exists('wp_get_current_user')) {
        echo "Current user: " . wp_get_current_user()->user_login . "\n";
        echo "Can manage options: " . (current_user_can('manage_options') ? 'Yes' : 'No') . "\n";
    } else {
        echo "Could not check user capabilities\n";
    }
}

echo "\n=== Check Completed ===\n";
echo "If you see any 'Failed' or 'No' responses, they may indicate issues with your Zoho CRM integration.\n";
echo "See the diagnostic log for more details about the connection test failures.";