<?php

namespace App\Exports\FinancialAccountVoucher;

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

    protected $filteredData;

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

    public function collection()
    {
        return AcReceipt::hydrate($this->filteredData);
    }
    public function map($receipt): array
    {

        $rows = [];
        foreach ($receipt['accountReceiptTransaction'] as $key => $transaction) {
            if ($transaction['transaction_type'] == 'CREDIT') {
                continue;
            }

            $row = [];

            if ($key == 1) {
                $row[] = $receipt['receipt_no'];
                $row[] = ($receipt['receipt_date'] ? str_replace('<br>', ' ', formatedDateTime($receipt['receipt_date'] . ' ' . $receipt['receipt_time'])) : '');
                $row[] = $receipt['accountReceiptDetail']['account']['name'] ?? '';
                $row[] = $receipt['accountReceiptDetail']['voucherType']['name'] ?? '';
                $row[] = $receipt['accountReceiptDetail']['voucherType']['name'] == "OPD Booking" ? $receipt['opdBooking']['booking_no'] ?? '' : $receipt['salesVoucher']['main_invoice_no'] ?? '';
            } else {
                $row = ['', '', '', '', ''];
            }

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

            $rows[] = $row;
        }

        return $rows;
    }

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