<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Approver;
use App\Models\Dealership;
use App\Models\Employee;
use App\Models\OrganizationUnit;
use App\Models\User;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Throwable;

class ApproverController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        
        // Get all organization units first
        $organizationUnits = OrganizationUnit::with([
            'dealership.dealership_approver',
            'group_division.group_division_approver',
            'division.division_approver',
            'department.department_approver',
            'section.section_approver',
        ]);

        if (!empty($sortBy) && !empty($sortType)) {
            $organizationUnits = $organizationUnits->orderBy($sortBy, $sortType);
        }

        $data = $organizationUnits->paginate($perPage);
        
        // Filter approvers by dealership_id in the response
        $data->getCollection()->transform(function ($unit) {
            $dealershipId = $unit->dealership_id;
            
            if ($unit->group_division && $unit->group_division->group_division_approver) {
                $unit->group_division->group_division_approver = $unit->group_division->group_division_approver
                    ->where('dealership_id', $dealershipId);
            }
            
            if ($unit->division && $unit->division->division_approver) {
                $unit->division->division_approver = $unit->division->division_approver
                    ->where('dealership_id', $dealershipId);
            }
            
            if ($unit->department && $unit->department->department_approver) {
                $unit->department->department_approver = $unit->department->department_approver
                    ->where('dealership_id', $dealershipId);
            }
            
            if ($unit->section && $unit->section->section_approver) {
                $unit->section->section_approver = $unit->section->section_approver
                    ->where('dealership_id', $dealershipId);
            }
            
            return $unit;
        });

        return response()->json($data);
    }
    
    public function getEmployeeApprover(String $employee_id)
    {
        $employee = Employee::where([
            'employee_id' => $employee_id,
            'enabled' => 1
            ])
            ->whereNull('date_resign')
            ->first();
            
        $approver = [];

        if($employee->classification_id == 1){
            $approver_result = $this->getRankAndFileApprover($employee->employee_id);
        } else if ($employee->classification_id == 2) {
            $approver_result = $this->getSupervisorApprover($employee->employee_id);
        } else if ($employee->classification_id == 3) {
            $approver_result = $this->getManagerApprover($employee->employee_id);
        }

        $endorser = Employee::whereNull('date_resign')->get();

        return response()->json($endorser);
    }

    public function getMrfApprover(Request $request)
    {
        $employee = Auth::user();
        $approver = [];

        if($request->employee_id){
            $employee_id = $request->employee_id;
            $classification_id = $request->classification_id;
        } else {
            $employee_id = $employee->employees->employee_id;
            $classification_id = $employee->employees->classification_id;
        }

        if($classification_id == 1){
            $approver_result = $this->getRankAndFileApprover($employee_id);
        } else if ($classification_id == 2) {
            $approver_result = $this->getSupervisorApprover($employee_id);
        } else if ($classification_id == 3) {
            $approver_result = $this->getManagerApprover($employee_id);
        }

        // Extract employee IDs from the new structure
        $employeeIds = collect($approver_result['endorser'])->pluck('employee_id')->toArray();
        
        // Get endorser details
        $endorser = Employee::with('employee_profile')
            ->whereIn('employee_id', $employeeIds)
            ->get();
        
        $endorser = $endorser->map(function ($endorser) use ($approver_result) {
            // Find the matching approver data from the result
            $approverData = collect($approver_result['endorser'])
                ->firstWhere('employee_id', $endorser->employee_id);
            
            // Add attachment if available
            if ($endorser->employee_profile && $endorser->employee_profile->attachment) {
                $endorser->attachment = asset('storage/employee-profile/' . $endorser->employee_profile->attachment);
            }
            
            // Add the approver type information to the endorser object
            if ($approverData) {
                $endorser->approver_type = $approverData['approver_type'];
                $endorser->employee_data = $approverData['employee_data'];
            }
        
            if($endorser->acting_manager == 1){
                $endorser->classification_id = 3;
            }

            return $endorser;
        });

        return response()->json($endorser);
    }

    public function getRankAndFileApprover($employee_id)
    {
        $approvers = [];
        $approverTypes = [];

        // Define hierarchy order
        $hierarchyOrder = [
            'section' => 1,
            'department' => 2,
            'division' => 3,
            'group' => 4,
            'dealership' => 5
        ];

        $dealer_id = Employee::where('employee_id', $employee_id)->value('dealer_id');

        // Get employee's full organizational context
        $employee = Employee::where('employee_id', $employee_id)->first();
        
        // Section Approver
        $data = Employee::with(['sectionApprover' => function ($query) use ($dealer_id, $employee) {
                $query->where('type', 'section')
                      ->where('dealership_id', $dealer_id)
                      ->where('type_id', $employee->section_id);
            }])
            ->where('employee_id', $employee_id)
            ->whereNull('date_resign')
            ->first();

        if ($data->sectionApprover) {
            $approvers['section'] = $data->sectionApprover->approvers;
            $approverTypes['section'] = $data->sectionApprover;
        }

        // Department Approver
        $data = Employee::with(['departmentApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'department')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->department_id)
                  ->where('group_id', $employee->group_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->departmentApprover) {
            $approvers['department'] = $data->departmentApprover->approvers;
            $approverTypes['department'] = $data->departmentApprover;
        }
        
        // Division Approver
        $data = Employee::with(['divisionApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'division')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->division_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->divisionApprover) {
            $approvers['division'] = $data->divisionApprover->approvers;
            $approverTypes['division'] = $data->divisionApprover;
        }

        // Group Division Approver
        $data = Employee::with(['groupDivisionApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'group')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->group_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->groupDivisionApprover) {
            $approvers['group'] = $data->groupDivisionApprover->approvers;
            $approverTypes['group'] = $data->groupDivisionApprover;
        }

        // Dealership Approver
        $data = Employee::with(['dealershipApprover' => function ($query) use ($dealer_id) {
            $query->where('type', 'dealership')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $dealer_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->dealershipApprover) {
            $approvers['dealership'] = $data->dealershipApprover->approvers;
            $approverTypes['dealership'] = $data->dealershipApprover;
        }

        $flattenedApprovers = collect($approvers)
            ->map(fn($item) => json_decode($item, true))
            ->flatten()
            ->unique()
            ->filter(fn($id) => $id != $employee_id)
            ->toArray();

        $currentUser = Auth::user();
        
        $role_permissions = DB::table('role_permissions')
            ->select('role_permissions.dealership_id')
            ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
            ->where('user_roles.user_id', $currentUser->id)
            ->distinct()
            ->get();

        $dealershipIds = $role_permissions->pluck('dealership_id')->toArray();

        $getTheFinalResult = Employee::select(
                'employees.employee_id', 
                'employees.firstname',
                'employees.middlename',
                'employees.lastname',
                'employees.position_id',
                'employees.email',
                'role_company_access.company_id', 
                'role_company_access.dealership_id'
            )
            ->join('users', 'users.employee_id', '=', 'employees.employee_id')
            ->join('user_roles', 'user_roles.user_id', '=', 'users.id')
            ->join('role_company_access', 'role_company_access.role_id', '=', 'user_roles.role_id')
            ->whereIn('employees.employee_id', $flattenedApprovers)
            ->whereIn('role_company_access.dealership_id', $dealershipIds)
            ->where('employees.employee_id', '!=', $employee_id)
            ->whereNull('employees.date_resign')
            ->get();

        $finalApproverIds = $getTheFinalResult->pluck('employee_id')->toArray();
        $employeeDataMap = $getTheFinalResult->keyBy('employee_id');

        $formattedResult = collect($approvers)
            ->map(function ($approver, $type) use ($finalApproverIds, $employeeDataMap, $approverTypes, $hierarchyOrder, $employee_id) {
                $ids = json_decode($approver, true);
                if (is_array($ids)) {
                    $intersectedIds = array_intersect($ids, $finalApproverIds);
                    $intersectedIds = array_filter($intersectedIds, fn($id) => $id != $employee_id);
                    
                    $approverType = $approverTypes[$type] ?? null;
                    
                    return array_map(function($id) use ($employeeDataMap, $approverType, $hierarchyOrder) {
                        $employee = $employeeDataMap->get($id);
                        return [
                            'employee_id' => $id,
                            'employee_data' => $employee ? [
                                'firstname' => $employee->firstname,
                                'middlename' => $employee->middlename,
                                'lastname' => $employee->lastname,
                                'email' => $employee->email,
                                'position_id' => $employee->position_id,
                                'company_id' => $employee->company_id,
                                'dealership_id' => $employee->dealership_id,
                            ] : null,
                            'approver_type' => $approverType ? [
                                'id' => $approverType->id,
                                'type' => $approverType->type,
                                'type_id' => $approverType->type_id,
                                'dealership_id' => $approverType->dealership_id,
                                'order' => $hierarchyOrder[$approverType->type] ?? 999,
                            ] : null
                        ];
                    }, $intersectedIds);
                }
                return [];
            })
            ->flatten(1)
            ->sortBy(function ($item) {
                return $item['approver_type']['order'] ?? 999;
            })
            ->values()
            ->toArray();

        return [
            'endorser' => $formattedResult
        ];
    }

    public function getSupervisorApprover($employee_id)
    {
        $approvers = [];
        $approverTypes = [];

        $hierarchyOrder = [
            'section' => 1,
            'department' => 2,
            'division' => 3,
            'group' => 4,
            'dealership' => 5
        ];

        $dealer_id = Employee::where('employee_id', $employee_id)->value('dealer_id');
        $employee = Employee::where('employee_id', $employee_id)->first();

        // Section Approver
        $data = Employee::with(['sectionApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'section')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->section_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->sectionApprover) {
            $approvers['section'] = $data->sectionApprover->approvers;
            $approverTypes['section'] = $data->sectionApprover;
        }

        // Department Approver
        $data = Employee::with(['departmentApprover' => function ($query) use ($dealer_id, $employee){
            $query->where('type', 'department')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->department_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->departmentApprover) {
            $approvers['department'] = $data->departmentApprover->approvers;
            $approverTypes['department'] = $data->departmentApprover;
        }

        // Division Approver
        $data = Employee::with(['divisionApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'division')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->division_id)
                  ->where('group_id', $employee->group_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->divisionApprover) {
            $approvers['division'] = $data->divisionApprover->approvers;
            $approverTypes['division'] = $data->divisionApprover;
        }

        // Group Division Approver
        $data = Employee::with(['groupDivisionApprover' => function ($query) use ($dealer_id, $employee) {
            $query->where('type', 'group')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->group_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->groupDivisionApprover) {
            $approvers['group'] = $data->groupDivisionApprover->approvers;
            $approverTypes['group'] = $data->groupDivisionApprover;
        }

        // Dealership Approver
        $data = Employee::with(['dealershipApprover' => function ($query) use ($dealer_id) {
            $query->where('type', 'dealership')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $dealer_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->dealershipApprover) {
            $approvers['dealership'] = $data->dealershipApprover->approvers;
            $approverTypes['dealership'] = $data->dealershipApprover;
        }

        $flattenedApprovers = collect($approvers)
            ->map(fn($item) => json_decode($item, true))
            ->flatten()
            ->unique()
            ->filter(fn($id) => $id != $employee_id)
            ->toArray();

        $currentUser = Auth::user();

        $role_permissions = DB::table('role_permissions')
            ->select('role_permissions.dealership_id')
            ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
            ->where('user_roles.user_id', $currentUser->id)
            ->distinct()
            ->get();

        $dealershipIds = $role_permissions->pluck('dealership_id')->toArray();

        $getTheFinalResult = Employee::select(
                'employees.employee_id', 
                'employees.firstname',
                'employees.middlename',
                'employees.lastname',
                'employees.position_id',
                'employees.email',
                'role_company_access.company_id', 
                'role_company_access.dealership_id'
            )
            ->join('users', 'users.employee_id', '=', 'employees.employee_id')
            ->join('user_roles', 'user_roles.user_id', '=', 'users.id')
            ->join('role_company_access', 'role_company_access.role_id', '=', 'user_roles.role_id')
            ->whereIn('employees.employee_id', $flattenedApprovers)
            ->whereIn('role_company_access.dealership_id', $dealershipIds)
            ->where('employees.employee_id', '!=', $employee_id)
            ->whereNull('employees.date_resign')
            ->get();
        
        $finalApproverIds = $getTheFinalResult->pluck('employee_id')->toArray();
        $employeeDataMap = $getTheFinalResult->keyBy('employee_id');

        $formattedResult = collect($approvers)
            ->map(function ($approver, $approverType) use ($finalApproverIds, $employeeDataMap, $approverTypes, $hierarchyOrder, $employee_id) {
                $ids = json_decode($approver, true);
                if (is_array($ids)) {
                    $intersectedIds = array_intersect($ids, $finalApproverIds);
                    $intersectedIds = array_filter($intersectedIds, fn($id) => $id != $employee_id);
                    
                    $typeObj = $approverTypes[$approverType] ?? null;
                    
                    return array_map(function($id) use ($employeeDataMap, $typeObj, $hierarchyOrder) {
                        $employee = $employeeDataMap->get($id);
                        return [
                            'employee_id' => $id,
                            'employee_data' => $employee ? [
                                'firstname' => $employee->firstname,
                                'middlename' => $employee->middlename,
                                'lastname' => $employee->lastname,
                                'email' => $employee->email,
                                'position_id' => $employee->position_id,
                                'company_id' => $employee->company_id,
                                'dealership_id' => $employee->dealership_id,
                            ] : null,
                            'approver_type' => $typeObj ? [
                                'id' => $typeObj->id,
                                'type' => $typeObj->type,
                                'type_id' => $typeObj->type_id,
                                'dealership_id' => $typeObj->dealership_id,
                                'order' => $hierarchyOrder[$typeObj->type] ?? 999,
                            ] : null
                        ];
                    }, $intersectedIds);
                }
                return [];
            })
            ->flatten(1)
            ->sortBy(function ($item) {
                return $item['approver_type']['order'] ?? 999;
            })
            ->values()
            ->toArray();

        return [
            'endorser' => $formattedResult
        ];
    }

    public function getManagerApprover($employee_id)
    {
        $approvers = [];
        $approverTypes = [];

        $hierarchyOrder = [
            'department' => 2,
            'division' => 3,
            'group' => 4,
            'dealership' => 5
        ];
        
        $dealer_id = Employee::where('employee_id', $employee_id)->value('dealer_id');
        $employee = Employee::where('employee_id', $employee_id)->first();

        // Department Approver
        $data = Employee::with(['departmentApprover' => function ($query) use ($employee_id, $dealer_id, $employee) {
            $query->where('type', 'department')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->department_id)
                  ->where('approvers', '!=', '["'.$employee_id.'"]');
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->departmentApprover) {
            $approvers['department'] = $data->departmentApprover->approvers;
            $approverTypes['department'] = $data->departmentApprover;
        }

        // Division Approver
        $data = Employee::with(['divisionApprover' => function ($query) use ($employee_id, $dealer_id, $employee) {
            $query->where('type', 'division')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->division_id)
                  ->where('approvers', '!=', '["'.$employee_id.'"]');
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->divisionApprover) {
            $approvers['division'] = $data->divisionApprover->approvers;
            $approverTypes['division'] = $data->divisionApprover;
        }

        // Group Division Approver
        $data = Employee::with(['groupDivisionApprover' => function ($query) use ($employee_id, $dealer_id, $employee) {
            $query->where('type', 'group')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $employee->group_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();

        if ($data->groupDivisionApprover) {
            $approvers['group'] = $data->groupDivisionApprover->approvers;
            $approverTypes['group'] = $data->groupDivisionApprover;
        }

        // Dealership Approver
        $data = Employee::with(['dealershipApprover' => function ($query) use ($dealer_id) {
            $query->where('type', 'dealership')
                  ->where('dealership_id', $dealer_id)
                  ->where('type_id', $dealer_id);
        }])
        ->where('employee_id', $employee_id)
        ->whereNull('date_resign')
        ->first();
        
        if ($data->dealershipApprover) {
            $approvers['dealership'] = $data->dealershipApprover->approvers;
            $approverTypes['dealership'] = $data->dealershipApprover;
        }
        
        $flattenedApprovers = collect($approvers)
            ->map(fn($item) => json_decode($item, true))
            ->flatten()
            ->unique()
            ->toArray();

        $currentUser = Auth::user();

        $role_permissions = DB::table('role_permissions')
            ->select('role_permissions.dealership_id')
            ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
            ->where('user_roles.user_id', $currentUser->id)
            ->distinct()
            ->get();

        $dealershipIds = $role_permissions->pluck('dealership_id')->toArray();

        $getTheFinalResult = Employee::select(
                'employees.employee_id', 
                'employees.firstname',
                'employees.middlename',
                'employees.lastname',
                'employees.position_id',
                'employees.email',
                'role_company_access.company_id', 
                'role_company_access.dealership_id'
            )
            ->join('users', 'users.employee_id', '=', 'employees.employee_id')
            ->join('user_roles', 'user_roles.user_id', '=', 'users.id')
            ->join('role_company_access', 'role_company_access.role_id', '=', 'user_roles.role_id')
            ->whereIn('employees.employee_id', $flattenedApprovers)
            ->whereIn('role_company_access.dealership_id', $dealershipIds)
            ->whereNull('employees.date_resign')
            ->get();
            
        $finalApproverIds = $getTheFinalResult->pluck('employee_id')->toArray();
        $employeeDataMap = $getTheFinalResult->keyBy('employee_id');

        $formattedResult = collect($approvers)
            ->map(function ($approver, $type) use ($finalApproverIds, $employeeDataMap, $approverTypes, $hierarchyOrder) {
                $ids = json_decode($approver, true);
                if (is_array($ids)) {
                    $intersectedIds = array_intersect($ids, $finalApproverIds);
                    
                    $approverType = $approverTypes[$type] ?? null;
                    
                    return array_map(function($id) use ($employeeDataMap, $approverType, $hierarchyOrder) {
                        $employee = $employeeDataMap->get($id);
                        return [
                            'employee_id' => $id,
                            'employee_data' => $employee ? [
                                'firstname' => $employee->firstname,
                                'middlename' => $employee->middlename,
                                'lastname' => $employee->lastname,
                                'email' => $employee->email,
                                'position_id' => $employee->position_id,
                                'company_id' => $employee->company_id,
                                'dealership_id' => $employee->dealership_id,
                            ] : null,
                            'approver_type' => $approverType ? [
                                'id' => $approverType->id,
                                'type' => $approverType->type,
                                'type_id' => $approverType->type_id,
                                'dealership_id' => $approverType->dealership_id,
                                'order' => $hierarchyOrder[$approverType->type] ?? 999,
                            ] : null
                        ];
                    }, $intersectedIds);
                }
                return [];
            })
            ->flatten(1)
            ->sortBy(function ($item) {
                return $item['approver_type']['order'] ?? 999;
            })
            ->values()
            ->toArray();

        return [
            'endorser' => $formattedResult
        ];
    }

    public function update(Request $request, int $id)
    {
        // Parse the hierarchy from parents array to get proper IDs
        $hierarchyIds = $this->parseHierarchyFromParents($request->parents, $request->type, $id);
        
        // Build query to find exact matching record
        $query = Approver::where('type_id', '=', $id)
            ->where('type', '=', $request->type);
        
        // Add hierarchy conditions - must match exactly (including nulls)
        foreach (['dealership_id', 'group_id', 'division_id', 'department_id'] as $field) {
            if ($hierarchyIds[$field] !== null) {
                $query->where($field, '=', $hierarchyIds[$field]);
            } else {
                $query->whereNull($field);
            }
        }
        
        $data = $query->first();

        // Ensure approvers is JSON encoded
        $approversJson = is_array($request->approvers) 
            ? json_encode($request->approvers) 
            : $request->approvers;
        
        $validationRules = [
            'approvers' => 'required',
            'type' => 'required|in:dealership,group,division,department,section',
            'type_id' => 'required',
        ];

        $validator = Validator::make([
            'approvers' => $approversJson,
            'type' => $request->type,
            'type_id' => $id,
        ], $validationRules);

        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            $dataToSave = [
                'type_id' => $id,
                'type' => $request->type,
                'approvers' => $approversJson,
                'dealership_id' => $hierarchyIds['dealership_id'],
                'group_id' => $hierarchyIds['group_id'],
                'division_id' => $hierarchyIds['division_id'],
                'department_id' => $hierarchyIds['department_id'],
                'enabled' => 1,
            ];
            
            if (!$data) {
                // Create new record
                $data = Approver::create($dataToSave);
                $message = 'Approvers successfully assigned!';
            } else {
                // Update existing record
                $data->fill($dataToSave);
                $data->save();
                $data->touch();
                $message = 'Approvers successfully updated!';
            }

            DB::connection()->commit();

            return response()->json([
                'message' => $message,
                'status' => 'success',
                'data' => $data,
            ], 201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Parse hierarchy IDs from parents array
     */
    private function parseHierarchyFromParents($parents, $currentType, $currentId)
    {
        $hierarchyIds = [
            'dealership_id' => null,
            'group_id' => null,
            'division_id' => null,
            'department_id' => null,
        ];

        // Process parents array to build hierarchy context
        if (is_array($parents)) {
            foreach ($parents as $parent) {
                if (isset($parent['type']) && isset($parent['id'])) {
                    switch ($parent['type']) {
                        case 'dealership':
                            $hierarchyIds['dealership_id'] = $parent['id'];
                            break;
                        case 'group':
                            $hierarchyIds['group_id'] = $parent['id'];
                            break;
                        case 'division':
                            $hierarchyIds['division_id'] = $parent['id'];
                            break;
                        case 'department':
                            $hierarchyIds['department_id'] = $parent['id'];
                            break;
                    }
                }
            }
        }

        // Set current type's ID in hierarchy
        switch ($currentType) {
            case 'dealership':
                $hierarchyIds['dealership_id'] = $currentId;
                break;
            case 'group':
                $hierarchyIds['group_id'] = $currentId;
                break;
            case 'division':
                $hierarchyIds['division_id'] = $currentId;
                break;
            case 'department':
                $hierarchyIds['department_id'] = $currentId;
                break;
            case 'section':
                // Sections don't have their own column in approvers table
                // type_id will store the section ID
                break;
        }

        return $hierarchyIds;
    }
    
    public function getEmployeeUnderApprover(Request $request)
    {
        $uniqueIds = explode('/', $request->uniqueId);
        $type = $request->approver['type'];

        // Build conditions from uniqueId path
        $conditions = [];
        
        foreach ($uniqueIds as $id) {
            $parts = explode('-', $id);
            
            if (count($parts) === 2) {
                $field = $parts[0] == 'dealership' ? 'dealer_id' : $parts[0] . '_id';
                $value = $parts[1];
                
                $conditions[$field] = $value;
            }
        }
        
        $employees = Employee::where($conditions)
            ->whereNull('date_resign')
            ->get();

        return response()->json($employees);
    }
}