<?php
class SparePartsController extends Controller
{
    public function indexAction()
    {
        $atId   = isset($_GET['asset_type_id']) && $_GET['asset_type_id'] !== '' ? (int)$_GET['asset_type_id'] : null;
        $search = trim((string)($_GET['q'] ?? ''));
        $rows   = (new SpareParts())->list(false, $atId, $search);
        $types  = (new AssetTypes())->all(true);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('SpareParts/index', [
            'page_title'  => 'Spare Parts Catalogue',
            'rows'        => $rows,
            'asset_types' => $types,
            'filter_at'   => $atId,
            'search'      => $search,
        ]);
    }

    public function saveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $this->assertRole();
            $id = (new SpareParts())->save($_POST, $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->assertRole();
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            (new SpareParts())->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','procurement'], true))
            throw new RuntimeException('Only Admin / PM / PC / Procurement can edit spare parts.');
    }
}
