<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\ServiceName;
use Illuminate\Http\Request;
use App\Models\ApprovalHierarchies;
use App\Models\ApprovalRequestHierarchy;

class TestController extends Controller
{
    //

    //dd(decrypt($id));

    public function index($service_name_route, $id)
    {
        // Get service ID based on route
        $service = ServiceName::where('add_route', $service_name_route)->first();

        if (!$service) {
            return "Service not found";
        }

        $service_id = $service->service_id;

        // Decrypt the ID
        // $id = decrypt($id);

        // Get all approval hierarchies with approver relation
        $hierarchies = ApprovalHierarchies::with('approver')
            ->where('service_id', $service_id)
            ->where('table_id', $id)
            ->get();

        // Show all approver names
        foreach ($hierarchies as $hierarchy) {
            echo $hierarchy->approver->name . "<br>";
        }
    }


    public function show_approval_hierarchy($hierarchyId)
    {
        try {
            $hierarchy = \App\Models\ApprovalRequestHierarchy::find($hierarchyId);

            if (!$hierarchy) {
                return redirect()->back()->with('error', 'Approval hierarchy not found.');
            }

            $approverLevels = ['first', 'second', 'third', 'fourth', 'five', 'six', 'seven', 'eight'];
            $employees = [];

            foreach ($approverLevels as $level) {
                $designationKey = "{$level}_approver_designation_id";
                $departmentKey = "{$level}_department_id";


                if (!empty($hierarchy->$designationKey)) {
                    $departmentId = $hierarchy->$departmentKey ?? $hierarchy->requester_department_id;

                    $users = User::with(['departmentUsers.department', 'departmentUsers.ward', 'departmentUsers.prabhags', 'roles'])
                        ->whereHas('departments', function ($q) use ($departmentId) {
                            $q->where('department_id', $departmentId);
                        })
                        ->whereHas('roles', function ($q) use ($hierarchy, $designationKey) {
                            $q->where('id', $hierarchy->$designationKey);
                        })->get();
                    foreach ($users as $user) {
                        $departments = [];
                        $depUsers = $user->departmentUsers->where('department_id', $departmentId);
                        foreach ($depUsers as $depUser) {
                            if (!$depUser->department)
                                continue;

                            $deptName = $depUser->department->name;
                            $wardNames = $depUser->ward ? [$depUser->ward->name] : [];
                            $prabhagNames = $depUser->prabhags ? [$depUser->prabhags->name] : [];

                            if (!isset($departments[$deptName])) {
                                $departments[$deptName] = [
                                    'wards' => [],
                                    'prabhags' => [],
                                ];
                            }

                            $departments[$deptName]['wards'] = array_unique(array_merge($departments[$deptName]['wards'], $wardNames));
                            $departments[$deptName]['prabhags'] = array_unique(array_merge($departments[$deptName]['prabhags'], $prabhagNames));
                        }

                        $employees[$user->id] = [
                            'employee_name' => $user->name,
                            'designation_name' => optional($user->roles->first())->name ?? '-',
                            'departments' => $departments,
                        ];
                    }
                }
            }

            // Reset array keys for Blade iteration
            $employees = array_values($employees);

            return view('test.show', compact('hierarchy', 'employees'));

        } catch (\Exception $e) {
            \Log::error('Error fetching hierarchy employees:', ['exception' => $e]);
            return redirect()->back()->with('error', 'An error occurred while loading hierarchy employees.');
        }
    }



}
