<?php

namespace App\Http\Controllers;

use App\Models\VisitorType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class VisitorTypeController extends Controller
{
    /**
     * Get all VisitorType records.
     */
    public function index()
    {
        $visitorTypes = VisitorType::all();
        return response()->json($visitorTypes);
    }

    /**
     * Get a specific VisitorType record by VT_Id.
     */
    public function show($id)
    {
        $visitorType = VisitorType::find($id);

        if (!$visitorType) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        return response()->json($visitorType);
    }

    /**
     * Create a new VisitorType record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Vt_Desc' => 'required|string|max:255',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        DB::beginTransaction(); // Start transaction

        try {
            $validated = $validator->validated();

            // Create VisitorType record
            $visitorType = VisitorType::create($validated);

            DB::commit(); // Commit transaction

            return response()->json([
                'message' => 'Visitor type registered successfully!',
                'visitor_type' => $visitorType
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack(); // Rollback on failure
            return response()->json(['error' => 'Visitor type registration failed!', 'details' => $e->getMessage()], 500);
        }
    }

    /**
     * Update a VisitorType record by VT_Id.
     */
    public function update(Request $request, $id)
    {
        $visitorType = VisitorType::find($id);

        if (!$visitorType) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'Vt_Desc' => 'nullable|string|max:255',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $validated = array_filter($validator->validated());

        $visitorType->update($validated);

        return response()->json($visitorType);
    }

    /**
     * Delete a VisitorType record by VT_Id.
     */
    public function destroy($id)
    {
        $visitorType = VisitorType::find($id);

        if (!$visitorType) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $visitorType->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
