<?php
// Include the configuration file
if (!defined('SITE_NAME')) {
    require_once __DIR__ . '/config.php';
}

// Initialize PDO variable
$pdo = null;

// Database Configuration - REPLACE WITH YOUR ACTUAL DATABASE DETAILS
if (!isset($host))
    $host = '';
if (!isset($dbname))
    $dbname = '';
if (!isset($username))
    $username = '';
if (!isset($password))
    $password = '';

// Database connection retry logic
function connectToDatabase($host, $dbname, $username, $password, $options, $isSharedHosting, $maxRetries = 3)
{
    $attempt = 0;
    $lastException = null;

    while ($attempt < $maxRetries) {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, $options);
            return ['pdo' => $pdo, 'success' => true];
        } catch (PDOException $e) {
            $lastException = $e;
            $attempt++;

            // Only retry on specific transient errors
            $errorMessage = $e->getMessage();
            $isTransientError = (
                strpos($errorMessage, 'timeout') !== false ||
                strpos($errorMessage, 'timed out') !== false ||
                strpos($errorMessage, "Can't connect") !== false ||
                strpos($errorMessage, 'Connection refused') !== false ||
                strpos($errorMessage, 'Too many connections') !== false
            );

            if (!$isTransientError || $attempt >= $maxRetries) {
                // Non-transient error or max retries reached
                break;
            }

            // Exponential backoff: wait 1s, 2s, 4s
            $waitTime = pow(2, $attempt - 1);
            // Sanitize error message if function exists, otherwise use as-is
            $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($errorMessage) : $errorMessage;
            error_log("Database connection attempt $attempt failed, retrying in {$waitTime} seconds: " . $sanitized_error);
            sleep($waitTime);
        }
    }

    return ['pdo' => null, 'success' => false, 'exception' => $lastException];
}

try {

    // Check if shared hosting optimizations should be enabled
    $isSharedHosting = defined('SHARED_HOSTING') && SHARED_HOSTING === true;

    if ($isSharedHosting) {
        // Enhanced options for shared hosting reliability and performance
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false, // Use real prepared statements
            PDO::ATTR_PERSISTENT => true, // Use persistent connections

            // Connection timeout settings (important for shared hosting)
            PDO::ATTR_TIMEOUT => 10, // 10 second connection timeout

            // MySQL-specific optimizations for shared hosting
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO'",
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, // Buffer queries for better memory management
            PDO::MYSQL_ATTR_FOUND_ROWS => true, // Return matched rows instead of affected rows

            // Connection management for shared hosting
            PDO::MYSQL_ATTR_COMPRESS => true, // Enable compression to reduce bandwidth
            PDO::MYSQL_ATTR_LOCAL_INFILE => false, // Disable LOAD DATA LOCAL INFILE for security
        ];

        // Add SSL options if available (many shared hosts support this now)
        if (defined('DB_SSL_ENABLED') && DB_SSL_ENABLED) {
            $options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = false; // Often needed for shared hosting
            if (defined('DB_SSL_CA') && DB_SSL_CA) {
                $options[PDO::MYSQL_ATTR_SSL_CA] = DB_SSL_CA;
            }
        }
    } else {
        // Standard options for dedicated/VPS hosting
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false, // Use real prepared statements
            PDO::ATTR_PERSISTENT => true, // Use persistent connections
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
        ];
    }

    // Attempt database connection with retry logic
    $connectionResult = connectToDatabase($host, $dbname, $username, $password, $options, $isSharedHosting);

    if (!$connectionResult['success']) {
        throw $connectionResult['exception'];
    }

    $pdo = $connectionResult['pdo'];

    if ($isSharedHosting) {
        // Set optimized session variables for shared hosting
        try {
            $pdo->exec("SET time_zone = '+00:00'"); // UTC timezone
            $pdo->exec("SET SESSION wait_timeout = 600"); // 10 minutes
            $pdo->exec("SET SESSION interactive_timeout = 600");
            $pdo->exec("SET SESSION net_read_timeout = 30");
            $pdo->exec("SET SESSION net_write_timeout = 30");

            // MySQL 8.0 compatibility: query_cache_type is removed
            $serverVersion = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
            if (version_compare($serverVersion, '8.0.0', '<')) {
                $pdo->exec("SET SESSION query_cache_type = ON");
            }

            $pdo->exec("SET SESSION autocommit = 1");
        } catch (PDOException $e) {
            // Log warning but continue - these are non-critical optimizations
            error_log("Non-critical database session optimization failed: " . $e->getMessage());
        }
    } else {
        // Standard session settings for dedicated/VPS hosting
        try {
            $pdo->exec("SET time_zone = '+00:00'"); // UTC timezone
        } catch (PDOException $e) {
            error_log("Failed to set database timezone: " . $e->getMessage());
        }
    }

} catch (PDOException $e) {
    $callerScript = basename($_SERVER['SCRIPT_NAME']);

    // Sanitize error message to prevent information disclosure
    $errorMessage = $e->getMessage();
    $safeErrorMessage = "Database connection failed";

    // Only log full error details, never expose to users
    if ($isSharedHosting) {
        // Enhanced error handling for shared hosting environments
        // Log full details for debugging, but don't expose to users
        $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($errorMessage) : $errorMessage;
        error_log("Database connection failed: " . $sanitized_error . " | Script: " . $callerScript);

        // Check for common shared hosting issues (for logging only)
        $isConnectionLimit = strpos($errorMessage, 'Too many connections') !== false;
        $isTimeout = strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, 'timed out') !== false;
        $isHostDown = strpos($errorMessage, "Can't connect") !== false;

        if ($isConnectionLimit) {
            error_log("Shared hosting connection limit reached - consider connection pooling optimization");
        } elseif ($isTimeout) {
            error_log("Database connection timeout - shared hosting may be under load");
        } elseif ($isHostDown) {
            error_log("Database host unreachable - shared hosting server may be down");
        }

        // Enhanced debug info for shared hosting - ONLY in DEBUG_MODE
        if (defined('DEBUG_MODE') && DEBUG_MODE) {
            $debugInfo = [
                'hosting_type' => 'shared',
                'error' => $errorMessage,
                'host' => $host,
                'database' => $dbname,
                'username' => $username,
                'connection_limit' => $isConnectionLimit,
                'timeout' => $isTimeout,
                'host_down' => $isHostDown
            ];
            die("Database Error Debug Info: " . json_encode($debugInfo, JSON_PRETTY_PRINT));
        }
    } else {
        // Standard error handling for dedicated/VPS hosting
        // Log full details for debugging, but don't expose to users
        $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($errorMessage) : $errorMessage;
        error_log("Database connection failed: " . $sanitized_error);

        // Standard debug info - ONLY in DEBUG_MODE
        if (defined('DEBUG_MODE') && DEBUG_MODE) {
            die("Database Error: " . $errorMessage . "<br>Host: '$host'<br>Database: '$dbname'<br>Username: '$username'");
        }
    }

    // Ensure PDO is null on failure
    $pdo = null;

} catch (Exception $e) {
    // Catch any other exceptions
    $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($e->getMessage()) : $e->getMessage();
    error_log("Unexpected database error: " . $sanitized_error);
    $pdo = null;
}

