<?php
namespace App\Exports;

use App\Models\User;
use App\Models\WorkGroup;
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;
    }

    public function collection()
    {
        $query = User::where('users.state', 'active');

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

        if (!empty($this->searchData['users']) && count($this->searchData['users']) > 0) {
            $query->whereIn('users.id', $this->searchData['users']);
        } else {
            if (!empty($this->searchData['committeeId'])) {
                /*
                $workGroupIds = WorkGroup::where('committee_id', $this->searchData['committeeId'])
                    ->pluck('id');

                $query->whereHas('workGroups', function ($q) use ($workGroupIds) {
                    $q->whereIn('work_group_id', $workGroupIds);
                });
                */
                $query->whereHas('committees', function ($query) {
                    $query->where('committee_id', $this->searchData['committeeId']);
                });
            } else if (!empty($this->searchData['workGroupId'])) {
                $query->whereHas('workGroups', function ($q) {
                    $q->where('work_group_id', $this->searchData['workGroupId']);
                });
            } else if (!empty($this->searchData['documentListId'])) {
                $query->whereHas('documentLists', function ($q) {
                    $q->where('document_list_id', $this->searchData['documentListId']);
                });
            }

            if (!empty($this->searchData['memberId'])) {
                $query->where('member_id', $this->searchData['memberId']);
            }
        }

        switch ($this->searchData['orderBy']) {
            case 'company':
                $query->join('members', 'member_id', '=', 'members.id')
                    ->orderBy('members.name', $orderDir);
                break;
            default:
                # name
                $query->orderBy('users.name', $orderDir)
                    ->orderBy('users.last_name', $orderDir);
                break;
        }

        if (empty($this->searchData['documentListId'])) {
            $query->with([
                'workGroups' => function ($query) {
                    $query->full()->where('status', 'published');
                }
            ]);
        }

        return $query->get();
    }

    public function headings(): array
    {
        $headers = [
            'Name',
            'Last Name',
            'Company',
        ];

        $activeLanguage = getActiveLanguage();

        if (!empty($this->searchData['workGroupId'])) {
            $headers[] = $activeLanguage === 'de' ? 'List AN' : 'List TO';
            $headers[] = 'List CC';
        }

        if (!empty($this->searchData['committeeId'])) {
            $headers[] = $activeLanguage === 'de' ? 'List AN' : 'List TO';
            $headers[] = 'List CC';
        }

        if (!empty($this->searchData['documentListId'])) {
            $headers[] = 'E-Mail';
        }

        return $headers;
    }

    public function map($user): array
    {
        $results = [
            $user->name,
            $user->last_name,
            $user->member->name,
        ];

        if (!empty($this->searchData['workGroupId'])) {
            $type = $user->workGroups->find($this->searchData['workGroupId'])->pivot->type;
            if ($type == 'to') {
                $results[] = $user->email;
            } else {
                $results[3] = '';
                $results[4] = $user->email;
            }
        }

        if (!empty($this->searchData['committeeId'])) {
            $type = $user->committees->find($this->searchData['committeeId'])->pivot->type;
            if ($type == 'to') {
                $results[] = $user->email;
            } else {
                $results[3] = '';
                $results[4] = $user->email;
            }
        }

        if (!empty($this->searchData['documentListId'])) {
            $results[] = $user->email;
        }

        return $results;
    }
}
