<?php

namespace App\Modules\HR\Reports\Data;

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

class AdditionDeductionDetailsReport
{
    public function getData($filters)
    {
        $query = Employee::with([
            'branch',
            'department',
            'designation',
            'additions.addition',
            'deductions.deduction'
        ]);

        // 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();

        /*
        ========================================
        Collect Used Additions & Deductions
        ========================================
        */

        $usedAdditions = collect();
        $usedDeductions = collect();

        foreach ($employees as $emp) {
            foreach ($emp->additions as $add) {
                if ($add->addition) {
                    $usedAdditions->push($add->addition);
                }
            }

            foreach ($emp->deductions as $ded) {
                if ($ded->deduction) {
                    $usedDeductions->push($ded->deduction);
                }
            }
        }

        $usedAdditions = $usedAdditions->unique('id')->values();
        $usedDeductions = $usedDeductions->unique('id')->values();

        /*
        ========================================
        Merge Columns (Additions + Deductions)
        ========================================
        */

        $dynamicColumns = collect();

        foreach ($usedAdditions as $add) {
            $dynamicColumns->push([
                'id'   => $add->id,
                'name' => $add->name,
                'type' => 'addition'
            ]);
        }

        foreach ($usedDeductions as $ded) {
            $dynamicColumns->push([
                'id'   => $ded->id,
                'name' => $ded->name,
                'type' => 'deduction'
            ]);
        }

        /*
        ========================================
        Chunking Logic
        ========================================
        */

        $employeesPerPage = 20;
        $columnsPerPage   = 8;

        $employeeChunks = $employees->chunk($employeesPerPage);
        $columnChunks   = $dynamicColumns->chunk($columnsPerPage);

        return [
            'employeeChunks' => $employeeChunks,
            'columnChunks'   => $columnChunks,
            'employees'      => $employees,
            'dynamicColumns' => $dynamicColumns,
        ];
    }
}
