<?php
class ServicePacksController extends Controller
{
    public function indexAction()
    {
        $atId = isset($_GET['asset_type_id']) && $_GET['asset_type_id'] !== '' ? (int)$_GET['asset_type_id'] : null;
        $rows = (new ServicePacks())->list(false, $atId);
        $types = (new AssetTypes())->all(true);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('ServicePacks/index', [
            'page_title'  => 'Service Packs',
            'rows'        => $rows,
            'asset_types' => $types,
            'filter_at'   => $atId,
        ]);
    }

    public function viewAction($id = 0)
    {
        $m  = new ServicePacks();
        $p  = $m->find((int)$id);
        if (empty($p)) { $this->fb('Pack not found.'); return; }
        $items = $m->itemsFor((int)$id);
        $parts = (new SpareParts())->list(true, (int)$p['asset_type_id']);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('ServicePacks/view', [
            'page_title' => 'Pack · ' . $p['code'],
            'pack'       => $p,
            'items'      => $items,
            'parts'      => $parts,
        ]);
    }

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

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

    public function deleteItemAjAction()
    {
        header('Content-Type: application/json');
        try {
            $this->assertRole();
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            (new ServicePacks())->deleteItem($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 service packs.');
    }

    private function fb(string $msg): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Service Packs',
            'fb_msg'     => '<div class="alert alert-warning">' . htmlspecialchars($msg) . '</div>',
        ]);
    }
}
