<?php

namespace App\Exports;

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

class NewJoinSummaryExport implements FromCollection, WithHeadings, ShouldAutoSize
{
    protected $summary;

    protected $employees;

    public function __construct(Collection $summary, $employees)
    {
        $this->summary   = $summary;
        $this->employees = $employees;
    }

    public function headings(): array
    {
        return ['#', 'Employee', 'Total User'];
    }

    public function collection()
    {
        $rows = $this->summary->map(function ($row, $index) {
            $employeeName = $row->marketing_employee_id
                ? ($this->employees[$row->marketing_employee_id] ?? 'Employee #' . $row->marketing_employee_id)
                : 'No employee';

            return [
                $index + 1,
                $employeeName,
                $row->total,
            ];
        });

        $grandTotal = $this->summary->sum('total');
        $rows->push([
            '',
            'Total',
            $grandTotal,
        ]);

        return $rows;
    }
}
