<?php

namespace App\Http\Controllers;

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

class EmppersProfileController extends Controller
{
    /**
     * List + Search + Pagination
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = $request->get('per_page', 15);
            $search = $request->get('search', '');

            $query = EmpPersProfile::with([
                'employee',
                'grade',
                'department',
                'designation',
                'payScale',
                'empType',
                'empStatus'
            ]);

            if (!empty($search)) {
                $query->whereHas('employee', function ($q) use ($search) {
                    $q->where('Emp_Name', 'like', "%{$search}%");
                });
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Employee profile list fetched successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'Emp_Id' => 'required|exists:employee_master,Emp_Id',
                'EPP_Date' => 'nullable|date',
                'EGM_Id' => 'nullable|exists:emp_grade_master,EGM_Id',
                'Dpt_id' => 'nullable|exists:dept_master,Dpt_id',
                'Dsg_Id' => 'nullable|exists:designation_master,Dsg_id',
                'PS_Id' => 'nullable|exists:pay_scale_master,PS_Id',
                'ETy_Id' => 'nullable|exists:emp_type_master,ETy_Id',
                'Join_Date' => 'nullable|date',
                'Est_Id' => 'nullable|exists:emp_status_master,Est_Id',
                'Is_Active' => 'boolean'
            ]);

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

            return response()->json([
                'success' => true,
                'message' => 'Employee profile 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' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show Single
     */
    public function show($id): JsonResponse
    {
        try {
            $data = EmpPersProfile::with([
                'employee',
                'grade',
                'department',
                'designation',
                'payScale',
                'empType',
                'empStatus'
            ])->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' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update (Only Provided Fields)
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {
            $data = EmpPersProfile::find($id);

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

            $validated = $request->validate([
                'Emp_Id' => 'sometimes|exists:employee_master,Emp_Id',
                'EPP_Date' => 'sometimes|date',
                'EGM_Id' => 'sometimes|exists:emp_grade_master,EGM_Id',
                'Dpt_id' => 'sometimes|exists:dept_master,Dpt_id',
                'Dsg_Id' => 'sometimes|exists:designation_master,Dsg_id',
                'PS_Id' => 'sometimes|exists:pay_scale_master,PS_Id',
                'ETy_Id' => 'sometimes|exists:emp_type_master,ETy_Id',
                'Join_Date' => 'sometimes|date',
                'Est_Id' => 'sometimes|exists:emp_status_master,Est_Id',
                'Is_Active' => 'sometimes|boolean'
            ]);

            $data->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Employee profile updated successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Soft Delete
     */
    public function destroy($id): JsonResponse
    {
        try {
            $data = EmpPersProfile::find($id);

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

            $data->delete();

            return response()->json([
                'success' => true,
                'message' => 'Employee profile deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * All Active
     */
   /**
 * All Active with Relationships
 */
public function all(): JsonResponse
{
    try {
        $data = EmpPersProfile::with([
            'employee',
            'grade',
            'department',
            'designation',
            'payScale',
            'empType',
            'empStatus'
        ])
        ->where('Is_Active', 1)
        ->get();

        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Something went wrong',
            'error' => $e->getMessage()
        ], 500);
    }
}
}