<?php
declare(strict_types=1);

require_once __DIR__ . '/env.php';

function admin_session_start()
{
    if (session_status() === PHP_SESSION_NONE) {
        // Better defaults
        ini_set('session.cookie_httponly', '1');
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
            ini_set('session.cookie_secure', '1');
        }
        session_start();
    }
}

function admin_is_logged_in()
{
    admin_session_start();
    return !empty($_SESSION['db_admin']['ok']);
}

function admin_logout()
{
    admin_session_start();
    unset($_SESSION['db_admin']);
}

function admin_default_creds(): array
{
    $vars = env_load(dirname(__DIR__) . '/.env');

    return [
        'host' => env_get($vars, 'DB_SERVERNAME', 'localhost') ?? 'localhost',
        'port' => (int)(env_get($vars, 'DB_PORT', '3306') ?? '3306'),
        'user' => env_get($vars, 'DB_USERNAME', '') ?? '',
        'pass' => env_get($vars, 'DB_PASSWORD', '') ?? '',
        'db'   => env_get($vars, 'DB_DATABASE', '') ?? '',
    ];
}

function admin_try_login(string $host, int $port, string $user, string $pass, string $db): array
{
    // Basic validation
    if ($host === '' || $port <= 0 || $user === '' || $db === '') {
        return ['ok' => false, 'error' => 'Bitte Host, Port, Benutzer und Datenbank angeben.'];
    }

    $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $host, $port, $db);

    try {
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);

        // smoke query
        $pdo->query('SELECT 1');

        admin_session_start();
        $_SESSION['db_admin'] = [
            'ok' => true,
            'host' => $host,
            'port' => $port,
            'user' => $user,
            'pass' => $pass,
            'db' => $db,
        ];

        return ['ok' => true, 'error' => null];
    } catch (Throwable $e) {
        return ['ok' => false, 'error' => 'Login fehlgeschlagen: ' . $e->getMessage()];
    }
}

function admin_pdo(): PDO
{
    admin_session_start();
    if (empty($_SESSION['db_admin']['ok'])) {
        throw new RuntimeException('Nicht eingeloggt');
    }

    $host = (string)$_SESSION['db_admin']['host'];
    $port = (int)$_SESSION['db_admin']['port'];
    $db   = (string)$_SESSION['db_admin']['db'];
    $user = (string)$_SESSION['db_admin']['user'];
    $pass = (string)$_SESSION['db_admin']['pass'];

    $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $host, $port, $db);

    return new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
}
