<?php
/**
 * Production Configuration
 * This file contains production-specific settings
 */

// Production Environment Settings
define('ENVIRONMENT', 'production');
define('DEBUG_MODE', false);
define('LOG_LEVEL', 'error'); // error, warning, info, debug

// Security Settings
define('SESSION_SECURE', true);
define('SESSION_HTTP_ONLY', true);
define('SESSION_USE_STRICT_MODE', true);
define('SESSION_COOKIE_SAMESITE', 'Strict');

// Performance Settings
define('CACHE_ENABLED', true);
define('CACHE_DURATION', 3600); // 1 hour
define('DB_QUERY_CACHE', true);
define('COMPRESSION_ENABLED', true);

// Error Handling
if (ENVIRONMENT === 'production') {
    // Hide all errors in production
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/logs/error.log');
    
    // Set custom error handler
    set_error_handler(function($severity, $message, $file, $line) {
        if (!(error_reporting() & $severity)) {
            return false;
        }
        
        $error = [
            'timestamp' => date('Y-m-d H:i:s'),
            'severity' => $severity,
            'message' => $message,
            'file' => $file,
            'line' => $line,
            'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            'request_uri' => $_SERVER['REQUEST_URI'] ?? 'unknown'
        ];
        
        error_log(json_encode($error));
        return true;
    });
    
    // Set custom exception handler
    set_exception_handler(function($exception) {
        $error = [
            'timestamp' => date('Y-m-d H:i:s'),
            'type' => 'Exception',
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => $exception->getTraceAsString(),
            'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            'request_uri' => $_SERVER['REQUEST_URI'] ?? 'unknown'
        ];
        
        error_log(json_encode($error));
        
        // Show generic error page
        http_response_code(500);
        include __DIR__ . '/error_pages/500.php';
        exit;
    });
    
    // Set shutdown handler for fatal errors
    register_shutdown_function(function() {
        $error = error_get_last();
        if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
            $errorData = [
                'timestamp' => date('Y-m-d H:i:s'),
                'type' => 'Fatal Error',
                'message' => $error['message'],
                'file' => $error['file'],
                'line' => $error['line'],
                'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                'request_uri' => $_SERVER['REQUEST_URI'] ?? 'unknown'
            ];
            
            error_log(json_encode($errorData));
            
            http_response_code(500);
            include __DIR__ . '/error_pages/500.php';
            exit;
        }
    });
}

// Security Headers
function setSecurityHeaders() {
    if (!headers_sent()) {
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('X-XSS-Protection: 1; mode=block');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
        
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
            header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
        }
        
        // Content Security Policy
        $csp = "default-src 'self'; " .
               "script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com https://cdnjs.cloudflare.com; " .
               "style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com; " .
               "font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; " .
               "img-src 'self' data: https:; " .
               "connect-src 'self'; " .
               "frame-ancestors 'none';";
        header("Content-Security-Policy: $csp");
    }
}

// Initialize security headers
setSecurityHeaders();

// Session Configuration
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_secure', SESSION_SECURE ? '1' : '0');
    ini_set('session.cookie_httponly', SESSION_HTTP_ONLY ? '1' : '0');
    ini_set('session.use_strict_mode', SESSION_USE_STRICT_MODE ? '1' : '0');
    ini_set('session.cookie_samesite', SESSION_COOKIE_SAMESITE);
    ini_set('session.gc_maxlifetime', 3600); // 1 hour
    ini_set('session.gc_probability', 1);
    ini_set('session.gc_divisor', 100);
}

// Database Connection Optimization
function getOptimizedDBConfig() {
    return [
        'host' => 'localhost',
        'username' => 'your_db_user',
        'password' => 'your_secure_password',
        'database' => 'your_database_name',
        'charset' => 'utf8mb4',
        'options' => [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
            PDO::ATTR_PERSISTENT => false, // Disable persistent connections in production
            PDO::ATTR_TIMEOUT => 30
        ]
    ];
}

// Cache Configuration
function getCacheConfig() {
    return [
        'enabled' => CACHE_ENABLED,
        'driver' => 'file', // file, redis, memcached
        'path' => __DIR__ . '/cache/',
        'duration' => CACHE_DURATION,
        'prefix' => 'megabytehub_'
    ];
}

// Rate Limiting Configuration
function getRateLimitConfig() {
    return [
        'enabled' => true,
        'login_attempts' => 5,
        'login_window' => 900, // 15 minutes
        'api_requests' => 1000,
        'api_window' => 3600, // 1 hour
        'storage' => 'database' // database, redis, file
    ];
}

// Logging Configuration
function getLoggingConfig() {
    return [
        'enabled' => true,
        'level' => LOG_LEVEL,
        'path' => __DIR__ . '/logs/',
        'max_size' => 10485760, // 10MB
        'max_files' => 5,
        'format' => 'json'
    ];
}

// Monitoring Configuration
function getMonitoringConfig() {
    return [
        'enabled' => true,
        'health_check' => true,
        'performance_monitoring' => true,
        'error_tracking' => true,
        'uptime_monitoring' => true
    ];
}

// Backup Configuration
function getBackupConfig() {
    return [
        'enabled' => true,
        'frequency' => 'daily',
        'retention' => 30, // days
        'path' => __DIR__ . '/backups/',
        'compress' => true,
        'encrypt' => true
    ];
}

// Production-specific functions
function isProduction() {
    return ENVIRONMENT === 'production';
}

function isDebugMode() {
    return DEBUG_MODE && !isProduction();
}

function logProduction($level, $message, $context = []) {
    if (!isProduction()) {
        return;
    }
    
    $logEntry = [
        'timestamp' => date('Y-m-d H:i:s'),
        'level' => $level,
        'message' => $message,
        'context' => $context,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'request_uri' => $_SERVER['REQUEST_URI'] ?? 'unknown'
    ];
    
    $logFile = __DIR__ . '/logs/production.log';
    file_put_contents($logFile, json_encode($logEntry) . "\n", FILE_APPEND | LOCK_EX);
}

// Initialize production environment
if (isProduction()) {
    // Create necessary directories
    $directories = ['logs', 'cache', 'backups', 'error_pages'];
    foreach ($directories as $dir) {
        $path = __DIR__ . '/' . $dir;
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
    }
    
    // Log production startup
    logProduction('info', 'Production environment initialized', [
        'php_version' => PHP_VERSION,
        'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'unknown',
        'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'unknown'
    ]);
}
?>


