<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\CategoryAttribute;
use App\Http\Controllers\Controller;
use App\Models\CategoryAttributeItem;
use Illuminate\Support\Facades\Response;
use App\Services\ValidNameGeneratorService;

class CategoryAttributeItemController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(CategoryAttribute $attribute)
    {
        $items = $attribute->items()->with('attribute')->get();

        return view('pages.admin.category-attribute-item.index', [
            'items' => $items,
            'attribute' => $attribute,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(CategoryAttribute $attribute)
    {
        return view('pages.admin.category-attribute-item.create', compact('attribute'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, CategoryAttribute $attribute)
    {
        $validated = $request->validate([
            'item_group' => 'nullable',
            'item_key' => 'nullable',
            'item_value' => 'required',
        ]);

        try {
            $validated['item_group'] = $validated['item_group'] ?? $attribute->name;

            $name = $validated['item_key'] ?? '';

            // Only regenerate when it's empty/null or not a valid PHP identifier
            if ($name === '' || !ValidNameGeneratorService::isValidName($name)) {
                // Pick the base input: prefer the old name (even if invalid),
                // otherwise fall back to the label (or an empty string)
                $base = $name !== ''
                    ? $name
                    : ($validated['item_value'] ?? '');

                // Slug-ify with underscores, then sanitize into a truly valid identifier
                $slugged = Str::slug($base, '_');
                $validated['item_key'] = ValidNameGeneratorService::makeValidName($slugged);
            }


            $attribute->items()->create($validated);
        } catch (\Throwable $th) {
            if ($request->ajax() || $request->ajax == true) {
                return Response::failure(__('The operation encountered an error'));
            }
            return back()->with('error', __('The operation encountered an error'));
        }

        if ($request->ajax() || $request->ajax == true) {
            return Response::success(__('The attribute created successfully'));
        }
        return back()->with('success', __('The attribute created successfully'));
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(CategoryAttribute $attribute, CategoryAttributeItem $item)
    {
        try {
            $item->delete();
        } catch (\Throwable $th) {
            return back()->with('error', __('The operation encountered an error'));
        }
        return back()->with('success', __('The The operation was successful'));
    }
}
