<?php

namespace App\Exports;

use App\Models\Plainte;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class PlaintesExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithStyles
{
    protected $filters;

    public function __construct(array $filters = [])
    {
        $this->filters = $filters;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $query = Plainte::with(['plaignant', 'media']);

        // Appliquer les filtres
        if (!empty($this->filters['statut'])) {
            $query->where('statut', $this->filters['statut']);
        }

        if (!empty($this->filters['date_debut'])) {
            $query->whereDate('created_at', '>=', $this->filters['date_debut']);
        }

        if (!empty($this->filters['date_fin'])) {
            $query->whereDate('created_at', '<=', $this->filters['date_fin']);
        }

        return $query->get();
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'ID',
            'Référence',
            'Date de réception',
            'Objet',
            'Description',
            'Niveau de sensibilité',
            'Statut',
            'Plaignant',
            'Email du plaignant',
            'Téléphone du plaignant',
            'Date de création',
            'Date de dernière mise à jour',
        ];
    }

    /**
     * @param mixed $plainte
     *
     * @return array
     */
    public function map($plainte): array
    {
        return [
            $plainte->id,
            $plainte->reference,
            $plainte->date_reception->format('d/m/Y H:i'),
            $plainte->objet,
            $plainte->description,
            ucfirst($plainte->niveau_sensibilite),
            ucfirst($plainte->statut),
            $plainte->plaignant ? $plainte->plaignant->full_name : 'Anonyme',
            $plainte->plaignant ? $plainte->plaignant->email : 'N/A',
            $plainte->plaignant ? $plainte->plaignant->telephone : 'N/A',
            $plainte->created_at->format('d/m/Y H:i'),
            $plainte->updated_at->format('d/m/Y H:i'),
        ];
    }

    /**
     * @param Worksheet $sheet
     */
    public function styles(Worksheet $sheet)
    {
        return [
            // Style de l'en-tête
            1 => [
                'font' => ['bold' => true],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'D9EAD3']
                ]
            ],
        ];
    }
}
