<?php

namespace App\Http\Controllers;

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

class FamilyInfoMasterController extends Controller
{
    /**
     * List with Search & Pagination
     */
    public function index(Request $request): JsonResponse
    {
        try {

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

            $query = FamilyInfoMaster::with(['employee', 'relationship']);

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {
                    $q->where('Member_name', 'like', "%{$search}%")
                        ->orWhere('Phone', 'like', "%{$search}%");
                });
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Family info 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',
                'Member_name' => 'required|string|max:50',
                'Gender' => 'nullable|in:male,female,other',
                'Rela_Id' => 'nullable|exists:relationship_master,Rela_Id',
                'Dob' => 'nullable|date',
                'Phone' => 'nullable|string|max:15',
                'Is_Active' => 'boolean'
            ]);

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

            return response()->json([
                'success' => true,
                'message' => 'Family info 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 = FamilyInfoMaster::with(['employee', 'relationship'])
                ->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
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {

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

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

            $validated = $request->validate([
                'Emp_id' => 'required|exists:employee_master,Emp_Id',
                'Member_name' => 'required|string|max:50',
                'Gender' => 'nullable|in:male,female,other',
                'Rela_Id' => 'nullable|exists:relationship_master,Rela_Id',
                'Dob' => 'nullable|date',
                'Phone' => 'nullable|string|max:15',
                'Is_Active' => 'boolean'
            ]);

            $data->update($validated);

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

    /**
     * Soft Delete
     */
    public function destroy($id): JsonResponse
    {
        try {

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

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

            $data->delete();

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

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

    /**
     * All Active Records
     */
    public function all(): JsonResponse
    {
        try {

            $data = FamilyInfoMaster::where('Is_Active', 1)
                ->orderBy('Member_name')
                ->get();

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

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