<?php

namespace App\Exports\FinancialAccountVoucher;

use App\Models\ContraVoucher;
use Maatwebsite\Excel\Concerns\Exportable;
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;

class ContraVoucherExport implements FromCollection, WithMapping, WithHeadings, WithStyles
{
    use Exportable;
    protected $filteredData;

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

    public function collection()
    {
        return ContraVoucher::with(
            'contraVoucherTransaction',
            'contraVoucherTransaction.financialYear',
            'contraVoucherTransaction.company',
            'contraVoucherTransaction.user',
            'contraVoucherTransaction.account',
            'contraVoucherTransaction.module'
        )->hydrate($this->filteredData);
    }
    public function map($journal): array
    {

        $rows = [];
        $i = 1;
        $grandTotal = 0;

        foreach ($journal['contraVoucherTransaction'] as $key => $transaction) {
            $count = count($journal['contraVoucherTransaction']);
            if ($key == 0) {
                $rows[] = [
                    formatedDate($transaction['transaction_date']),
                    $journal['voucher_no'],
                    $transaction['account']['name'],
                    $transaction['voucher_type'],
                    $transaction['transaction_referrence'] ?? '',
                    $transaction['transaction_type'],
                    convertDecimelPoint($transaction['amount']),
                ];
            } else {
                $rows[] = [
                    '',
                    '',
                    $transaction['account']['name'],
                    $transaction['voucher_type'],
                    '',
                    $transaction['transaction_type'],
                    convertDecimelPoint($transaction['amount']),
                ];
            }

            $i++;
        }

        return $rows;
    }

    public function headings(): array
    {
        return [
            'DATE',
            'VOUCHER',
            'ACCOUNT NAME',
            'VOUCHER TYPE',
            'REFERENCE',
            'MODE',
            'AMOUNT'
        ];
    }
    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle(1)->getFont()->setBold(true);
        return [
            // Styling the first row (headings)
            'G' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "Amount"
        ];
    }
}
