<?php

namespace App\Controller;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class ContentController
{
    public function getContent(Request $request, Response $response, array $args): Response
    {
        // Access PDO from global scope or container
        $pdo = new \PDO('sqlite:' . __DIR__ . '/../../data.sqlite3');
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $key = $args['key'];
        $stmt = $pdo->prepare('SELECT content FROM contents WHERE key = :key');
        $stmt->execute(['key' => $key]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($row) {
            $response->getBody()->write($row['content']);
            return $response->withHeader('Content-Type', 'application/json');
        } else {
            $response->getBody()->write(json_encode(['error' => 'Not found']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
    }
}
