<?php

namespace App\Http\Controllers\SuperAdmin;

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

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class SuperAdminRfqTypeController extends Controller
{
    public function index()
    {
        return view('superadmin.master.rfqtype');
    }

    public function list()
    {
        $types = RfqType::select('id', 'rfqtype')->get();
        return response()->json(['data' => $types]);
    }

    public function show(RfqType $rfqtype)
    {
        return response()->json($rfqtype);
    }

    public function store_old(Request $request)
    {
        $request->validate(['rfq_type' => 'required']);
        RfqType::create(['rfqtype' => $request->rfq_type]);
        return response()->json(['success' => true, 'message' => 'RFQ Type added']);
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rfq_type' => 'required|unique:rfq_types,rfqtype'
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        RfqType::create(['rfqtype' => $request->rfq_type]);
    
        return response()->json(['success' => true, 'message' => 'RFQ Type added']);
    }

    public function update_old(Request $request, RfqType $rfqtype)
    {
        $request->validate(['rfq_type' => 'required']);
        $rfqtype->update(['rfqtype' => $request->rfq_type]);
        return response()->json(['success' => true, 'message' => 'RFQ Type updated']);
    }
    
    public function update(Request $request, RfqType $rfqtype)
    {
        $validator = Validator::make($request->all(), [
            'rfq_type' => [
                'required',
                Rule::unique('rfq_types', 'rfqtype')->ignore($rfqtype->id)
            ]
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        $rfqtype->update(['rfqtype' => $request->rfq_type]);
    
        return response()->json(['success' => true, 'message' => 'RFQ Type updated']);
    }

    public function delete(RfqType $rfqtype)
    {
        $rfqtype->delete();
        return response()->json(['success' => true, 'message' => 'RFQ Type deleted']);
    }
}
