<?php
declare(strict_types=1);

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

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

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

        $host = (string)env_value('MASTER_DB_HOST', env_value('DB_HOST', 'localhost'));
        $db   = (string)env_value('MASTER_DB_NAME', '');
        $user = (string)env_value('MASTER_DB_USER', '');
        $pass = (string)env_value('MASTER_DB_PASS', '');
        $charset = (string)env_value('MASTER_DB_CHARSET', 'utf8mb4');

        if ($host === '' || $db === '' || $user === '') {
            throw new RuntimeException('Konfigurasi database master HR belum lengkap. Isi MASTER_DB_HOST, MASTER_DB_NAME, MASTER_DB_USER, dan MASTER_DB_PASS di file .env.');
        }

        $pdo = new PDO(
            "mysql:host={$host};dbname={$db};charset={$charset}",
            $user,
            $pass,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]
        );

        return $pdo;
    }
}
