<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\VendorType;
use Illuminate\Http\Request;

class VendorTypeController extends Controller
{
    public function index()
    {
        $vendorTypes = VendorType::withCount('vendors')->get();
        return view('admin.vendor_types.index', compact('vendorTypes'));
    }

    public function create()
    {
        return view('admin.vendor_types.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:vendor_types',
            'slug' => 'required|string|max:255|unique:vendor_types',
            'icon' => 'nullable|string|max:10',
        ]);

        VendorType::create($request->only('name', 'slug', 'icon', 'is_active'));

        return redirect()->route('admin.vendor-types.index')->with('success', 'Vendor type created successfully.');
    }

    public function edit(VendorType $vendorType)
    {
        return view('admin.vendor_types.edit', compact('vendorType'));
    }

    public function update(Request $request, VendorType $vendorType)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:vendor_types,name,' . $vendorType->id,
            'icon' => 'nullable|string|max:10',
        ]);

        $vendorType->update($request->only('name', 'icon', 'is_active'));

        return redirect()->route('admin.vendor-types.index')->with('success', 'Vendor type updated successfully.');
    }

    public function toggle(VendorType $vendorType)
    {
        $vendorType->update(['is_active' => !$vendorType->is_active]);
        return back()->with('success', 'Vendor type status updated.');
    }
}
