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

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

class PayslipExport implements FromCollection, WithHeadings
{
    protected $data;

    public function __construct($data)
    {
        $this->data = $data['payslips'];
    }

    public function collection()
    {
        return collect($this->data)->map(function ($payslip) {
            $employee = $payslip['employee'];
            $detail = $payslip['detail'];
            $process = $payslip['process'];

            // Calculate total additions
            $totalAdditionsBeforeGross = $payslip['additions_before_gross']->sum('amount');
            $totalAdditionsAfterGross = $payslip['additions_after_gross']->sum('amount');
            $totalAdditions = $totalAdditionsBeforeGross + $totalAdditionsAfterGross;

            // Calculate total deductions
            $totalDeductions = $payslip['deductions']->sum('amount');

            // Calculate total loan recovery
            $totalLoans = $payslip['loans']->sum('amount');

            return [
                $employee->employee_code,
                $employee->epf_no,
                trim($employee->first_name . ' ' . $employee->middle_name . ' ' . $employee->last_name),
                optional($employee->designation)->name,
                optional($employee->department)->name,
                optional($employee->branch)->name,
                optional($process->payrollGroup)->name,
                $process->date_from->format('Y-m-d'),
                $process->date_to->format('Y-m-d'),
                number_format($detail->basic_salary, 2),
                number_format($totalAdditions, 2),
                number_format($detail->gross_salary, 2),
                number_format($totalDeductions, 2),
                number_format($totalLoans, 2),
                number_format($detail->net_salary, 2),
                number_format($detail->epf_12, 2),
                number_format($detail->etf_3, 2),
            ];
        });
    }

    public function headings(): array
    {
        return [
            'Employee Code',
            'EPF No',
            'Employee Name',
            'Designation',
            'Department',
            'Branch',
            'Payroll Group',
            'Period From',
            'Period To',
            'Basic Salary',
            'Total Additions',
            'Gross Salary',
            'Total Deductions',
            'Loan Recovery',
            'Net Salary',
            'EPF 12%',
            'ETF 3%',
        ];
    }
}
