<?php

namespace App\Http\Controllers\Modules\MasterData;

use App\Http\Controllers\Controller;
use App\Http\Traits\HasRoleViews;
use App\Models\ProductType;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

/**
 * Unified ProductType Controller
 *
 * Handles product type management for all roles (Admin, Manager, SuperAdmin).
 * Views are automatically resolved based on the logged-in user's role.
 */
class ProductTypeController extends Controller
{
    use HasRoleViews;

    /**
     * Display the product types management page
     */
    public function index()
    {
        return $this->roleView('master.producttype');
    }

    /**
     * Get product types list for DataTable/AJAX
     */
    public function list(): JsonResponse
    {
        $types = ProductType::select('id', 'name')->get();
        return response()->json(['data' => $types]);
    }

    /**
     * Get a single product type for editing
     */
    public function show(ProductType $producttype): JsonResponse
    {
        return response()->json($producttype);
    }

    /**
     * Store a newly created product type
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'product_type' => 'required|string|max:255|unique:product_types,name',
        ]);

        ProductType::create([
            'name' => $validated['product_type'],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Product Type added successfully',
        ]);
    }

    /**
     * Update the specified product type
     */
    public function update(Request $request, ProductType $producttype): JsonResponse
    {
        $validated = $request->validate([
            'product_type' => 'required|string|max:255|unique:product_types,name,' . $producttype->id,
        ]);

        $producttype->update([
            'name' => $validated['product_type'],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Product Type updated successfully',
        ]);
    }

    /**
     * Remove the specified product type
     */
    public function destroy(ProductType $producttype): JsonResponse
    {
        $producttype->delete();

        return response()->json([
            'success' => true,
            'message' => 'Product Type deleted successfully',
        ]);
    }

    /**
     * Alias for destroy() - backward compatibility with old routes
     */
    public function delete(ProductType $producttype): JsonResponse
    {
        return $this->destroy($producttype);
    }
}
