<?php

namespace App\Exports;

use App\Models\Transmittal;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\View;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithDefaultStyles;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Style;

class TransmittalsExport implements FromCollection, ShouldAutoSize, ShouldQueue, WithDefaultStyles, WithHeadings, WithMapping
{
    use Exportable, Queueable, SerializesModels;

    public function __construct(
        private readonly array $id
    ) {}

    public function view(): \Illuminate\Contracts\View\View
    {
        $transmittals = Transmittal::query()->with(['client', 'branch', 'files.notes', 'files.remarks'])->whereIn('id', Arr::flatten($this->id))->get();

        return View::make('transmittal.export.transmittal-export-table')->with(['transmittals' => $transmittals]);
    }

    /**
     * @throws Exception
     */
    public function defaultStyles(Style $defaultStyle)
    {
        return $defaultStyle->applyFromArray([
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
            ],

        ]);
    }

    public function headings(): array
    {
        return [
            'series',
            'files',
            'notes',
            'remarks',
        ];
    }

    public function collection()
    {
        $transmittals = Transmittal::query()->with(['client', 'branch', 'files.notes', 'files.remarks'])
            ->withCount(['files', 'notes', 'remarks'])->with(['files' => function ($files) {
                $files->withCount(['notes', 'remarks']);
            }])
            ->whereIn('id', Arr::flatten($this->id))->get();

        return $transmittals;
    }

    public function map($transmittal): array
    {

        $data = [];

        $firstFile = $transmittal->files->first();

        $data[] = [
            $transmittal->series,
            $firstFile?->description,
            $firstFile->notes->first()?->comment,
            $firstFile->remarks->first()?->remark,
        ];

        //iterate comments and remarks for first file
        $notes = $firstFile->notes->pluck('comment');
        $remarks = $firstFile->remarks->pluck('remark');

        $fileNoteCount = count($notes);
        $fileRemarkCount = count($remarks);

        $fileRowCount = $fileNoteCount;
        if ($fileRemarkCount > $fileNoteCount) {
            $fileRowCount = $fileRemarkCount;
        }

        for ($i = 1; $i < $fileRowCount; $i++) {
            $data[] = [
                '',
                '',
                $notes[$i] ?? '',
                $remarks[$i] ?? '',
            ];
        }

        //file iteration except for first file
        $fileRowCounter = 0;
        foreach ($transmittal->files as $file) {
            $notes = $file->notes->pluck('comment');
            $remarks = $file->remarks->pluck('remark');

            $fileNoteCount = count($notes);
            $fileRemarkCount = count($remarks);

            $fileRowCount = $fileNoteCount;
            if ($fileRemarkCount > $fileNoteCount) {
                $fileRowCount = $fileRemarkCount;
            }

            if ($fileRowCounter != 0) {
                $data[] = [
                    '',
                    $file->description,
                    $file->notes->first()?->comment ?? '',
                    $file->remarks->first()?->remark ?? '',
                ];

                //iterate for remaining notes and remarks
                for ($i = 1; $i < $fileRowCount; $i++) {
                    $data[] = [
                        '',
                        '',
                        $notes[$i] ?? '',
                        $remarks[$i] ?? '',
                    ];
                }
            }

            $fileRowCounter++;
        }

        return $data;
    }
}
