<?php
class CalloutCategoriesController extends Controller
{
    public function indexAction()
    {
        $rows = (new CalloutCategories())->all();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CalloutCategories/index', ['page_title' => 'Callout Categories · SLA Matrix', 'rows' => $rows]);
    }

    public function saveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $this->assertRole();
            $id = (new CalloutCategories())->save($_POST);
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function deleteAjAction()
    {
        header('Content-Type: application/json');
        try {
            $this->assertRole();
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            (new CalloutCategories())->delete($id);
            echo json_encode(['ok' => true]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    private function assertRole(): void
    {
        $g = strtolower(trim($this->currentUserGroup()));
        if (!in_array($g, ['administrator','project manager','projects coordinator'], true))
            throw new RuntimeException('Only Admin / PM / PC can edit callout categories.');
    }
}
