<?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 TransactionSummaryReportExport implements FromArray, WithHeadings, WithTitle, ShouldAutoSize
{
    protected $data;

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

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

        // By Type
        $rows[] = ['TRANSACTIONS BY TYPE'];
        $rows[] = ['Type', 'Count', 'Total Amount', 'Total Fees'];
        foreach ($this->data['by_type'] as $type => $stats) {
            $rows[] = [$type, $stats['count'], $stats['total_amount'], $stats['total_fees']];
        }
        $rows[] = [''];

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

        // By Payment Method
        $rows[] = ['TRANSACTIONS BY PAYMENT METHOD'];
        $rows[] = ['Payment Method', 'Count', 'Total Amount'];
        foreach ($this->data['by_payment_method'] as $method => $stats) {
            $rows[] = [$method, $stats['count'], $stats['total_amount']];
        }
        $rows[] = [''];

        // Daily Totals
        $rows[] = ['DAILY TRANSACTION TOTALS'];
        $rows[] = ['Date', 'Count', 'Total Amount', 'Deposits', 'Withdrawals'];
        foreach ($this->data['daily_totals'] as $date => $stats) {
            $rows[] = [$date, $stats['count'], $stats['total_amount'], $stats['deposits'], $stats['withdrawals']];
        }

        return $rows;
    }

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

    public function title(): string
    {
        return 'Transaction Summary';
    }
}
