<?php

namespace App\Exports;

use App\Models\Patients;
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;
use DateTime;

class PatientExport implements FromCollection, WithHeadings, WithMapping, WithStyles, ShouldAutoSize
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Patients::orderBy('lastname', 'asc')->get();
    }
    
    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'ID',
            'Identificación',
            'Nombre',
            'Apellido',
            'Edad',
            'Género',
            'Correo Electrónico',
            'Teléfono',
            'Fecha de Nacimiento',
            'Tipo de Sangre',
            'Dirección',
            'Representante(s)',
            'Fecha de Registro',
            'Última Actualización'
        ];
    }
    
    /**
     * @param mixed $patient
     *
     * @return array
     */
    public function map($patient): array
    {
        // Formatear la fecha de nacimiento
        $birthday = new DateTime($patient->birthday);
        $birthdayFormatted = $birthday->format('d/m/Y');
        
        // Obtener representantes
        $representatives = Patients::getRepresentatives($patient);
        
        return [
            $patient->id,
            $patient->identification ?? 'N/A',
            $patient->firstname,
            $patient->lastname,
            $patient->age,
            $patient->gender,
            $patient->email ?? 'N/A',
            $patient->phone ?? 'N/A',
            $birthdayFormatted,
            $patient->blood_type ?? 'N/A',
            $patient->address ?? 'N/A',
            $representatives,
            $patient->created_at->format('d/m/Y H:i'),
            $patient->updated_at ? $patient->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']
                ]
            ]
        ];
    }
}
