<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\Company;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use App\Classes\General\Eloquent\ApplyFiltersToQuery;

class ExportsAllCustomersInfoForLarkSystem implements FromQuery, WithMapping, WithHeadings, ShouldAutoSize
{
    use Exportable;

    public function __construct() {}

    public function headings(): array
    {
        return [
            'Marking',
            'Name',
            'Phone Number',
            'Email',
            'Registration Date',
            'Last Order Date',
            'Debtor Code',
            'Custom Segments',
        ];
    }

    public function query()
    {
        return (new ApplyFiltersToQuery())->execute(
            Company::query()->with([
                'employees',
                'segments',
                'contacts'
            ]),
            ['business_type' => 2]
        );
    }

    public function map($company): array
    {
        $employeeEmail = '';
        if ($company->employees->first()) {
            $employeeEmail = $company->employees->first()->email;
        }

        $contactPhone = '';
        if ($company->contacts->first()) {
            $contactPhone = $company->contacts->first()->phone;
        }

        $segments = '';
        if ($company->segments->first()) {
            $segments = $company->segments->pluck('name')->implode(', ');
        }

        return [
            $company->reference,
            $company->name,
            $contactPhone,
            $employeeEmail,
            $company->created_at ? $company->created_at->toDateString() : '',
            $company->updated_at ? $company->updated_at->toDateString() : '',
            $company->debtor,
            $segments,
        ];
    }
}
