<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class DailyReportExport implements FromArray, ShouldAutoSize, WithHeadings, WithStyles, WithTitle
{
    public function __construct(
        private readonly array $report
    ) {}

    /**
     * 시트 제목
     */
    public function title(): string
    {
        return '일일일보';
    }

    /**
     * 헤더 정의
     */
    public function headings(): array
    {
        return [
            ['일일 일보 - '.$this->report['date']],
            [],
            ['전일 잔액', number_format($this->report['previous_balance']).'원'],
            ['당일 입금액', number_format($this->report['daily_deposit']).'원'],
            ['당일 출금액', number_format($this->report['daily_withdrawal']).'원'],
            ['당일 잔액', number_format($this->report['current_balance']).'원'],
            [],
            ['구분', '거래처명', '계정과목', '입금액', '출금액', '적요'],
        ];
    }

    /**
     * 데이터 배열
     */
    public function array(): array
    {
        $rows = [];

        foreach ($this->report['details'] as $detail) {
            $rows[] = [
                $detail['type_label'],
                $detail['client_name'],
                $detail['account_code'],
                $detail['deposit_amount'] > 0 ? number_format($detail['deposit_amount']) : '',
                $detail['withdrawal_amount'] > 0 ? number_format($detail['withdrawal_amount']) : '',
                $detail['description'],
            ];
        }

        // 합계 행 추가
        $rows[] = [];
        $rows[] = [
            '합계',
            '',
            '',
            number_format($this->report['daily_deposit']),
            number_format($this->report['daily_withdrawal']),
            '',
        ];

        return $rows;
    }

    /**
     * 스타일 정의
     */
    public function styles(Worksheet $sheet): array
    {
        return [
            1 => ['font' => ['bold' => true, 'size' => 14]],
            3 => ['font' => ['bold' => true]],
            4 => ['font' => ['bold' => true]],
            5 => ['font' => ['bold' => true]],
            6 => ['font' => ['bold' => true]],
            8 => [
                'font' => ['bold' => true],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'E0E0E0'],
                ],
            ],
        ];
    }
}
