<?php

declare(strict_types=1);

namespace App\Application\Actions\Content;

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

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

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

    public function list(Request $request, Response $response, array $args): Response
    {
        $stmt = $this->pdo->query('SELECT * FROM contents ORDER BY id DESC');
        $contents = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $html = $this->twig->render('admin/contents_list.twig', ['contents' => $contents]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }

    public function create(Request $request, Response $response, array $args): Response
    {
        $error = null;
        if ($request->getMethod() === 'POST') {
            $data = $request->getParsedBody();
            $key = $data['key'] ?? '';
            $content = $data['value'] ?? '';
            if (!$key || !$content) {
                $error = 'Key and content are required.';
            } elseif (!preg_match('/^[a-z_]+$/', $key)) {
                $error = 'Key must be all lowercase letters and underscores only.';
            } else {
                $stmt = $this->pdo->prepare('INSERT INTO contents (key, content) VALUES (:key, :content)');
                $stmt->execute([':key' => $key, ':content' => $content]);
                return $response->withHeader('Location', '/admin/contents')->withStatus(302);
            }
        }
        $html = $this->twig->render('admin/contents_create.twig', ['error' => $error]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }

    public function edit(Request $request, Response $response, array $args): Response
    {
        $id = $args['id'] ?? null;
        $error = null;
        $stmt = $this->pdo->prepare('SELECT * FROM contents WHERE id = :id');
        $stmt->execute([':id' => $id]);
        $content = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$content) {
            $response->getBody()->write('Not found');
            return $response->withStatus(404);
        }
        if ($request->getMethod() === 'POST') {
            $data = $request->getParsedBody();
            $key = $data['key'] ?? '';
            $contentValue = $data['value'] ?? '';
            if (!$key || !$contentValue) {
                $error = 'Key and content are required.';
            } elseif (!preg_match('/^[a-z_]+$/', $key)) {
                $error = 'Key must be all lowercase letters and underscores only.';
            } else {
                $stmt = $this->pdo->prepare('UPDATE contents SET key = :key, content = :content WHERE id = :id');
                $stmt->execute([':key' => $key, ':content' => $contentValue, ':id' => $id]);
                return $response->withHeader('Location', '/admin/contents')->withStatus(302);
            }
        }
        $html = $this->twig->render('admin/contents_edit.twig', ['content' => $content, 'error' => $error]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }

    public function delete(Request $request, Response $response, array $args): Response
    {
        $id = $args['id'] ?? null;
        $stmt = $this->pdo->prepare('DELETE FROM contents WHERE id = :id');
        $stmt->execute([':id' => $id]);
        return $response->withHeader('Location', '/admin/contents')->withStatus(302);
    }
}
