<?php

declare(strict_types=1);

class AdminInboxController
{
    public static function routes(): void
    {
        Router::get('/admin/inbox', [self::class, 'index']);
    }

    public static function index(): void
    {
        Auth::requireAdmin();

        $tab = $_GET['tab'] ?? 'messages';
        if (!in_array($tab, ['messages', 'reports'], true)) {
            $tab = 'messages';
        }

        $unreadMessages = ContactMessage::countUnread();
        $pendingReports = Report::countPending();

        $data = [
            'pageTitle'       => 'Inbox',
            'activeMenu'      => 'inbox',
            'contentTemplate' => '_inbox',
            'currentTab'      => $tab,
            'unreadMessages'  => $unreadMessages,
            'pendingReports'  => $pendingReports,
        ];

        if ($tab === 'messages') {
            $filterUnread = ($_GET['filter'] ?? '') === 'unread';
            $total = ContactMessage::count($filterUnread);
            $pagination = Pagination::fromRequest($total, 20);
            $messages = ContactMessage::all($pagination->perPage, $pagination->offset, $filterUnread);
            $data['messages'] = $messages;
            $data['pagination'] = $pagination;
            $data['totalMessages'] = ContactMessage::count();
            $data['filterUnread'] = $filterUnread;
        } else {
            $filters = [];
            if (!empty($_GET['status'])) {
                $filters['status'] = $_GET['status'];
            }
            if (!empty($_GET['reason'])) {
                $filters['reason'] = $_GET['reason'];
            }
            $total = Report::count($filters);
            $pagination = Pagination::fromRequest($total, 20);
            $reports = Report::all($filters, $pagination->perPage, $pagination->offset);
            $data['reports'] = $reports;
            $data['pagination'] = $pagination;
            $data['totalReports'] = $total;
            $data['currentStatus'] = $_GET['status'] ?? 'all';
            $data['currentReason'] = $_GET['reason'] ?? 'all';
            $data['pendingCount'] = $pendingReports;
        }

        Router::render('admin/inbox', $data);
    }
}
