<?php

namespace App\Http\Controllers;


use App\Models\FormItem;
use Illuminate\Http\Request;
use PermissionHelper;
use App\Interfaces\StatusRepositoryInterface;
use Illuminate\Support\Facades\DB;

class ChecklistItemController extends Controller
{

    private $status;

    public function __construct(
        StatusRepositoryInterface $StatusRepositoryInterface,
    ) {
        $this->status = $StatusRepositoryInterface;
    }


    public function store(Request $request)
    {
        $request->validate([
            'name' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    if (str_word_count($value) > 25) {
                        $fail('Kolom ' . $attribute . ' maksimal 25 kata.');
                    }
                },
            ],

            'form_section_id' => 'required',
        ]);

        $formItem = FormItem::create([
            "name" => $request->name,
            "form_section_id" => $request->form_section_id,
        ]);


        if ($request->has('status')) {
            $formItem->status()->sync($request->status);
        }


        return response()->json(['message' => 'Checklist item berhasil ditambahkan.']);
    }

    /**
     * Display the specified resource.
     */


    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    if (str_word_count($value) > 25) {
                        $fail('Kolom ' . $attribute . ' maksimal 25 kata.');
                    }
                },
            ],
            'form_section_id' => 'required',
        ]);

        FormItem::findOrFail($id)->update([
            "name" => $request->name,
            "form_section_id" => $request->form_section_id,
        ]);



        if ($request->has('status')) {
            FormItem::findOrFail($id)->status()->sync($request->status);
        }

        return response()->json(['message' => 'Checklist item berhasil diupdate.']);
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {

        FormItem::find($id)->delete();
        return response()->json(data: ['message' => 'Checklist item berhasil dihapus.']);
    }


}
