<?php

namespace App\Http\Controllers;

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

class GuardRegistrationController extends Controller
{
    /**
     * Get all GuardRegistration records.
     */
    public function index()
    {
        $guardRegistrations = GuardRegistration::with(['securityAgency', 'user', 'guardCategory'])->get();
        return response()->json($guardRegistrations);
    }

    /**
     * Get a specific GuardRegistration record by GR_Id.
     */
    public function show($id)
    {
        $guardRegistration = GuardRegistration::with(['securityAgency', 'user', 'guardCategory'])->find($id);

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

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

    /**
     * Create a new GuardRegistration record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SA_Id' => 'nullable|integer|exists:security_agencies,SA_Id',
            'U_Id' => 'required|integer|exists:users_master,U_Id',
            'GC_Id' => 'nullable|integer|exists:guard_category,GC_Id',
        ]);

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

        DB::beginTransaction(); // Start transaction

        try {
            // Retrieve the associated user
            $user = User::find($request->input('U_Id'));
            if (!$user) {
                return response()->json(['error' => 'Invalid user.'], 422);
            }

            // Update Role_Id from 4 to 6 if applicable
            if ($user->Role_Id == 4) {
                $user->Role_Id = 6;
                $user->save();
            }

            // Create Guard Registration
            $guardRegistration = GuardRegistration::create([
                'SA_Id' => $request->input('SA_Id'),
                'U_Id' => $request->input('U_Id'),
                'GC_Id' => $request->input('GC_Id'),
            ]);

            DB::commit(); // Commit transaction

            // Eager load the related user and other defined relationships
            $guardRegistration->load('securityAgency', 'user', 'guardCategory');

            return response()->json([
                'message' => 'Guard registered successfully, Role updated!',
                'guard' => $guardRegistration
            ], 201);

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

    /**
     * Update a GuardRegistration record by GR_Id.
     */
    public function update(Request $request, $id)
    {
        $guardRegistration = GuardRegistration::find($id);

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

        // Make all fields optional
        $validator = Validator::make($request->all(), [
            'SA_Id' => 'nullable|integer|exists:security_agencies,SA_Id',
            'U_Id' => 'nullable|integer|exists:users_master,U_Id',
            'GC_Id' => 'nullable|integer|exists:guard_category,GC_Id',
        ]);

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

        // Prepare data for update, only including provided fields
        $updateData = $request->only([
            'SA_Id', 'U_Id', 'GC_Id'
        ]);

        // Handle user role updates based on U_Id change
        if ($request->has('U_Id')) {
            $userId = $request->input('U_Id');
            $user = User::find($userId);

            if (!$user) {
                return response()->json(['error' => 'Invalid user.'], 422);
            }

            if ($user->Role_Id != 4) {
                $user->Role_Id = 4;
                $user->save();
            }
        }

        // Update the guard registration record with provided fields
        $guardRegistration->update($updateData);

        // Eager load the related user details
        $guardRegistration->load('securityAgency', 'user', 'guardCategory');

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

    /**
     * Delete a GuardRegistration record by GR_Id.
     */
    public function destroy($id)
    {
        $guardRegistration = GuardRegistration::find($id);

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

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