<?php

namespace App\Exports;

use App\Models\Saving;
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;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class SavingsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithStyles
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Saving::with('user')->get();
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'ID',
            'Member Name',
            'Membership Number',
            'Amount (KSh)',
            'Type',
            'Status',
            'Maturity Date',
            'Created Date',
            'Branch',
            'Phone Number',
            'Email'
        ];
    }

    /**
     * @param mixed $saving
     * @return array
     */
    public function map($saving): array
    {
        return [
            $saving->id,
            $saving->user->full_name ?? 'N/A',
            $saving->user->membership->membership_number ?? 'N/A',
            number_format($saving->amount, 2),
            ucfirst($saving->type),
            ucfirst($saving->status),
            $saving->maturity_date ? $saving->maturity_date->format('d M Y') : 'N/A',
            $saving->created_at->format('d M Y'),
            $saving->user->branch->name ?? 'N/A',
            $saving->user->phone_number ?? 'N/A',
            $saving->user->email ?? 'N/A'
        ];
    }

    /**
     * @param Worksheet $sheet
     * @return array
     */
    public function styles(Worksheet $sheet)
    {
        return [
            // Style the header row
            1 => [
                'font' => [
                    'bold' => true,
                    'color' => ['rgb' => 'FFFFFF'],
                ],
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => '247F1B'], // Morio Sacco primary color
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical' => Alignment::VERTICAL_CENTER,
                ],
            ],

            // Style data rows
            'A2:Z1000' => [
                'alignment' => [
                    'vertical' => Alignment::VERTICAL_CENTER,
                ],
            ],

            // Style amount column (D)
            'D2:D1000' => [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_RIGHT,
                ],
            ],
        ];
    }
}
