<?php

namespace App\Http\Controllers\Admin\Quotation;

use App\Http\Controllers\Controller;
use App\Models\QuotationType;
use Illuminate\Http\Request;
use Inertia\Inertia;

class QuotationTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Inertia::render('Quotation/QuotationType');
    }

    /**
     * Fetch all quotation types.
     */
    public function view()
    {
        $types = QuotationType::orderByDesc('id')->get();
        return response()->json(['types' => $types]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:quotation_types,name',
            'description' => 'nullable|string',
            'status' => 'nullable|string|in:0,1',
        ]);

        QuotationType::create([
            'name' => $request->name,
            'description' => $request->description,
            'status' => $request->status ?? '1',
        ]);

        return response()->json([
            'success' => 'Quotation type created successfully',
            'types' => QuotationType::orderByDesc('id')->get(),
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $type = QuotationType::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255|unique:quotation_types,name,' . $id,
            'description' => 'nullable|string',
            'status' => 'nullable|string|in:0,1',
        ]);

        $type->update($request->only(['name', 'description', 'status']));

        return response()->json([
            'success' => 'Quotation type updated successfully',
            'types' => QuotationType::orderByDesc('id')->get(),
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $type = QuotationType::findOrFail($id);
        $type->delete();

        return response()->json([
            'success' => 'Quotation type deleted successfully',
            'types' => QuotationType::orderByDesc('id')->get(),
        ]);
    }
}


