<?php
namespace App\Modules\HR\Reports\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;

class PayrollDetailsCrosstabExport implements FromCollection, WithHeadings
{
    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function collection()
    {
        $rows        = $this->data['rows'];
        $allAdditions  = $this->data['all_additions'];
        $allDeductions = $this->data['all_deductions'];
        $allLoans      = $this->data['all_loans'];

        return collect($rows)->map(function ($row) use ($allAdditions, $allDeductions, $allLoans) {
            $employee = $row['employee'];

            $line = [
                $employee->employee_code,
                $employee->epf_no ?? '',
                trim($employee->first_name . ' ' . $employee->middle_name . ' ' . $employee->last_name),
                optional($row['department'])->name ?? '',
                optional($row['designation'])->name ?? '',
                number_format($row['basic_salary'], 2),
            ];

            foreach ($allAdditions as $addition) {
                $amount  = $row['additions'][$addition->id] ?? 0;
                $line[] = number_format($amount, 2);
            }

            $line[] = number_format($row['gross_salary'], 2);

            foreach ($allDeductions as $deduction) {
                $amount  = $row['deductions'][$deduction->id] ?? 0;
                $line[] = number_format($amount, 2);
            }

            foreach ($allLoans as $loan) {
                $amount  = $row['loans'][$loan->id] ?? 0;
                $line[] = number_format($amount, 2);
            }

            $line[] = number_format($row['net_salary'], 2);
            $line[] = number_format($row['epf_12'], 2);
            $line[] = number_format($row['etf_3'], 2);

            return $line;
        });
    }

    public function headings(): array
    {
        $allAdditions  = $this->data['all_additions'];
        $allDeductions = $this->data['all_deductions'];
        $allLoans      = $this->data['all_loans'];

        $headers = [
            'EMP No',
            'EPF No',
            'Employee Name',
            'Department',
            'Designation',
            'Basic Salary',
        ];

        foreach ($allAdditions as $addition) {
            $headers[] = $addition->payslip_label ?: $addition->name;
        }

        $headers[] = 'Gross Salary';

        foreach ($allDeductions as $deduction) {
            $headers[] = $deduction->payslip_label ?: $deduction->name;
        }

        foreach ($allLoans as $loan) {
            $headers[] = $loan->name . ' Recovery';
        }

        $headers[] = 'Net Salary';
        $headers[] = 'EPF 12%';
        $headers[] = 'ETF 3%';

        return $headers;
    }
}
