<?php

declare(strict_types=1);

trait AnimalLifecycleActions
{
    public static function delete(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            http_response_code(405);
            return;
        }

        $id = (int) ($_POST['id'] ?? 0);
        if ($id <= 0) {
            http_response_code(400);
            return;
        }

        $db = DB::pdo();

        $reason = trim((string) ($_POST['reason'] ?? ''));
        $db->prepare(
            "
        UPDATE animals
        SET deleted_at = datetime('now'),
                     archived_at = NULL,
                     deletion_reason = :reason,
                     updated_at = datetime('now')
        WHERE id = :id
        ",
        )->execute([':id' => $id, ':reason' => $reason !== '' ? $reason : null]);

        self::logHistory($id, 'delete', 'Animal placé dans la corbeille', $reason);

        header('Location: /animals');
        exit();
    }

    public static function archive(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            http_response_code(405);
            return;
        }
        $id = (int) ($_POST['id'] ?? 0);
        if ($id <= 0) {
            http_response_code(400);
            return;
        }
        $db = DB::pdo();
        $db->prepare(
            "
        UPDATE animals SET archived_at = datetime('now'), deleted_at = NULL,
                           deletion_reason = NULL, updated_at = datetime('now')
        WHERE id = :id
        ",
        )->execute([':id' => $id]);
        self::logHistory($id, 'update', 'Animal archivé');
        header('Location: /animals');
        exit();
    }

    public static function restore(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            http_response_code(405);
            return;
        }
        $id = (int) ($_POST['id'] ?? 0);
        if ($id <= 0) {
            http_response_code(400);
            return;
        }
        $db = DB::pdo();
        $db->prepare(
            "
        UPDATE animals SET archived_at = NULL, deleted_at = NULL,
                           deletion_reason = NULL, updated_at = datetime('now')
        WHERE id = :id
        ",
        )->execute([':id' => $id]);
        self::logHistory($id, 'update', 'Animal restauré');
        header('Location: /animals');
        exit();
    }
}
