<?php
declare(strict_types=1);

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface  as Request;
use Slim\Views\Twig;
use App\Models\Post;

/**
 * Contrôleur dédié à la gestion des articles.
 */
class PostController
{
    private Twig $view;

    public function __construct(Twig $view)
    {
        $this->view = $view;
    }

    /** Page publique – liste des articles */
    public function index(Request $request, Response $response): Response
    {
        $posts = Post::allDesc();
        return $this->view->render($response, 'pages/home.twig', ['posts' => $posts]);
    }

    /** Tableau de bord admin */
    public function admin(Request $request, Response $response): Response
    {
        $posts = Post::allDesc();
        return $this->view->render($response, 'pages/admin.twig', ['posts' => $posts]);
    }

    /** Formulaire création / édition */
    public function form(Request $request, Response $response, array $args): Response
    {
        $id   = (int)($args['id'] ?? 0);
        $post = $id ? Post::find($id) : null;   // id=0 → création

        $action = $id ? "/admin/edit/{$id}" : "/admin/create";

        return $this->view->render($response, 'pages/post_form.twig', [
            'action' => $action,
            'post'   => $post,
        ]);
    }

    /** Enregistrement d’un nouvel article */
    public function create(Request $request, Response $response): Response
    {
        $data = $request->getParsedBody();
        $post = Post::make($data);
        $post->save();

        return $response->withHeader('Location', '/admin')->withStatus(302);
    }

    /** Mise à jour d’un article existant */
    public function update(Request $request, Response $response, array $args): Response
    {
        $post = Post::find((int)$args['id']);
        $post->updateFromArray($request->getParsedBody());
        $post->save();

        return $response->withHeader('Location', '/admin')->withStatus(302);
    }

    /** Suppression d’un article */
    public function delete(Request $request, Response $response, array $args): Response
    {
        $post = Post::find((int)$args['id']);
        $post->delete();

        return $response->withHeader('Location', '/admin')->withStatus(302);
    }
}
