<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

define('APP_NAME', 'WISHNET - Billing System');

define('DEBUG', true);

$envHost = getenv('DB_HOST') !== false ? getenv('DB_HOST') : 'localhost'; // hosting biasa pakai localhost
$envName = getenv('DB_NAME') !== false ? getenv('DB_NAME') : 'supplie3_isp_billing'; // GANTI SESUAI DB lo
$envUser = getenv('DB_USER') !== false ? getenv('DB_USER') : 'supplie3_supplie3';    // GANTI SESUAI USER lo
$envPass = getenv('DB_PASS') !== false ? getenv('DB_PASS') : 'Yoga24434@';          // GANTI SESUAI PASSWORD user DB lo

define('DB_HOST', $envHost);
define('DB_NAME', $envName);
define('DB_USER', $envUser);
define('DB_PASS', $envPass);

$documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? rtrim(str_replace('\\\\', '/', $_SERVER['DOCUMENT_ROOT']), '/') : '';
$appRoot = rtrim(str_replace('\\\\', '/', realpath(__DIR__ . '/..')), '/');

$basePath = '';
if ($documentRoot !== '') {
    $relative = preg_replace('#^' . preg_quote($documentRoot, '#') . '#i', '', $appRoot, 1);
    if ($relative !== null && $relative !== $appRoot) {
        $relative = trim($relative, '/');
        $basePath = $relative === '' ? '' : '/' . $relative;
    }
}

if ($basePath === '') {
    $basePath = '/' . trim(basename($appRoot), '/');
    if ($basePath === '/') {
        $basePath = '';
    }
}

define('BASE_PATH', rtrim($basePath, '/'));
define('UPLOAD_DIR', __DIR__ . '/../uploads/');

$__db_connection = null;

function get_db_connection(): mysqli
{
    global $__db_connection;

    if (!$__db_connection instanceof mysqli) {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

        try {
            $__db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            $__db_connection->set_charset('utf8mb4');
        } catch (mysqli_sql_exception $e) {
            if (DEBUG) {
                die('[DB] Connection error: ' . $e->getMessage());
            }

            error_log('Database connection failed: ' . $e->getMessage());
            die('[DB] Connection error. Please contact the administrator.');
        }
    }

    return $__db_connection;
}

function close_db_connection(): void
{
    global $__db_connection;

    if ($__db_connection instanceof mysqli) {
        $__db_connection->close();
        $__db_connection = null;
    }
}
?>

