<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class OrgChartController extends Controller
{
    public function index()
    {
        $currentUser = Auth::user();
        $companyId = $currentUser?->company_id;

        $usersQuery = User::query()
            ->with(['designation', 'department'])
            ->forActiveDirectory();

        if ($companyId) {
            $usersQuery->where('company_id', $companyId);
        }

        $users = $usersQuery->orderBy('name')->get();

        $userIds = $users->pluck('id')->all();
        $nodes = [];
        $childrenByManager = [];

        foreach ($users as $user) {
            $managerId = $user->report_to;
            if ($managerId && ! in_array($managerId, $userIds, true)) {
                $managerId = null;
            }

            $nodes[$user->id] = [
                'id' => $user->id,
                'name' => $user->name,
                'title' => $user->designation?->name ?: ($user->department?->name ?: 'Employee'),
                'report_to' => $managerId,
                'initials' => $user->getInitials(),
                'avatar_color_class' => $user->getAvatarColorClass(),
                'children' => [],
            ];
            $childrenByManager[$managerId ?? 0] = $childrenByManager[$managerId ?? 0] ?? [];
            $childrenByManager[$managerId ?? 0][] = $user->id;
        }

        $buildNode = function (int $id, array $path = []) use (&$buildNode, &$nodes, $childrenByManager): array {
            $node = $nodes[$id];
            if (in_array($id, $path, true)) {
                // Prevent infinite loops for bad cyclical mappings.
                return $node;
            }

            $nextPath = [...$path, $id];
            $childIds = $childrenByManager[$id] ?? [];
            $node['children'] = array_map(
                fn (int $childId) => $buildNode($childId, $nextPath),
                $childIds
            );

            return $node;
        };

        $rootIds = $childrenByManager[0] ?? [];
        $orgTree = collect($rootIds)->map(fn (int $id) => $buildNode($id))->values();

        return view('people.org-chart', [
            'orgTree' => $orgTree,
            'totalEmployees' => $users->count(),
        ]);
    }
}
