<?php
function get_db_connection(): ?mysqli {
    // Priority 1: Use config.php constants if they exist
    if (file_exists(__DIR__ . '/config.php')) {
        require_once __DIR__ . '/config.php';
    }

    $host = defined('DB_HOST') ? DB_HOST : (getenv('DB_HOST') ?: 'localhost');
    $user = defined('DB_USER') ? DB_USER : (getenv('DB_USER') ?: 'imefotxb_tpieceuser1');
    $pass = defined('DB_PASS') ? DB_PASS : (getenv('DB_PASS') ?: '6xKf_b?rGQLn');
    $db   = defined('DB_NAME') ? DB_NAME : (getenv('DB_NAME') ?: 'imefotxb_tpiece');

    // On cPanel, we must connect directly to the database.
    // CREATE DATABASE is usually restricted for the DB user.
    $mysqli = @new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_errno) {
        // Log the error for easier debugging on cPanel
        error_log("Database connection failed: " . $mysqli->connect_error);
        return null;
    }

    // Ensure proper charset
    $mysqli->set_charset('utf8mb4');

    return $mysqli;
}