<?php

namespace App\Exports;

use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class AudienciasPAExport implements FromView, WithColumnWidths, WithStyles, WithEvents
{
    protected $audiencias;

    public function __construct($audiencias)
    {
        $this->audiencias = $audiencias;
    }

    public function view(): View
    {
        return view('audiencias.reportes.xls.procesos-abiertos', [
            'audiencias' => $this->audiencias,
            'hoy' => now()
        ]);
    }

    public function columnWidths(): array
    {
        return [
            'A' => 22,
            'B' => 45,
            'C' => 25,
            'D' => 15,
            'E' => 25,
            'F' => 20,
            'G' => 18,
            'H' => 35,
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => [
                'font' => ['bold' => true],
                'alignment' => [
                    'horizontal' => 'center',
                    'vertical'   => 'center',
                ],
            ],
        ];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {

                $sheet = $event->sheet->getDelegate();

                // 🧊 Congelar primera fila
                $sheet->freezePane('A2');

                // 🔍 Activar filtros
                $highestColumn = $sheet->getHighestColumn();
                $highestRow    = $sheet->getHighestRow();

                $sheet->setAutoFilter("A1:{$highestColumn}1");

                // Centrar encabezados
                $sheet->getStyle("A1:{$highestColumn}1")->getAlignment()
                    ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
            },
        ];
    }

}
