<?php

namespace Modules\Vrc\Http\Controllers\Registers;

use Modules\Vrc\Entities\VrcNcr;

/** ISO 9001 non-conformance reports. */
class NcrController extends AbstractRegisterController
{
    protected function schema(): array
    {
        $source = ['complaint' => 'Complaint', 'incident' => 'Incident', 'audit' => 'Audit', 'internal' => 'Internal', 'supplier' => 'Supplier'];
        $severity = ['minor' => 'Minor', 'major' => 'Major', 'critical' => 'Critical'];
        $status = ['open' => 'Open', 'investigating' => 'Investigating', 'action_planned' => 'Action planned', 'closed' => 'Closed'];

        return [
            'key' => 'ncrs',
            'route' => 'vrc.quality.ncrs',
            'model' => VrcNcr::class,
            'permView' => 'vrc.quality.view',
            'permManage' => 'vrc.quality.manage',
            'title' => 'Non-Conformance Reports',
            'singular' => 'NCR',
            'defaults' => ['status' => 'open'],
            'beforeSave' => function (array $data, $request, $row) {
                if (! $row && empty($data['raised_at'])) {
                    $data['raised_at'] = now();
                    $data['raised_by'] = (int) request()->session()->get('user.id');
                }
                if (($data['status'] ?? null) === 'closed' && (! $row || $row->status !== 'closed')) {
                    $data['closed_at'] = now();
                }
                return $data;
            },
            'columns' => [
                ['key' => 'number', 'label' => 'No.'],
                ['key' => 'title', 'label' => 'Title'],
                ['key' => 'source', 'label' => 'Source', 'map' => $source],
                ['key' => 'severity', 'label' => 'Severity', 'map' => $severity, 'badge' => ['minor' => 'default', 'major' => 'warning', 'critical' => 'danger']],
                ['key' => 'status', 'label' => 'Status', 'map' => $status, 'badge' => ['open' => 'danger', 'investigating' => 'warning', 'action_planned' => 'info', 'closed' => 'success']],
            ],
            'fields' => [
                ['name' => 'number', 'label' => 'NCR no.', 'type' => 'text', 'col' => 4, 'max' => 60],
                ['name' => 'title', 'label' => 'Title', 'type' => 'text', 'required' => true, 'col' => 8, 'max' => 191],
                ['name' => 'source', 'label' => 'Source', 'type' => 'select', 'options' => $source, 'col' => 4, 'default' => 'internal'],
                ['name' => 'severity', 'label' => 'Severity', 'type' => 'select', 'options' => $severity, 'col' => 4, 'default' => 'minor'],
                ['name' => 'status', 'label' => 'Status', 'type' => 'select', 'options' => $status, 'col' => 4, 'default' => 'open'],
                ['name' => 'description', 'label' => 'Description', 'type' => 'textarea', 'col' => 12, 'rows' => 3],
            ],
        ];
    }
}
