<?php

namespace App\Http\Controllers\Modules\MasterData;

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

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

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

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

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

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

        RfqType::create([
            'rfqtype' => $validated['rfq_type'],
        ]);

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

    /**
     * Update the specified RFQ type
     */
    public function update(Request $request, RfqType $rfqtype): JsonResponse
    {
        $validated = $request->validate([
            'rfq_type' => 'required|string|max:255|unique:rfq_types,rfqtype,' . $rfqtype->id,
        ]);

        $rfqtype->update([
            'rfqtype' => $validated['rfq_type'],
        ]);

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

    /**
     * Remove the specified RFQ type
     */
    public function destroy(RfqType $rfqtype): JsonResponse
    {
        $rfqtype->delete();

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

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