<?php

namespace App\Http\Controllers\Admin;

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

class CategoryAttributeController extends Controller
{
    public function index(Category $category, Request $request)
    {
        $attributes = $category->attributes()->latest()->paginate(20);

        return $request->ajax()
            ? Response::api($attributes, __('Attributes fetched successfully.'), 200)
            : view('pages.admin.category-attribute.index', compact('category', 'attributes'));
    }

    public function create(Category $category)
    {
        return view('pages.admin.category-attribute.create', compact('category'));
    }

    public function store(Category $category, Request $request)
    {
        $validated = $this->validateData($request);
        $validated['category_id'] = $category->id;

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

        // 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['label'] ?? '');

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

        $attribute = CategoryAttribute::create($validated);

        return $request->ajax()
            ? Response::api($attribute, __('Attribute created.'), 201)
            : redirect()->route('admin.category.attribute.index', $category)->with('success', __('Attribute created.'));
    }

    public function show(Category $category, CategoryAttribute $attribute, Request $request)
    {
        return $request->ajax()
            ? Response::api($attribute, __('Attribute fetched successfully.'), 200)
            : view('pages.admin.category-attribute.show', compact('category', 'attribute'));
    }

    public function edit(Category $category, CategoryAttribute $attribute)
    {
        return view('pages.admin.category-attribute.edit', compact('category', 'attribute'));
    }

    public function update(Category $category, Request $request, CategoryAttribute $attribute)
    {
        $validated = $this->validateData($request);
        $attribute->update($validated);

        return $request->ajax()
            ? Response::api($attribute, __('Attribute updated.'), 200)
            : redirect()->route('admin.category.attribute.index', $category)->with('success', __('Attribute updated.'));
    }

    public function destroy(Category $category, CategoryAttribute $attribute, Request $request)
    {

        $attribute->delete();

        return $request->ajax()
            ? Response::api(null, __('Attribute deleted.'), 200)
            : redirect()->route('admin.category.attribute.index', $category)->with('success', __('Attribute deleted.'));
    }

    protected function validateData(Request $request): array
    {
        $request->merge([
            'is_required' => $request->is_required == "true" ?  true : false,
            'is_filterable' => $request->is_filterable == "true" ?  true : false,
            'is_price_effective' => $request->is_price_effective == "true" ?  true : false,
        ]);

        return $request->validate([
            'label' => 'required|string|max:255',
            'type' => 'required|string',
            'name' => 'nullable|string|max:255',
            'default_value' => 'nullable|string',
            'is_required' => 'boolean',
            'is_filterable' => 'boolean',
            'filter_type' => 'nullable|string',
            'is_price_effective' => 'boolean',
            'validation' => 'nullable|string',
        ]);
    }
}
