<?php
namespace App\Http\Controllers;

use App\Models\FileCustomField;
use App\Models\ProjectCategory;
use Illuminate\Http\Request;

class FileCustomFieldController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->pageTitle = 'app.menu.customFields';
        $this->activeSettingMenu = 'custom_fields';
        $this->middleware(function ($request, $next) {
            abort_403(user()->permission('manage_custom_field_setting') !== 'all');

            return $next($request);
        });
    }

    public function index()
    {
       // dd(1);
        $this->customFields = FileCustomField::with('projectCategories')->get(); // Get all custom fields with their linked categories

        // return view('settings.file_custom_fields.index', compact('categories'));
        return view('file-custom-fields.index', $this->data);

    }
    public function store(Request $request)
    {
        //dd($request->all());
        
        $validated = $request->validate([
            'field_name' => 'required|unique:file_custom_fields,field_name',
            'field_display_name' => 'required',
            'field_type' => 'required|in:text,number,dropdown,date,checkbox',
            'field_values' => 'nullable|string',
            'project_category_ids' => 'required|array',
            'project_category_ids.*' => 'exists:project_category,id',
        ]);
    
        // Create the custom field
        $customField = FileCustomField::create($validated);
    
        // Attach the selected categories
        $customField->projectCategories()->attach($request->project_category_ids);
    
        return response()->json(['status' => 'success', 'message' => 'Custom Field added successfully!']);
    }
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'field_display_name' => 'required',
            'field_type' => 'required|in:text,number,dropdown,date,checkbox',
            'project_category_ids' => 'required|array',
            'project_category_ids.*' => 'exists:project_category,id',
        ]);
    
        $customField = FileCustomField::findOrFail($id);
        $customField->update($validated);
    
        $customField->projectCategories()->sync($request->project_category_ids);
    
        return response()->json(['status' => 'success', 'message' => 'Custom field updated successfully!']);
    }
    
    public function destroy(FileCustomField $fileCustomField)
    {
        $fileCustomField->delete();
        return back()->with('success', 'Custom field deleted successfully!');
    }
}
