<?php

namespace App\Exports;

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

class VotingTablesExport implements FromCollection, WithHeadings, WithMapping
{
    public function collection()
    {
        return VotingTable::with('votingLocation.district.province.department')
            ->orderBy('voting_location_id')
            ->orderBy('table_number')
            ->get();
    }

    public function headings(): array
    {
        return [
            'Nro Mesa',
            'Electores',
            'Local de Votación',
            'Dirección',
            'Distrito',
            'Provincia',
            'Departamento',
        ];
    }

    public function map($table): array
    {
        $loc = $table->votingLocation;
        $dist = $loc?->district;
        $prov = $dist?->province;
        $dept = $prov?->department;

        return [
            $table->table_number,
            $table->voter_count ?? '',
            $loc?->name ?? '',
            $loc?->address ?? '',
            $dist?->name ?? '',
            $prov?->name ?? '',
            $dept?->name ?? '',
        ];
    }
}
