<?php

namespace App\Exports;

use App\Models\Grievance;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class GrievancesExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    protected $component;
    protected $fromDate;
    protected $toDate;

    public function __construct($component = 'all', $fromDate = null, $toDate = null)
    {
        $this->component = $component;
        $this->fromDate  = $fromDate;
        $this->toDate    = $toDate;
    }

    public function collection()
    {
        $query = Grievance::query();

        if ($this->component !== 'all') {
            $query->where('component', $this->component);
        }

        if ($this->fromDate) {
            $query->whereDate('report_date', '>=', $this->fromDate);
        }
        if ($this->toDate) {
            $query->whereDate('report_date', '<=', $this->toDate);
        }

        return $query->get();
    }

    public function headings(): array
    {
        return [
            'SN',
            'Component',
            'Complainant Name',
            'Gender',
            'State & AA',
            'County',
            'Payam',
            'Project Beneficiary',
            'Report Date',
            'Grievance Type',
            'Case Category',
            'Evidence Provided',
            'Complaint Channel',
            'Status',
            'GRM Focal Person',
            'Date of Actions',
            'Date of Notification',
        ];
    }

    public function map($grievance): array
    {
        return [
            $grievance->sn,
            'Component ' . $grievance->component,
            $grievance->complainant_name ?? 'Anonymous',
            $grievance->gender ?? '-',
            $grievance->state_aa ?? '-',
            $grievance->county ?? '-',
            $grievance->payam ?? '-',
            $grievance->project_beneficiary ?? '-',
            $grievance->report_date ? $grievance->report_date->format('d/m/Y') : '-',
            $grievance->grievance_type ?? '-',
            $grievance->case_category ?? '-',
            $grievance->evidence_provided ?? '-',
            $grievance->complaint_channel ?? '-',
            $grievance->status ?? 'Open',
            $grievance->grm_focal_person_name ?? '-',
            $grievance->grm_actions_date ? $grievance->grm_actions_date->format('d/m/Y') : '-',
            $grievance->notification_date ? $grievance->notification_date->format('d/m/Y') : '-',
        ];
    }
}