<?php

namespace App\Http\Controllers;

use App\Models\EmpGroupIns;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class EmpGroupInsController extends Controller
{

   
    public function index(Request $request): JsonResponse
    {
        try {

            $perPage = $request->get('per_page', 20);
            $search  = $request->get('search');

            $query = EmpGroupIns::with('payCommission');

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {

                    
                    $q->where('Group_Type', 'like', "%$search%")
                        ->orWhere('Insurance_Amt', 'like', "%$search%")
                        ->orWhere('Save_Amt', 'like', "%$search%")
                        ->orWhere('Effective_Date', 'like', "%$search%");

                    
                    $q->orWhereHas('payCommission', function ($subQ) use ($search) {
                        $subQ->where('PC_Name', 'like', "%$search%");
                    });
                });
            }

            $data = $query->orderBy('EGI_Id', 'desc')
                ->paginate($perPage);

            return response()->json([
                'success' => true,
                'message' => 'Emp Group Insurance list fetched successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

 
    public function store(Request $request): JsonResponse
    {
        try {

            $validated = $request->validate([
                'Effective_Date' => 'nullable|date',
                'Group_Type'     => 'nullable|string|max:50',
                'Insurance_Amt'  => 'nullable|numeric',
                'Save_Amt'       => 'nullable|numeric',
                'PC_Id'          => 'nullable|exists:pay_comm_master,PC_Id'
            ]);

            $data = EmpGroupIns::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Record created successfully',
                'data' => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    public function show($id): JsonResponse
    {
        try {

            $data = EmpGroupIns::with('payCommission')->find($id);
            if (!$data) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    public function update(Request $request, $id): JsonResponse
    {
        try {

            $data = EmpGroupIns::find($id);

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

            $validated = $request->validate([
                'Effective_Date' => 'sometimes|nullable|date',
                'Group_Type'     => 'sometimes|nullable|string|max:50',
                'Insurance_Amt'  => 'sometimes|nullable|numeric',
                'Save_Amt'       => 'sometimes|nullable|numeric',
                'PC_Id'          => 'sometimes|nullable|exists:pay_comm_master,PC_Id'
            ]);

            $data->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Record updated successfully',
                'data' => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

 
    public function destroy($id): JsonResponse
    {
        try {

            $data = EmpGroupIns::find($id);

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

            $data->delete();

            return response()->json([
                'success' => true,
                'message' => 'Deleted successfully'
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    public function all(): JsonResponse
    {
        try {

            $data = EmpGroupIns::with('payCommission')
                ->orderBy('EGI_Id', 'desc')
                ->get();
            return response()->json([
                'success' => true,
                'message' => 'All records fetched successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
