<?php
// config.php - Configuration and database initialization for Team Mania Pro

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$is_demo = isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true;
$lock_file = __DIR__ . '/data/install.lock';

if ($is_demo) {
    // Session-specific database for demo playground
    $db_file = __DIR__ . '/data/demo_' . session_id() . '.sqlite';
} else {
    $db_file = __DIR__ . '/data/club.sqlite';
    // Redirect to installer if not installed (only in non-demo mode)
    if (!file_exists($lock_file) && basename($_SERVER['PHP_SELF']) !== 'install.php') {
        header("Location: install.php");
        exit;
    }
}

// Garbage collection for old demo databases (1% chance)
if (rand(1, 100) === 1) {
    foreach (glob(__DIR__ . '/data/demo_*.sqlite') as $file) {
        if (time() - filemtime($file) > 7200) { // Older than 2 hours
            @unlink($file);
        }
    }
}

// Database Connection
$pdo = null;
try {
    // Create data directory if not exists
    if (!file_exists(__DIR__ . '/data')) {
        mkdir(__DIR__ . '/data', 0777, true);
    }
    
    // Only connect if db exists or if it is demo mode (which auto-initializes)
    if (file_exists($db_file) || $is_demo) {
        $pdo = new PDO("sqlite:" . $db_file);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec("PRAGMA foreign_keys = ON;");
    }
} catch (PDOException $e) {
    die("Datenbankverbindung fehlgeschlagen: " . $e->getMessage());
}

// Settings Helpers
$settings_cache = null;

function get_settings() {
    global $pdo, $settings_cache;
    if ($settings_cache !== null) {
        return $settings_cache;
    }
    if (!$pdo) return [];

    $settings_cache = [];
    try {
        $stmt = $pdo->query("SELECT key, value FROM settings");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings_cache[$row['key']] = $row['value'];
        }
    } catch (PDOException $e) {
        // Table might not exist yet during install
    }
    return $settings_cache;
}

function get_setting($key, $default = '') {
    $settings = get_settings();
    return $settings[$key] ?? $default;
}

function set_setting($key, $value) {
    global $pdo, $settings_cache;
    if (!$pdo) return false;
    
    $stmt = $pdo->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (:key, :value)");
    $result = $stmt->execute([':key' => $key, ':value' => (string)$value]);
    if ($result && $settings_cache !== null) {
        $settings_cache[$key] = (string)$value;
    }
    return $result;
}

