<?php
/**
 * Zoho CRM Configuration
 * 
 * This file contains the necessary constants for Zoho CRM integration.
 * Modified with enhanced debugging and log file path.
 */

// Load environment variables from .env file
function load_env_from_dotenv() {
    // Look for .env file in WordPress root first, then other locations
    $search_dirs = [
        ABSPATH, // WordPress root directory (most likely location)
        dirname(dirname(dirname(__FILE__))), // Plugin directory
        dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins
        dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
        dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // fallback path
    ];
    
    foreach ($search_dirs as $dir) {
        $env_file = $dir . '/.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($name, $value) = explode('=', $line, 2);
                    $name = trim($name);
                    $value = trim($value);
                    
                    // Remove quotes if present
                    if (strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value) - 1) {
                        $value = substr($value, 1, -1);
                    } elseif (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value) - 1) {
                        $value = substr($value, 1, -1);
                    }
                    
                    // Don't use putenv() as it may be disabled on some servers
                    // putenv("$name=$value");
                    $_ENV[$name] = $value;
                }
            }
            return true;
        }
    }
    return false;
}

// Try to load environment variables
$env_loaded = load_env_from_dotenv();

// Enhanced debugging for .env loading
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
    $debug_info = "[" . date('Y-m-d H:i:s') . "] ENV LOADING DEBUG:\n";
    $debug_info .= "Environment loaded from .env: " . ($env_loaded ? 'Yes' : 'No') . "\n";
    
    // Check search paths
    $search_dirs = [
        ABSPATH, // WordPress root directory (most likely location)
        dirname(dirname(dirname(__FILE__))), // Plugin directory
        dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins  
        dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
        dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // fallback path
    ];
    
    foreach ($search_dirs as $i => $dir) {
        $env_file = $dir . '/.env';
        $exists = file_exists($env_file);
        $debug_info .= "Search path " . ($i+1) . ": $env_file - " . ($exists ? 'EXISTS' : 'NOT FOUND') . "\n";
        if ($exists) {
            $debug_info .= "File size: " . filesize($env_file) . " bytes\n";
        }
    }
    
    // Check if variables are set
    $debug_info .= "getenv('ZOHO_CLIENT_ID'): " . (getenv('ZOHO_CLIENT_ID') ?: 'NOT SET') . "\n";
    $debug_info .= "\$_ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? $_ENV['ZOHO_CLIENT_ID'] : 'NOT SET') . "\n";
    
    // Log to debug file
    if (!defined('ZOHO_LOG_FILE')) {
        $log_dir = dirname(dirname(__FILE__)) . '/logs';
        if (!file_exists($log_dir)) {
            mkdir($log_dir, 0755, true);
        }
        define('ZOHO_LOG_FILE', $log_dir . '/zoho-debug.log');
    }
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}

// Log directory setup
$log_dir = dirname(dirname(__FILE__)) . '/logs';
if (!file_exists($log_dir)) {
    mkdir($log_dir, 0755, true);
}

// Load .env file directly if it exists and getenv() doesn't work
if (empty(getenv('ZOHO_CLIENT_ID')) && function_exists('load_env_file')) {
    $env_file = defined('ABSPATH') ? ABSPATH . '.env' : __DIR__ . '/../../../../.env';
    if (file_exists($env_file)) {
        load_env_file($env_file);
    }
}

// OAuth Client Credentials
// IMPORTANT: You need to fill these values with your Zoho OAuth credentials
if (!defined('ZOHO_CLIENT_ID')) {
    $client_id = getenv('ZOHO_CLIENT_ID');
    if (empty($client_id) && isset($_ENV['ZOHO_CLIENT_ID'])) {
        $client_id = $_ENV['ZOHO_CLIENT_ID'];
    }
    // If still empty, try manual .env parsing
    if (empty($client_id)) {
        $env_file = defined('ABSPATH') ? ABSPATH . '.env' : __DIR__ . '/../../../../.env';
        if (file_exists($env_file)) {
            $content = file_get_contents($env_file);
            if (preg_match('/ZOHO_CLIENT_ID=([^\r\n]+)/', $content, $matches)) {
                $client_id = trim($matches[1]);
            }
        }
    }
    define('ZOHO_CLIENT_ID', $client_id ?: '');
}
if (!defined('ZOHO_CLIENT_SECRET')) {
    $client_secret = getenv('ZOHO_CLIENT_SECRET');
    if (empty($client_secret) && isset($_ENV['ZOHO_CLIENT_SECRET'])) {
        $client_secret = $_ENV['ZOHO_CLIENT_SECRET'];
    }
    // If still empty, try manual .env parsing
    if (empty($client_secret)) {
        $env_file = defined('ABSPATH') ? ABSPATH . '.env' : __DIR__ . '/../../../../.env';
        if (file_exists($env_file)) {
            $content = file_get_contents($env_file);
            if (preg_match('/ZOHO_CLIENT_SECRET=([^\r\n]+)/', $content, $matches)) {
                $client_secret = trim($matches[1]);
            }
        }
    }
    define('ZOHO_CLIENT_SECRET', $client_secret ?: '');
}
// Get site URL from WordPress if available, otherwise use environment variable or detect from server
if (function_exists('get_site_url')) {
    $site_url = get_site_url();
} elseif (getenv('UPSKILL_STAGING_URL')) {
    $site_url = getenv('UPSKILL_STAGING_URL');
} elseif (isset($_SERVER['HTTP_HOST'])) {
    // Auto-detect from server request
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    $site_url = $protocol . $_SERVER['HTTP_HOST'];
} else {
    // Production fallback - use the production domain
    $site_url = 'https://upskillhvac.com';
}
$site_url = rtrim($site_url, '/');

