<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class UsersExport implements FromCollection, WithHeadings, WithMapping
{
    protected $searchData;

    public function __construct($searchData = []) {
        $this->searchData = $searchData;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $query = User::where('users.state', 'active')
                     ->where('role', '!=', 'super')
                     ->with('legalEntity');

        $orderDir = $this->searchData['orderDir'] ? $this->searchData['orderDir'] : 'asc';

        switch ($this->searchData['orderBy']) {
            case 'company':
                $query->orderBy('company_name', $orderDir);
                break;
            case 'firstName':
                $query->orderBy('first_name', $orderDir);
                break;
            case 'lastName':
                $query->orderBy('last_name', $orderDir);
                break;
            default:
                # creation
                $query->orderBy('created_at', $orderDir);
                break;
        }

        return $query->get();
    }

    public function headings(): array
    {
        return [
            'Name',
            'Last Name',
            'Email',
            'Company',
            'Phone',
            'Fax',
            'Address',
            'House No',
            'Zip',
            'City',
            'Country',
            'Legal Entity'
        ];
    }

    public function map($user): array
    {
        $legalEntityNames = $user->legalEntity->pluck('legal_entity')->implode(', ');

        $results = [
            $user->first_name,
            $user->last_name,
            $user->email,
            $user->company_name,
            $user->phone,
            $user->fax,
            $user->address,
            $user->house_no,
            $user->zip,
            $user->city,
            $user->country,
            $legalEntityNames,
        ];

        return $results;
    }
}
