<?php
namespace App\Http\Controllers;

use App\Models\AssetCategory;
use App\Models\AssetCustomField;
use Illuminate\Http\Request;

class AssetCategoryController extends Controller
{
    public function index() {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $categories = AssetCategory::with(['customFields','models'])->withCount('assets')->get();
        return view('admin.asset-config.categories', compact('categories'));
    }
    public function store(Request $request) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate(['name'=>'required','icon'=>'nullable','color'=>'nullable','active'=>'boolean']);
        AssetCategory::create($data);
        return back()->with('success','Categoría creada.');
    }
    public function update(Request $request, AssetCategory $assetCategory) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate(['name'=>'required','icon'=>'nullable','color'=>'nullable','active'=>'boolean']);
        $assetCategory->update($data);
        return back()->with('success','Categoría actualizada.');
    }
    public function storeField(Request $request, AssetCategory $assetCategory) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate(['label'=>'required','name'=>'required','type'=>'required','required'=>'boolean','order'=>'integer']);
        $data['category_id'] = $assetCategory->id;
        AssetCustomField::create($data);
        return back()->with('success','Campo agregado.');
    }
}
