<?php
class DocExpiriesController extends Controller
{
    public function indexAction()
    {
        $m = new DocExpiries();
        $filter = trim((string)($_GET['bucket'] ?? ''));
        $rows   = $m->listAll(false);

        // Apply bucket filter in-memory (the source is a UNION, so no direct WHERE)
        if ($filter !== '' && $filter !== 'all') {
            $rows = array_values(array_filter($rows, function ($r) use ($filter) {
                $d = (int)$r['days_remaining'];
                return match ($filter) {
                    'expired' => $d < 0,
                    '0_7'     => $d >= 0  && $d <= 7,
                    '8_14'    => $d >= 8  && $d <= 14,
                    '15_30'   => $d >= 15 && $d <= 30,
                    '30_plus' => $d > 30,
                    default   => true,
                };
            }));
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('DocExpiries/index', [
            'page_title' => 'Document Expiries',
            'rows'       => $rows,
            'buckets'    => $m->bucketCounts(),
            'filter'     => $filter,
        ]);
    }

    public function sweepNowAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('DocExpiries'); return; }
        $r = (new DocExpiries())->sweep();
        $_SESSION['flash_tenant_msg']  = "Sweep ran · {$r['emitted']} alert(s) emitted · {$r['skipped']} suppressed by cooldown.";
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('DocExpiries');
    }
}
