<?php

declare(strict_types=1);

class AdminCommentController
{
    public static function routes(): void
    {
        Router::get('/admin/comments', [self::class, 'index']);
        Router::post('/admin/comments/{id}/approve', [self::class, 'approve']);
        Router::post('/admin/comments/{id}/spam', [self::class, 'spam']);
        Router::post('/admin/comments/{id}/delete', [self::class, 'destroy']);
        Router::post('/admin/comments/bulk-delete', [self::class, 'bulkDelete']);
    }

    public static function index(): void
    {
        Auth::requireAdmin();
        $status = $_GET['status'] ?? '';
        $total = Comment::count($status);
        $pagination = Pagination::fromRequest($total, 100);
        Router::render('admin/comments', [
            'pageTitle' => 'Comments', 'activeMenu' => 'comments', 'contentTemplate' => '_comments',
            'comments' => Comment::all($pagination->perPage, $pagination->offset, $status),
            'pagination' => $pagination, 'status' => $status,
        ]);
    }

    public static function approve(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/comments'); }
        Comment::approve((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Comment approved.'];
        Router::redirect('/admin/comments');
    }

    public static function spam(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/comments'); }
        Comment::spam((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Comment marked as spam.'];
        Router::redirect('/admin/comments');
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/comments'); }
        Comment::delete((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Comment deleted successfully.'];
        Router::redirect('/admin/comments');
    }

    public static function bulkDelete(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { http_response_code(403); echo json_encode(['error' => 'CSRF']); return; }
        $input = json_decode(file_get_contents('php://input'), true);
        $ids = array_filter(array_map('intval', $input['ids'] ?? []), fn($id) => $id > 0);
        $result = BulkDelete::run($ids, static fn(array $batch): int => BulkDelete::rows('comments', $batch));
        $_SESSION['flash'] = ['type' => 'success', 'message' => BulkDelete::message($result, 'comment', 'comments')];
        echo json_encode(BulkDelete::payload($result));
    }
}
