<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Subcategory;
use App\Models\CategoryField;
use Illuminate\Http\Request;

class CategoryFieldController extends Controller
{
    /**
     * Get fields for a category or subcategory
     */
    public function index(Request $request)
    {
        $query = CategoryField::query();

        if ($request->has('subcategory_id')) {
            $query->where('subcategory_id', $request->subcategory_id);
        } elseif ($request->has('category_id')) {
            $query->where('category_id', $request->category_id)->whereNull('subcategory_id');
        }

        $fields = $query->orderBy('sort_order')->get();

        return response()->json($fields);
    }

    /**
     * Store a new custom field (or link a global field)
     */
    public function store(Request $request)
    {
        // Support linking Global Fields
        if ($request->filled('global_field_id')) {
            $globalField = \App\Models\GlobalField::findOrFail($request->global_field_id);
            
            $field = CategoryField::create([
                'category_id' => $request->category_id,
                'subcategory_id' => $request->subcategory_id,
                'global_field_id' => $globalField->id,
                
                // Inherit from global field (Snapshot approach for now to preserve API compatibility)
                'name' => $globalField->name,
                'slug' => $globalField->slug,
                'type' => $globalField->type,
                'options' => $globalField->options,
                'icon' => $globalField->icon,
                
                // Instance specific
                'is_required' => $request->boolean('is_required'), // Defaults to false/0 if not present
                'sort_order' => $request->input('sort_order', 0),
                'is_active' => true,
            ]);

            return response()->json(['message' => 'Field linked successfully', 'field' => $field]);
        }

        // Legacy / Custom manual creation
        $validated = $request->validate([
            'category_id' => 'required_without:subcategory_id|exists:categories,id',
            'subcategory_id' => 'nullable|exists:subcategories,id',
            'name' => 'required|string|max:255',
            'type' => 'required|in:text,number,dropdown,radio,checkbox,date',
            'options' => 'required_if:type,dropdown,radio,checkbox|array', 
            'is_required' => 'boolean',
            'sort_order' => 'integer',
        ]);

        $slug = str()->slug($validated['name']);
        
        $iconPath = null;
        if ($request->hasFile('icon_image')) {
            $iconPath = $request->file('icon_image')->store('category_icons', 'public');
        } elseif ($request->filled('icon')) {
             $iconPath = $request->icon; 
        }

        $field = CategoryField::create([
            'category_id' => $request->category_id,
            'subcategory_id' => $request->subcategory_id,
            'name' => $validated['name'],
            'slug' => $slug,
            'type' => $validated['type'],
            'options' => $request->options, 
            'icon' => $iconPath,
            'is_required' => $request->boolean('is_required'),
            'sort_order' => $request->input('sort_order', 0),
            'is_active' => true,
        ]);

        return response()->json(['message' => 'Field created successfully', 'field' => $field]);
    }

    /**
     * Update a custom field
     */
    public function update(Request $request, $id)
    {
        $field = CategoryField::findOrFail($id);
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:text,number,dropdown,radio,checkbox,date',
            'options' => 'nullable|array',
            'is_required' => 'boolean',
            'sort_order' => 'integer',
        ]);

        // Handle Icon Upload
        if ($request->hasFile('icon_image')) {
            $field->icon = $request->file('icon_image')->store('category_icons', 'public');
        } elseif ($request->filled('icon')) {
             $field->icon = $request->icon;
        }

        $field->update([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'options' => $request->options,
            'is_required' => $request->boolean('is_required'),
            'sort_order' => $request->input('sort_order', 0),
        ]);

        return response()->json(['message' => 'Field updated successfully', 'field' => $field]);
    }

    /**
     * Delete a custom field
     */
    public function destroy($id)
    {
        $field = CategoryField::findOrFail($id);
        $field->delete();
        return response()->json(['message' => 'Field deleted successfully']);
    }
}
