<?php
require_once __DIR__ . '/config.php';

function db() {
    static $pdo = null;
    if ($pdo === null) {
        $isNew = !file_exists(DB_PATH);
        $pdo = new PDO('sqlite:' . DB_PATH);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec('PRAGMA journal_mode = WAL');
        db_init_schema($pdo);
    }
    return $pdo;
}

function db_init_schema($pdo) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS news (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        guid TEXT UNIQUE,
        title TEXT NOT NULL,
        slug TEXT,
        summary TEXT,
        content TEXT,
        link TEXT,
        image TEXT,
        source TEXT,
        published_at TEXT,
        created_at TEXT DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_news_published ON news(published_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_news_slug ON news(slug)");

    $pdo->exec("CREATE TABLE IF NOT EXISTS games (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        slug TEXT UNIQUE,
        name TEXT NOT NULL,
        category TEXT,
        description TEXT,
        play_url TEXT,
        gplay_url TEXT,
        appstore_url TEXT,
        views INTEGER DEFAULT 0,
        created_at TEXT DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_games_name ON games(name)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_games_category ON games(category)");

    $pdo->exec("CREATE TABLE IF NOT EXISTS meta (
        k TEXT PRIMARY KEY,
        v TEXT
    )");
}

function meta_get($key, $default = null) {
    $stmt = db()->prepare("SELECT v FROM meta WHERE k = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? $row['v'] : $default;
}

function meta_set($key, $value) {
    $stmt = db()->prepare("INSERT INTO meta (k, v) VALUES (?, ?)
        ON CONFLICT(k) DO UPDATE SET v = excluded.v");
    $stmt->execute([$key, $value]);
}
