<?php
declare(strict_types=1);

use Slim\App;
use Slim\Psr7\Request;
use Slim\Psr7\Response;
use App\Models\Post;
use Slim\Views\Twig;

return function (App $app) {

    // -------------------------------------------------
    // Page admin – tableau de bord
    // -------------------------------------------------
    $app->get('/admin', function (Request $request, Response $response) use ($app) {
        $posts = Post::orderByDesc('id')->get();

        /** @var Twig $view */
        $view = $request->getAttribute('view');
        return $view->render($response, 'pages/admin.twig', ['posts' => $posts]);
    });

    // -------------------------------------------------
    // Création d'un article (POST depuis admin)
    // -------------------------------------------------
    $app->post('/admin/create', function (Request $request, Response $response) {
        $data = $request->getParsedBody();

        Post::create([
            'title'   => $data['title'],
            'content' => $data['content'],
        ]);

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

    // -------------------------------------------------
    // Formulaire d'édition (GET depuis admin)
    // -------------------------------------------------
    $app->get('/admin/edit/{id}', function (Request $request, Response $response, $args) use ($app) {
        $id   = (int)$args['id'];
        $post = $id ? Post::findOrFail($id) : null;   // id=0 → création

        /** @var Twig $view */
        $view = $request->getAttribute('view');

        return $view->render($response, 'pages/post_form.twig', [
            'action' => $id ? "/admin/edit/{$id}" : "/admin/create",
            'post'   => $post,
        ]);
    });

    // -------------------------------------------------
    // Enregistrement des modifications (POST depuis admin)
    // -------------------------------------------------
    $app->post('/admin/edit/{id}', function (Request $request, Response $response, $args) {
        $post = Post::findOrFail($args['id']);
        $data = $request->getParsedBody();

        $post->update([
            'title'   => $data['title'],
            'content' => $data['content'],
        ]);

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

    // -------------------------------------------------
    // Suppression d'un article (POST depuis admin)
    // -------------------------------------------------
    $app->post('/admin/delete/{id}', function (Request $request, Response $response, $args) {
        $post = Post::findOrFail($args['id']);
        $post->delete();

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