<?php

namespace App\Http\Controllers;

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

class PayMatrixMasterController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = $request->get('per_page', 20);
            $search = $request->get('search', '');

            $query = PayMatrixMaster::with('empGrade');

            if (!empty($search)) {
                $query->where(function($q) use ($search) {
                    $q->where('Cell_Index', 'like', "%{$search}%")
                      ->orWhere('Basic_Pay', 'like', "%{$search}%")
                      ->orWhereHas('empGrade', function($sub) use ($search) {
                          $sub->where('EGM_Name', 'like', "%{$search}%");
                      });
                });
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Pay matrix 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([
                'EGM_id' => 'nullable|exists:emp_grade_master,EGM_Id',
                'Cell_Index' => 'required|integer',
                'Basic_Pay' => 'required|numeric'
            ]);

            $data = PayMatrixMaster::create($validated);
            $data->load('empGrade');

            return response()->json([
                'success' => true,
                'message' => 'Pay matrix 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 = PayMatrixMaster::with('empGrade')
                ->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 = PayMatrixMaster::find($id);

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

            $validated = $request->validate([
                'EGM_id' => 'sometimes|nullable|exists:emp_grade_master,EGM_Id',
                'Cell_Index' => 'sometimes|required|integer',
                'Basic_Pay' => 'sometimes|required|numeric'
            ]);

            $data->update($validated);
            $data->load('empGrade');

            return response()->json([
                'success' => true,
                'message' => 'Pay matrix 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 = PayMatrixMaster::find($id);

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

            $data->delete();

            return response()->json([
                'success' => true,
                'message' => 'Pay matrix 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 = PayMatrixMaster::with('empGrade')
                ->orderBy('Cell_Index')
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'All pay matrix 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);
        }
    }
}
