<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsQcChecklist;
use Modules\Bms\Services\Qc\QcService;

/**
 * P1 editor for the QC checklist template. Manages the business's default
 * checklist items (label + Arabic label) used to instantiate inspections.
 */
class QcChecklistController extends BmsBaseController
{
    public function edit()
    {
        $this->guard('bms.qc.manage');
        $biz = $this->businessId();
        app(QcService::class)->ensureDefaults($biz);

        $checklist = BmsQcChecklist::where('business_id', $biz)->orderBy('sort_order')->first();

        return view('bms::settings.qc_checklist', ['checklist' => $checklist]);
    }

    public function update(Request $request)
    {
        $this->guard('bms.qc.manage');
        $biz = $this->businessId();
        $checklist = BmsQcChecklist::where('business_id', $biz)->orderBy('sort_order')->firstOrFail();

        $items = [];
        foreach ((array) $request->input('item_label', []) as $i => $label) {
            $label = trim((string) $label);
            if ($label !== '') {
                $items[] = ['label' => $label, 'label_ar' => trim((string) ($request->input('item_label_ar')[$i] ?? ''))];
            }
        }

        $checklist->update([
            'name'      => $request->input('name', $checklist->name),
            'name_ar'   => $request->input('name_ar'),
            'stage'     => $request->input('stage', 'pre_event'),
            'items'     => $items,
            'is_active' => $request->boolean('is_active'),
        ]);

        return redirect()->route('bms.qc-checklist.edit')
            ->with('status', ['success' => 1, 'msg' => __('bms::lang.success')]);
    }
}
