<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class SavingsPerformanceReportExport implements FromArray, WithHeadings, WithTitle, ShouldAutoSize
{
    protected $data;

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

    public function array(): array
    {
        $rows = [];

        // By Type
        $rows[] = ['SAVINGS ACCOUNTS BY TYPE'];
        $rows[] = ['Type', 'Count', 'Total Balance', 'Average Balance'];
        foreach ($this->data['by_type'] as $type => $stats) {
            $rows[] = [$type, $stats['count'], $stats['total_balance'], $stats['average_balance']];
        }
        $rows[] = [''];

        // By Status
        $rows[] = ['SAVINGS ACCOUNTS BY STATUS'];
        $rows[] = ['Status', 'Count', 'Total Balance'];
        foreach ($this->data['by_status'] as $status => $stats) {
            $rows[] = [$status, $stats['count'], $stats['total_balance']];
        }
        $rows[] = [''];

        // Growth Metrics
        $rows[] = ['GROWTH METRICS'];
        $rows[] = ['Metric', 'Value'];
        $rows[] = ['Total Accounts', $this->data['growth_metrics']['total_accounts']];
        $rows[] = ['Active Accounts', $this->data['growth_metrics']['active_accounts']];
        $rows[] = ['Total Balance', $this->data['growth_metrics']['total_balance']];
        $rows[] = ['Average Balance', $this->data['growth_metrics']['average_balance']];
        $rows[] = ['Monthly Deposits', $this->data['growth_metrics']['monthly_deposits']];
        $rows[] = ['Monthly Withdrawals', $this->data['growth_metrics']['monthly_withdrawals']];
        $rows[] = [''];

        // Member Distribution
        $rows[] = ['MEMBER BALANCE DISTRIBUTION'];
        $rows[] = ['Balance Range', 'Count', 'Total Balance'];
        foreach ($this->data['member_distribution'] as $range => $stats) {
            $rows[] = [$range, $stats['count'], $stats['total_balance']];
        }

        return $rows;
    }

    public function headings(): array
    {
        return [
            'Savings Performance Report - ' . date('M Y')
        ];
    }

    public function title(): string
    {
        return 'Savings Performance';
    }
}
