<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}


function pdo(): PDO {
    static $pdo_connection = null;

    if ($pdo_connection === null) {

        if (!defined('DB_HOST')) {

           if (file_exists(__DIR__ . '/../../config.php')) {
                 require_once __DIR__ . '/../../config.php';
             } else {
                 die('Database configuration constants are not defined.');
             }
        }

        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
        ];
        try {
            $pdo_connection = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {

            if (defined('ERROR_LOG_PATH')) {
                 file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CRITICAL DB Connection Error: " . $e->getMessage() . "\n", FILE_APPEND);
            }

            die("Database connection failed. Please contact support or check error logs.");
        }
    }
    return $pdo_connection;
}
?>