// Connection health check function (available for both hosting types)
function checkDatabaseHealth()
{
    global $pdo;

    if (!$pdo) {
        return ['status' => 'disconnected', 'message' => 'No database connection'];
    }

    try {
        $stmt = $pdo->query("SELECT 1");
        $result = $stmt->fetch();

        if ($result) {
            return ['status' => 'healthy', 'message' => 'Database connection is active'];
        } else {
            return ['status' => 'error', 'message' => 'Database query failed'];
        }
    } catch (PDOException $e) {
        $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($e->getMessage()) : $e->getMessage();
        error_log("Database health check failed: " . $sanitized_error);
        return ['status' => 'error', 'message' => 'Database health check failed'];
    }
}

// Function to get connection info (enhanced for shared hosting when enabled)
function getDatabaseConnectionInfo()
{
    global $pdo;

    if (!$pdo) {
        return ['connected' => false];
    }

    $isSharedHosting = defined('SHARED_HOSTING') && SHARED_HOSTING === true;

    try {
        $info = [
            'connected' => true,
            'hosting_type' => $isSharedHosting ? 'shared' : 'dedicated/vps',
            'server_version' => $pdo->getAttribute(PDO::ATTR_SERVER_VERSION),
            'connection_status' => $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS),
            'persistent' => $pdo->getAttribute(PDO::ATTR_PERSISTENT),
        ];

        if ($isSharedHosting) {
            // Get additional MySQL-specific info for shared hosting monitoring
            $stmt = $pdo->query("SELECT CONNECTION_ID() as connection_id, @@wait_timeout as wait_timeout, @@max_connections as max_connections, @@query_cache_type as query_cache_type");
            $mysqlInfo = $stmt->fetch();

            if ($mysqlInfo) {
                $info = array_merge($info, $mysqlInfo);
            }
        } else {
            // Basic info for dedicated/VPS hosting
            $stmt = $pdo->query("SELECT CONNECTION_ID() as connection_id");
            $mysqlInfo = $stmt->fetch();

            if ($mysqlInfo) {
                $info = array_merge($info, $mysqlInfo);
            }
        }

        return $info;
    } catch (PDOException $e) {
        $sanitized_error = function_exists('sanitizeLogMessage') ? sanitizeLogMessage($e->getMessage()) : $e->getMessage();
        error_log("Failed to get database connection info: " . $sanitized_error);
        return ['connected' => true, 'error' => 'Could not retrieve connection details'];
    }
}
?>