<?php
class AssetTypesController extends Controller
{
    public function indexAction()
    {
        $rows = (new AssetTypes())->all();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('AssetTypes/index', ['page_title' => 'Asset Types', 'rows' => $rows]);
    }

    public function saveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $this->assertAdminOrPmPc();
            $id = (new AssetTypes())->save([
                'c0d'         => (int)($_POST['c0d'] ?? 0),
                'code'        => (string)($_POST['code'] ?? ''),
                'name'        => (string)($_POST['name'] ?? ''),
                'description' => (string)($_POST['description'] ?? ''),
                'icon'        => (string)($_POST['icon'] ?? ''),
                'is_active'   => !empty($_POST['is_active']) ? 1 : 0,
            ], $this->currentUserId());
            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->assertAdminOrPmPc();
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            (new AssetTypes())->delete($id);
            echo json_encode(['ok' => true]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    private function assertAdminOrPmPc(): 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 asset types.');
    }
}
