<?php
// Check if function already exists to prevent redeclaration
if (!function_exists('getDbConnection')) {
    
    // Database configuration
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "shopnest_db";

    // Create connection with error reporting
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {
        $conn = mysqli_connect($host, $username, $password, $database);
        
        if (!$conn) {
            throw new Exception("Database connection failed: " . mysqli_connect_error());
        }
        
        // Set charset to UTF-8
        mysqli_set_charset($conn, "utf8mb4");
        
        // Set timezone for MySQL
        mysqli_query($conn, "SET time_zone = '+05:30'");
        
    } catch (Exception $e) {
        // Log error
        error_log("Database connection failed: " . $e->getMessage());
        
        // Display user-friendly error
        die("<div style='text-align: center; padding: 50px; font-family: Arial;'>
                <h2 style='color: #dc3545;'>Database Connection Error</h2>
                <p>We're experiencing technical difficulties. Please check:</p>
                <ul style='text-align: left; display: inline-block;'>
                    <li>Database name: <strong>$database</strong></li>
                    <li>Username: <strong>$username</strong></li>
                    <li>Host: <strong>$host</strong></li>
                </ul>
                <p><small style='color: #666;'>Error: " . htmlspecialchars($e->getMessage()) . "</small></p>
                <a href='complete-database-setup.php' style='padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px;'>Setup Database</a>
             </div>");
    }

    // Global helper function to include db connection
    function getDbConnection() {
        global $conn;
        return $conn;
    }
    
} else {
    // Function already exists, just get the connection
    $conn = getDbConnection();
}
?>