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

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

class LoanAdvanceSummaryExport implements FromCollection, WithHeadings
{
    protected $data;

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

    public function collection()
    {
        return collect($this->data)->map(function ($summary) {
            $employee = $summary['employee'];
            $employeeLoan = $summary['employee_loan'];
            $loan = $summary['loan'];

            return [
                $employee->employee_code,
                $employee->epf_no,
                trim($employee->first_name . ' ' . $employee->middle_name . ' ' . $employee->last_name),
                optional($employee->department)->name,
                optional($loan)->name,
                $employeeLoan->loan_number,
                optional($employeeLoan->start_date)->format('Y-m-d'),
                $employeeLoan->repayment_period,
                number_format($summary['approved_amount'], 2),
                number_format($employeeLoan->installment_amount, 2),
                $summary['payment_count'],
                number_format($summary['paid_amount'], 2),
                number_format($summary['remaining_amount'], 2),
                $employeeLoan->status,
            ];
        });
    }

    public function headings(): array
    {
        return [
            'Employee Code',
            'EPF No',
            'Employee Name',
            'Department',
            'Loan Type',
            'Loan Number',
            'Start Date',
            'Repayment Period',
            'Approved Amount',
            'Installment Amount',
            'Payments Made',
            'Total Paid',
            'Remaining Balance',
            'Status',
        ];
    }
}
