<?php

namespace Modules\Vrc\Http\Controllers\Registers;

use Modules\Vrc\Entities\VrcDocument;

/**
 * ISO 9001 controlled-document / SOP register. CRUD + versioning + status; the
 * approval stamp (approved_by/approved_at) is set when status flips to approved.
 */
class DocumentController extends AbstractRegisterController
{
    protected function schema(): array
    {
        $status = ['draft' => 'Draft', 'under_review' => 'Under review', 'approved' => 'Approved', 'obsolete' => 'Obsolete'];
        $cats = ['sop' => 'SOP', 'work_instruction' => 'Work instruction', 'policy' => 'Policy', 'form' => 'Form', 'manual' => 'Manual'];

        return [
            'key' => 'documents',
            'route' => 'vrc.quality.documents',
            'model' => VrcDocument::class,
            'permView' => 'vrc.quality.view',
            'permManage' => 'vrc.quality.manage',
            'title' => 'Controlled Documents (SOPs)',
            'singular' => 'Document',
            'defaults' => ['status' => 'draft'],
            'beforeSave' => function (array $data, $request, $row) {
                if (($data['status'] ?? null) === 'approved' && (! $row || $row->status !== 'approved')) {
                    $data['approved_by'] = (int) request()->session()->get('user.id');
                    $data['approved_at'] = now();
                }
                return $data;
            },
            'columns' => [
                ['key' => 'code', 'label' => 'Code'],
                ['key' => 'title', 'label' => 'Title'],
                ['key' => 'category', 'label' => 'Category', 'map' => $cats],
                ['key' => 'version', 'label' => 'Ver.'],
                ['key' => 'status', 'label' => 'Status', 'map' => $status, 'badge' => ['draft' => 'default', 'under_review' => 'warning', 'approved' => 'success', 'obsolete' => 'danger']],
                ['key' => 'review_due', 'label' => 'Review due', 'type' => 'date'],
            ],
            'fields' => [
                ['name' => 'code', 'label' => 'Code', 'type' => 'text', 'required' => true, 'col' => 4, 'max' => 60],
                ['name' => 'title', 'label' => 'Title', 'type' => 'text', 'required' => true, 'col' => 8, 'max' => 191],
                ['name' => 'category', 'label' => 'Category', 'type' => 'select', 'options' => $cats, 'col' => 4, 'default' => 'sop'],
                ['name' => 'version', 'label' => 'Version', 'type' => 'text', 'col' => 4, 'default' => '1.0', 'max' => 20],
                ['name' => 'status', 'label' => 'Status', 'type' => 'select', 'options' => $status, 'col' => 4, 'default' => 'draft'],
                ['name' => 'review_due', 'label' => 'Next review', 'type' => 'date', 'col' => 4],
                ['name' => 'file_path', 'label' => 'File URL / path', 'type' => 'text', 'col' => 8, 'max' => 255],
                ['name' => 'content', 'label' => 'Content / summary', 'type' => 'textarea', 'col' => 12, 'rows' => 4],
            ],
        ];
    }
}
