<?php

namespace App\Exports;

use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class CashLedgerExport implements FromCollection, WithHeadings, WithMapping, WithColumnFormatting, ShouldAutoSize
{
    public function __construct(
        private Collection $transactions,
        private float $saldoAwal
    ) {}

    public function collection()
    {
        // tambah baris saldo awal agar sama dengan tabel
        $saldoAwalRow = collect([[
            'tanggal' => null,
            'keterangan' => 'Saldo Awal',
            'customer' => null,
            'rekening' => null,
            'debit' => 0,
            'kredit' => 0,
            'saldo' => $this->saldoAwal,
        ]]);

        return $saldoAwalRow->merge($this->transactions);
    }

    public function headings(): array
    {
        return ['Tanggal', 'Keterangan', 'Customer', 'Rekening', 'Debit', 'Kredit', 'Saldo'];
    }

    public function map($trx): array
    {
        $tanggal = null;
        if (!empty($trx['tanggal'])) {
            $tanggal = Carbon::parse($trx['tanggal']); // bisa Carbon/string
        }

        return [
            $tanggal,
            $trx['keterangan'] ?? '',
            $trx['customer'] ?? '-',
            $trx['rekening'] ?? '-',
            (float)($trx['debit'] ?? 0),
            (float)($trx['kredit'] ?? 0),
            (float)($trx['saldo'] ?? 0),
        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_DATE_DATETIME,
            'E' => '"Rp" #,##0',
            'F' => '"Rp" #,##0',
            'G' => '"Rp" #,##0',
        ];
    }
}