<?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\Style\Fill;
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']),
            '',
        ];

        // ── 어음 및 외상매출채권 현황 ──
        $noteReceivables = $this->report['note_receivables'] ?? [];

        $rows[] = [];
        $rows[] = [];
        $rows[] = ['어음 및 외상매출채권 현황'];
        $rows[] = ['No.', '내용', '금액', '발행일', '만기일'];

        $noteTotal = 0;
        $no = 1;
        foreach ($noteReceivables as $item) {
            $amount = $item['current_balance'] ?? 0;
            $noteTotal += $amount;
            $rows[] = [
                $no++,
                $item['content'] ?? '-',
                $amount > 0 ? number_format($amount) : '',
                $item['issue_date'] ?? '-',
                $item['due_date'] ?? '-',
            ];
        }

        // 어음 합계
        $rows[] = [
            '합계',
            '',
            number_format($noteTotal),
            '',
            '',
        ];

        return $rows;
    }

    /**
     * 스타일 정의
     */
    public function styles(Worksheet $sheet): array
    {
        $styles = [
            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' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'E0E0E0'],
                ],
            ],
        ];

        // 어음 섹션 헤더 스타일 (동적 행 번호)
        // headings 8행 + details 수 + 합계 2행 + 빈 2행 + 어음 제목 1행 + 어음 헤더 1행
        $detailCount = count($this->report['details']);
        $noteHeaderTitleRow = 8 + $detailCount + 2 + 2 + 1;  // 어음 제목 행
        $noteHeaderRow = $noteHeaderTitleRow + 1;             // 어음 컬럼 헤더 행

        $styles[$noteHeaderTitleRow] = ['font' => ['bold' => true, 'size' => 12]];
        $styles[$noteHeaderRow] = [
            'font' => ['bold' => true],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E0E0E0'],
            ],
        ];

        // 어음 합계 행
        $noteCount = count($this->report['note_receivables'] ?? []);
        $noteTotalRow = $noteHeaderRow + $noteCount + 1;
        $styles[$noteTotalRow] = ['font' => ['bold' => true]];

        return $styles;
    }
}
