<?php

namespace App\Exports;

use App\Models\Newsletter;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;

class NewsletterExport implements FromCollection, WithCustomCsvSettings
{
    protected $type;

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

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        if ($this->type == 'email') {
            return collect(Newsletter::where('email', '!=', null)->get()->map(fn($newsletter) => [
                'data' => $newsletter->email
            ]));
        } else {
            return collect(Newsletter::where('phone', '!=', null)->get()->map(fn($newsletter) => [
                'data' => $newsletter->phone
            ]));
        }
    }

    public function getCsvSettings(): array
    {
        return [
            'delimiter' => ',',
            'use_bom' => true,
            'output_encoding' => 'UTF-8',
            'enclosure' => '',
        ];
    }
}
