<?php

namespace App\Exports\FinancialAccountVoucher;

use App\Models\AcJournal;
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 JournalVoucherExport implements FromCollection, WithMapping, WithHeadings, WithStyles
{
    use Exportable;

    protected $filteredData;

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

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

        $rows = [];
        $i = 1;

        foreach ($journal['accountJournalTransaction'] as $key => $transaction) {
            if ($key == 0) {
                $count = count($journal['accountJournalTransaction']);
                $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_referrence'] ?? '',
                    $transaction['transaction_type'],
                    convertDecimelPoint($transaction['amount'])
                ];
            }
        }

        return $rows;
    }

    public function headings(): array
    {
        return [
            'DATE',
            'ACCOUNT NAME',
            'VOUCHER TYPE',
            'TRANSACTION REFF.',
            'TRANSACTION MODE',
            'PAYMENT 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"
        ];
    }
}
