<?php

namespace App\Exports;

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

class LeadsExport implements FromCollection, WithHeadings, WithMapping
{
    public function __construct(private Collection $leads) {}

    public function collection(): Collection
    {
        return $this->leads;
    }

    public function headings(): array
    {
        return [
            'ID',
            'Company',
            'Name',
            'Primary Email',
            'All Emails',
            'Primary Phone',
            'All Phones',
            'Source',
            'Priority',
            'Status',
            'Interest',
            'Call Back',
            'Primary',
            'Created By',
            'Assigned To',
            'Verified At',
            'Client At',
            'Created At',
            'Updated At',
        ];
    }

    public function map($lead): array
    {
        return [
            $lead->id,
            $lead->company?->name ?? 'N/A',
            $lead->name,
            $lead->email ?? 'N/A',
            $lead->emails->pluck('email')->implode(', ') ?: 'N/A',
            trim(($lead->country_code ?? '').' '.($lead->phone ?? '')),
            $lead->phones
                ->map(fn ($phone) => trim(($phone->country_code ?? '').' '.($phone->phone ?? '')))
                ->filter()
                ->implode(', ') ?: 'N/A',
            $lead->source ?? 'N/A',
            $lead->priority ?? 'N/A',
            $lead->status ?? 'N/A',
            $lead->is_interest ? 'Yes' : 'No',
            $lead->is_call_back ? 'Yes' : 'No',
            $lead->is_primary ? 'Yes' : 'No',
            $lead->creator?->name ?? 'N/A',
            $lead->assignee?->name ?? 'N/A',
            $lead->cnvt_to_verified_at,
            $lead->cnvt_to_client_at,
            $lead->created_at,
            $lead->updated_at,
        ];
    }
}
