namespace App\Exports; use App\Models\Baseline; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; class BaselineExport implements FromCollection, WithHeadings { protected $filters; public function __construct(array $filters = []) { $this->filters = $filters; } public function collection(): Collection { return $this->query() ->get() ->map(function ($b) { $whs = $b->waterHarvestingStructuresPlanning; return [ 'Unit' => optional($b->unit)->name, 'State' => optional($b->state)->name, 'District' => optional($b->district)->name, 'Block' => optional($b->block)->name, 'Panchayat' => optional($b->panchayat)->name, 'Village' => optional($b->village)->name, 'Respondent Name' => $b->name_of_respondent, 'Date of Survey' => $b->date_of_survey, 'Technical Feasibility Score' => $b->technical_feasibility_score, 'Water User Land Total' => $b->water_user_land_total, 'Crop Income Total' => $b->crop_income_total, 'Total Livestock Income' => $b->total_livestock_inc, 'Total' => $b->total, // WHS details (flattened) 'WHS Lengths' => $whs->pluck('length')->implode(', '), 'WHS Widths' => $whs->pluck('width')->implode(', '), 'WHS Depths/Heights' => $whs->pluck('depth_or_height')->implode(', '), 'WHS Latitudes' => $whs->pluck('latitude')->implode(', '), 'WHS Longitudes' => $whs->pluck('longitude')->implode(', '), 'WHS Statuses' => $whs->pluck('status')->implode(', '), 'User ID' => $b->user_id, ]; }); } protected function query() { $query = Baseline::with([ 'unit', 'state', 'district', 'block', 'panchayat', 'village', 'waterHarvestingStructuresPlanning', ]); // Optional filters if (!empty($this->filters['state_id'])) { $query->where('state_id', $this->filters['state_id']); } if (!empty($this->filters['date_from']) && !empty($this->filters['date_to'])) { $query->whereBetween('date_of_survey', [$this->filters['date_from'], $this->filters['date_to']]); } return $query; } public function headings(): array { return [ 'Unit', 'State', 'District', 'Block', 'Panchayat', 'Village', 'Respondent Name', 'Date of Survey', 'Technical Feasibility Score', 'Water User Land Total', 'Crop Income Total', 'Total Livestock Income', 'Total', 'WHS Lengths', 'WHS Widths', 'WHS Depths/Heights', 'WHS Latitudes', 'WHS Longitudes', 'WHS Statuses', 'User ID', ]; } }