<?php
/**
 * Blog DB connection — reads credentials from the parent EduTrack .env file.
 * Returns a shared mysqli singleton.
 */

function blog_db(): mysqli
{
    static $conn = null;
    if ($conn !== null) return $conn;

    // Parse parent .env (INI-style with semicolons as comment character)
    $env_file = __DIR__ . '/../../.env';
    if (!file_exists($env_file)) {
        throw new RuntimeException('EduTrack .env not found at: ' . $env_file);
    }

    $lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $env   = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, ';') || str_starts_with($line, '#')) continue;
        if (!str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $env[trim($k)] = trim($v, " \t\n\r\0\x0B\"'");
    }

    $host = $env['DB_HOST'] ?? 'localhost';
    $user = $env['DB_USER'] ?? 'root';
    $pass = $env['DB_PASS'] ?? '';
    $name = $env['DB_NAME'] ?? '';

    $conn = new mysqli($host, $user, $pass, $name);
    if ($conn->connect_error) {
        throw new RuntimeException('Blog DB connect error: ' . $conn->connect_error);
    }
    $conn->set_charset('utf8mb4');
    return $conn;
}

function blog_groq_key(): string
{
    static $key = null;
    if ($key !== null) return $key;

    $env_file = __DIR__ . '/../../.env';
    $lines    = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if (str_starts_with($line, 'GROQ_API_KEY=')) {
            $key = trim(substr($line, strlen('GROQ_API_KEY=')), " \t\"'");
            return $key;
        }
    }
    return '';
}
