<?php

namespace App\Http\Controllers;

use App\Models\Field;
use App\Models\Collection;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class FieldController extends Controller
{
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, Project $project, Collection $collection)
    {
        $validated = $request->validate([
            'type' => 'required|string|max:60',
            'label' => 'required|string|max:60',
            'name' => [
                'required',
                'string',
                'max:60',
                'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
                'unique:collection_fields,name,NULL,id,collection_id,' . $collection->id,
            ],
            'description' => 'nullable|string',
            'placeholder' => 'nullable|string',
            'options' => 'nullable|array',
            'validations' => 'nullable|array',
        ]);

        // If name is not provided, generate it from the label
        if (empty($validated['name'])) {
            $validated['name'] = Str::slug($validated['label']);
        }

        $field = $collection->fields()->create([
            ...$validated,
            'project_id' => $project->id,
            'order' => $collection->fields()->count() + 1,
        ]);

        return redirect()->route('projects.collections.edit', [
            'project' => $project->id,
            'collection' => $collection->id,
        ])->with('success', 'Field created successfully');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Project $project, Collection $collection, Field $field)
    {
        $validated = $request->validate([
            'type' => 'required|string|max:60',
            'label' => 'required|string|max:60',
            'name' => [
                'required',
                'string',
                'max:60',
                'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
                'unique:collection_fields,name,' . $field->id . ',id,collection_id,' . $collection->id,
            ],
            'description' => 'nullable|string',
            'placeholder' => 'nullable|string',
            'options' => 'nullable|array',
            'validations' => 'nullable|array',
        ]);

        // If name is not provided, generate it from the label
        if (empty($validated['name'])) {
            $validated['name'] = Str::slug($validated['label']);
        }

        $field->update($validated);

        return redirect()->route('projects.collections.edit', [
            'project' => $project->id,
            'collection' => $collection->id,
        ])->with('success', 'Field updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Project $project, Collection $collection, Field $field)
    {
        $field->delete();

        return redirect()->route('projects.collections.edit', [
            'project' => $project->id,
            'collection' => $collection->id,
        ])->with('success', 'Field deleted successfully');
    }

    public function reorder(Request $request, Project $project, Collection $collection)
    {
        $validated = $request->validate([
            'fields' => 'required|array',
            'fields.*.id' => 'required|exists:collection_fields,id',
            'fields.*.order' => 'required|integer|min:0',
        ]);

        foreach ($validated['fields'] as $field) {
            Field::where('id', $field['id'])->update(['order' => $field['order']]);
        }

        return response()->json(['message' => 'Fields reordered successfully']);
    }
}
