<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\EmployeeMaster;
use App\Models\EmpLangMaster;
use Illuminate\Http\JsonResponse;

class EmployeeMasterController extends Controller
{

    /*
    ===============================
    Index + Pagination + Search
    ===============================
    */
    public function index(Request $request): JsonResponse
    {
        try {

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

            $query = EmployeeMaster::with([
                'department',
                'caste',
                'quota',
                'category',
                'user'
            ]);

            if ($search) {
                $query->where(function ($q) use ($search) {
                    $q->where('Emp_Code', 'like', "%$search%")
                        ->orWhere('First_Name', 'like', "%$search%")
                        ->orWhere('Last_Name', 'like', "%$search%");
                });
            }

            $employees = $query->orderByDesc('Emp_Id')->paginate($perPage);

            $employees->getCollection()->transform(function ($emp) {

                $emp->languages = EmpLangMaster::whereIn('ELg_Id', $emp->ELg_Id ?? [])->get();

                return $emp;
            });

            return response()->json([
                'status' => true,
                'message' => 'Employee list fetched',
                'data' => $employees
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'status' => false,
                'message' => 'Error fetching employees',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    /*
    ===============================
    Store
    ===============================
    */
    public function store(Request $request): JsonResponse
    {
        try {

            $employee = EmployeeMaster::create([
                'Emp_Code' => $request->Emp_Code,
                'First_Name' => $request->First_Name,
                'Last_Name' => $request->Last_Name,
                'Dpt_Id' => $request->Dpt_Id,
                'Caste_Id' => $request->Caste_Id,
                'Qut_Id' => $request->Qut_Id,
                'Ect_Id' => $request->Ect_Id,
                'Usr_Id' => $request->Usr_Id,
                'ELg_Id' => $request->ELg_Id,
                'Phone' => $request->Phone,
                'Email_Id' => $request->Email_Id,
                'Alt_Phone' => $request->Alt_Phone,
                'F_M' => $request->F_M,
                'Emp_Add1' => $request->Emp_Add1,
                'Emp_Add2' => $request->Emp_Add2,
                'Emp_Add3' => $request->Emp_Add3,
                'Birth_Date' => $request->Birth_Date,
                'Bank_AcNo' => $request->Bank_AcNo,
                'Bank_Name' => $request->Bank_Name,
                'Bank_Br_Name' => $request->Bank_Br_Name,
                'BkAc_Type' => $request->BkAc_Type,
                'Gpf_AcNo_Pref' => $request->Gpf_AcNo_Pref,
                'Gpf_AcNo' => $request->Gpf_AcNo,
                'Cpf_AcNo' => $request->Cpf_AcNo,
                'Inc_TxNo' => $request->Inc_TxNo,
                'UID_AdharNo' => $request->UID_AdharNo,
                'Is_Active' => $request->Is_Active ?? 1,
            ]);

            return $this->show($employee->Emp_Id);
        } catch (\Exception $e) {

            return response()->json([
                'status' => false,
                'message' => 'Create failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    /*
    ===============================
    Show
    ===============================
    */
    public function show($id): JsonResponse
    {
        try {

            $employee = EmployeeMaster::with([
                'department',
                'caste',
                'quota',
                'category',
                'user'
            ])->findOrFail($id);

            $employee->languages = EmpLangMaster::whereIn('ELg_Id', $employee->ELg_Id ?? [])->get();

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

            return response()->json([
                'status' => false,
                'message' => 'Employee not found',
                'error' => $e->getMessage()
            ], 404);
        }
    }



    /*
    ===============================
    Update
    ===============================
    */
    public function update(Request $request, $id): JsonResponse
    {
        try {

            $employee = EmployeeMaster::findOrFail($id);

            // Only update fields that are sent
            $data = $request->only([
                'Emp_Code',
                'First_Name',
                'Last_Name',
                'Dpt_Id',
                'Caste_Id',
                'Qut_Id',
                'Ect_Id',
                'Usr_Id',
                'ELg_Id',
                'Phone',
                'Email_Id',
                'Alt_Phone',
                'F_M',
                'Emp_Add1',
                'Emp_Add2',
                'Emp_Add3',
                'Birth_Date',
                'Bank_AcNo',
                'Bank_Name',
                'Bank_Br_Name',
                'BkAc_Type',
                'Gpf_AcNo_Pref',
                'Gpf_AcNo',
                'Cpf_AcNo',
                'Inc_TxNo',
                'UID_AdharNo',
                'Is_Active'
            ]);

            $employee->update($data);

            return $this->show($employee->Emp_Id);
        } catch (\Exception $e) {

            return response()->json([
                'status' => false,
                'message' => 'Update failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }




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

            $employee = EmployeeMaster::findOrFail($id);
            $employee->delete();

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

            return response()->json([
                'status' => false,
                'message' => 'Delete failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    /*
    ===============================
    All Data
    ===============================
    */
    public function all(): JsonResponse
    {
        try {

            $employees = EmployeeMaster::with([
                'department',
                'caste',
                'quota',
                'category',
                'user'
            ])->orderByDesc('Emp_Id')->get();

            $employees->transform(function ($emp) {

                $emp->languages = EmpLangMaster::whereIn('ELg_Id', $emp->ELg_Id ?? [])->get();

                return $emp;
            });

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

            return response()->json([
                'status' => false,
                'message' => 'Fetch failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
