<?php

namespace App\Http\Controllers;

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

class GateMasterController extends Controller
{
    /**
     * Get all GateMaster records.
     */
    public function index()
    {
        $gates = GateMaster::with('society')->get();
        return response()->json($gates);
    }

    /**
     * Get a specific GateMaster record by GM_ID.
     */
    public function show($id)
    {
        $gate = GateMaster::with('society')->find($id);

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

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

    /**
     * Create a new GateMaster record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SocId' => 'required|integer|exists:society_master,SocId',
            'GM_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 GateMaster record
            $gate = GateMaster::create($validated);

            DB::commit(); // Commit transaction

            // Eager load the related society
            $gate->load('society');

            return response()->json([
                'message' => 'Gate registered successfully!',
                'gate' => $gate
            ], 201);

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

    /**
     * Update a GateMaster record by GM_ID.
     */
    public function update(Request $request, $id)
    {
        $gate = GateMaster::find($id);

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

        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|integer|exists:society_master,SocId',
            'GM_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());

        $gate->update($validated);

        $gate->load('society');

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

    /**
     * Delete a GateMaster record by GM_ID.
     */
    public function destroy($id)
    {
        $gate = GateMaster::find($id);

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

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