<?php

namespace App\Exports\FinancialAccountVoucher;

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

    protected $filteredData;

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

    public function collection()
    {
        return PaymentVoucher::with(
            'company',
            'paymentVoucherDetail',
            'paymentVoucherDetails.company',
            'paymentVoucherDetails.user',
            'paymentVoucherDetails.account',
            'paymentVoucherDetails.module'
        )->hydrate($this->filteredData);
    }
    public function map($payment): array
    {

        $rows = [];
        $i = 1;

        foreach ($payment['paymentVoucherDetails'] as $key => $transaction) {
            if ($transaction['transaction_type'] == 'DEBIT' || $transaction['amount'] < 1) {
                continue;
            }

            $row = [];

            if ($key == 1) {
                $row[] = formatedDate($transaction['transaction_date']);
                $row[] = $payment['paymentVoucherDetail']['account']['name'] ?? '';
                $row[] = $payment['paymentVoucherDetail']['voucher_type'] ?? '';
                $row[] = $transaction['transaction_referrence'] ?? '';
            } else {
                $row = ['', '', '', ''];
            }

            $row[] = $transaction['account']['name'] ?? '';
            $row[] = $transaction['payment_mode']['mode'] ?? '';
            $row[] = $transaction['amount'] > 0 ? convertDecimelPoint($transaction['amount']) : "0";

            $rows[] = $row;
        }

        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"
        ];
    }
}
