<?php

namespace App\Modules\HR\Reports\Data;

use App\Modules\HR\Core\Models\Employee;
use App\Modules\HR\Core\Models\EmployeeExit;
use Carbon\Carbon;

class HeadCountReport
{
     public function getData($filters)
    {
        $query = Employee::with([
            'department',
            'designation'
        ]);

        // Branch filter
        if (!empty($filters['branch_id'])) {
            $query->where('branch_id', $filters['branch_id']);
        }

        // Department filter
        if (!empty($filters['department_id'])) {
            $query->where('department_id', $filters['department_id']);
        }

        $employees = $query->get();

        // 🔥 Group by Department
        $departments = $employees->groupBy('department_id')->map(function ($deptEmployees) {

            $departmentName = optional($deptEmployees->first()->department)->name;

            // 🔥 Group by Designation
            $designations = $deptEmployees->groupBy('designation_id')->map(function ($desEmployees) {

                $designation = $desEmployees->first()->designation;

                $actual = $desEmployees->count();
                $budget = $designation->budget ?? 0;

                return [
                    'designation_name' => optional($designation)->name,
                    'actual' => $actual,
                    'budget' => $budget,
                    'difference' => $actual - $budget,
                ];
            });

            return [
                'department_name' => $departmentName,
                'designations' => $designations->values()
            ];
        });

        return [
            'departments' => $departments->values()
        ];
    }
}
