<?php

namespace App\Exports;

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

class PaymentExport implements FromCollection, WithHeadings, WithMapping, WithStyles, ShouldAutoSize
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Payments::where('active', 1)
            ->with(['especiality', 'currency', 'paymentMethod'])
            ->orderBy('created_at', 'desc')
            ->get();
    }
    
    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'ID',
            'Referencia',
            'Pagador',
            'Monto',
            'Especialidad',
            'Método de Pago',
            'Moneda',
            'Dirección',
            'Descripción',
            'Fecha de Creación',
            'Última Actualización'
        ];
    }
    
    /**
     * @param mixed $payment
     *
     * @return array
     */
    public function map($payment): array
    {
        return [
            substr($payment->id, -6),
            $payment->reference,
            $payment->payer,
            $payment->amount,
            $payment->especiality->name ?? 'N/A',
            $payment->paymentMethod->title ?? 'N/A',
            $payment->currency->title ?? 'N/A',
            $payment->address_payer ?? 'N/A',
            $payment->description ?? 'N/A',
            $payment->created_at->format('d/m/Y H:i'),
            $payment->updated_at ? $payment->updated_at->format('d/m/Y H:i') : 'N/A'
        ];
    }
    
    /**
     * @param Worksheet $sheet
     *
     * @return void
     */
    public function styles(Worksheet $sheet)
    {
        return [
            // Estilo para la primera fila (encabezados)
            1 => [
                'font' => ['bold' => true],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => '4A90E2']
                ],
                'font' => [
                    'color' => ['rgb' => 'FFFFFF']
                ]
            ]
        ];
    }
}