if (!defined('ZOHO_REDIRECT_URI')) {
    define('ZOHO_REDIRECT_URI', $site_url . '/oauth/callback');
}

// API Endpoints
if (!defined('ZOHO_ACCOUNTS_URL')) {
    define('ZOHO_ACCOUNTS_URL', 'https://accounts.zoho.com');
}
if (!defined('ZOHO_API_BASE_URL')) {
    define('ZOHO_API_BASE_URL', 'https://www.zohoapis.com/crm/v2');
}

// Scopes
if (!defined('ZOHO_SCOPES')) {
    define('ZOHO_SCOPES', 'ZohoCRM.settings.ALL,ZohoCRM.modules.ALL,ZohoCRM.users.ALL,ZohoCRM.org.ALL,ZohoCRM.bulk.READ');
}

// Optional - Refresh Token (if already obtained)
if (!defined('ZOHO_REFRESH_TOKEN')) {
    $refresh_token = getenv('ZOHO_REFRESH_TOKEN');
    if (empty($refresh_token) && isset($_ENV['ZOHO_REFRESH_TOKEN'])) {
        $refresh_token = $_ENV['ZOHO_REFRESH_TOKEN'];
    }
    // If still empty, try manual .env parsing
    if (empty($refresh_token)) {
        $env_file = defined('ABSPATH') ? ABSPATH . '.env' : __DIR__ . '/../../../../.env';
        if (file_exists($env_file)) {
            $content = file_get_contents($env_file);
            if (preg_match('/ZOHO_REFRESH_TOKEN=([^\r\n]+)/', $content, $matches)) {
                $refresh_token = trim($matches[1]);
            }
        }
    }
    define('ZOHO_REFRESH_TOKEN', $refresh_token ?: '');
}

// Debug Settings - Enhanced for better logging
if (!defined('ZOHO_DEBUG_MODE')) {
    define('ZOHO_DEBUG_MODE', true);
}
if (!defined('ZOHO_LOG_FILE')) {
    define('ZOHO_LOG_FILE', $log_dir . '/zoho-debug.log');
}

// Add diagnostic information to log
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
    $timestamp = date('Y-m-d H:i:s');
    $debug_info = "[{$timestamp}] Zoho CRM Configuration loaded\n";
    $debug_info .= "[{$timestamp}] .env file loaded: " . ($env_loaded ? 'Yes' : 'No') . "\n";
    $debug_info .= "[{$timestamp}] Client ID exists: " . (!empty(ZOHO_CLIENT_ID) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[{$timestamp}] Client ID value: " . (ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[{$timestamp}] Client Secret exists: " . (!empty(ZOHO_CLIENT_SECRET) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[{$timestamp}] Client Secret value: " . (ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[{$timestamp}] Refresh Token exists: " . (!empty(ZOHO_REFRESH_TOKEN) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[{$timestamp}] Refresh Token value: " . (ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[{$timestamp}] Log file path: " . ZOHO_LOG_FILE . "\n";
    
    if (function_exists('get_site_url')) {
        $debug_info .= "[{$timestamp}] WordPress site URL: " . get_site_url() . "\n";
        $debug_info .= "[{$timestamp}] Staging mode: " . (strpos(get_site_url(), 'upskillhvac.com') === false ? 'Yes' : 'No') . "\n";
        $debug_info .= "[{$timestamp}] Using OAuth Redirect URI: " . ZOHO_REDIRECT_URI . "\n";
    } else {
        $debug_info .= "[{$timestamp}] WordPress functions not available\n";
        $debug_info .= "[{$timestamp}] Using environment variable for domain: " . ($site_url ?? 'Not set') . "\n";
        $debug_info .= "[{$timestamp}] Using OAuth Redirect URI: " . ZOHO_REDIRECT_URI . "\n";
    }
    
    // Check for environment variables directly
    $debug_info .= "[{$timestamp}] Environment variables:\n";
    $debug_info .= "[{$timestamp}]   - _ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? 'Set' : 'Not set') . "\n";
    $debug_info .= "[{$timestamp}]   - _ENV['ZOHO_CLIENT_SECRET']: " . (isset($_ENV['ZOHO_CLIENT_SECRET']) ? 'Set' : 'Not set') . "\n";
    $debug_info .= "[{$timestamp}]   - _ENV['ZOHO_REFRESH_TOKEN']: " . (isset($_ENV['ZOHO_REFRESH_TOKEN']) ? 'Set' : 'Not set') . "\n";
    
    // Log configuration details
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}