<?php
// Generated by setup_mariadb_project.sh — edit as needed.
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'app_31009');
define('DB_USER', 'app_31009');
define('DB_PASS', '2c66b530-2a65-423a-a106-6760b49ad1a2');

function db() {
    static $pdo;
    if ($pdo) {
        return $pdo;
    }

    try {
        $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    } catch (PDOException $e) {
        if ($e->getCode() === 1049) { // SQLSTATE[HY000] [1049] Unknown database
            try {
                $tempPdo = new PDO('mysql:host='.DB_HOST, DB_USER, DB_PASS, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                ]);
                $tempPdo->exec('CREATE DATABASE IF NOT EXISTS `'.DB_NAME.'`');
                
                // Now, reconnect to the newly created database
                $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]);
            } catch (PDOException $e) {
                // If database creation also fails, re-throw the exception
                throw $e;
            }
        } else {
            // For any other PDO exception, re-throw it
            throw $e;
        }
    }

    return $pdo;
}
