<?php
declare(strict_types=1);

// config/database.php
// KHUSUS database aplikasi Keperawatan (bukan master HR).
// Sejak Step 3, credential dibaca dari .env agar tidak tersimpan di Git/source code.

$envFile = __DIR__ . '/env.php';
if (is_file($envFile)) {
    require_once $envFile;
}

if (!defined('DB_HOST')) {
    define('DB_HOST', (string)env_value('DB_HOST', 'localhost'));
}
if (!defined('DB_USER')) {
    define('DB_USER', (string)env_value('DB_USER', ''));
}
if (!defined('DB_PASS')) {
    define('DB_PASS', (string)env_value('DB_PASS', ''));
}
if (!defined('DB_NAME')) {
    define('DB_NAME', (string)env_value('DB_NAME', ''));
}
if (!defined('DB_CHARSET')) {
    define('DB_CHARSET', (string)env_value('DB_CHARSET', 'utf8mb4'));
}

if (!function_exists('db_config_ready')) {
    function db_config_ready(): bool
    {
        return DB_HOST !== '' && DB_USER !== '' && DB_NAME !== '';
    }
}

if (!function_exists('getAppConnection')) {
    function getAppConnection(): mysqli
    {
        static $conn = null;

        if ($conn instanceof mysqli) {
            return $conn;
        }

        if (!db_config_ready()) {
            throw new RuntimeException('Konfigurasi database aplikasi belum lengkap. Buat file .env dari .env.example lalu isi DB_HOST, DB_NAME, DB_USER, dan DB_PASS.');
        }

        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        $conn->set_charset(DB_CHARSET);
        return $conn;
    }
}

if (!function_exists('getConnection')) {
    function getConnection(): mysqli
    {
        return getAppConnection();
    }
}

if (!function_exists('getAppConnectionPDO')) {
    function getAppConnectionPDO(): PDO
    {
        static $pdo = null;

        if ($pdo instanceof PDO) {
            return $pdo;
        }

        if (!db_config_ready()) {
            throw new RuntimeException('Konfigurasi database aplikasi belum lengkap. Buat file .env dari .env.example lalu isi DB_HOST, DB_NAME, DB_USER, dan DB_PASS.');
        }

        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
        return $pdo;
    }
}

if (!function_exists('getConnectionPDO')) {
    function getConnectionPDO(): PDO
    {
        return getAppConnectionPDO();
    }
}
