<?php

declare(strict_types=1);

namespace App\Application\Actions;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Twig\Environment;
use PDO;

class IndexAction
{
    private Environment $twig;
    private PDO $pdo;

    public function __construct(Environment $twig, PDO $pdo)
    {
        $this->twig = $twig;
        $this->pdo = $pdo;
    }

    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $stmt = $this->pdo->prepare('SELECT * FROM contents WHERE key = :key ORDER BY id DESC LIMIT 1');
        $stmt->execute([':key' => 'links']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $links = $row ? json_decode($row['content'], true) : [];

        $html = $this->twig->render('index.twig', ['links' => $links]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }
}
