<?php
namespace App;

use PDO;

function get_mysql_env(): array
{
    static $env = null;
    if ($env !== null) {
        return $env;
    }

    $fileEnv = @parse_ini_file(__DIR__ . '/../.env', INI_SCANNER_RAW) ?: [];

    $env = [
        'MYSQL_HOST' => getenv('MYSQL_HOST') ?: ($fileEnv['MYSQL_HOST'] ?? '127.0.0.1'),
        'MYSQL_PORT' => getenv('MYSQL_PORT') ?: ($fileEnv['MYSQL_PORT'] ?? '3306'),
        'MYSQL_DATABASE' => getenv('MYSQL_DATABASE') ?: ($fileEnv['MYSQL_DATABASE'] ?? 'invitaci_event_tech'),
        'MYSQL_USER' => getenv('MYSQL_USER') ?: ($fileEnv['MYSQL_USER'] ?? 'root'),
        'MYSQL_PASSWORD' => getenv('MYSQL_PASSWORD') ?: ($fileEnv['MYSQL_PASSWORD'] ?? ''),
        'STRIPE_WEBHOOK_SECRET' => getenv('STRIPE_WEBHOOK_SECRET') ?: ($fileEnv['STRIPE_WEBHOOK_SECRET'] ?? ''),
    ];

    return $env;
}

function get_mysql_db(): PDO
{
    static $pdo = null;
    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $env = get_mysql_env();
    $dsn = sprintf(
        'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4',
        $env['MYSQL_HOST'],
        $env['MYSQL_PORT'],
        $env['MYSQL_DATABASE']
    );

    $pdo = new PDO($dsn, (string)$env['MYSQL_USER'], (string)$env['MYSQL_PASSWORD'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    return $pdo;
}
