<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithEvents;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Events\AfterSheet;

class ImportTransitReportExport implements FromCollection, WithHeadings, WithMapping, WithEvents
{
    protected $data;

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

    public function headings(): array
    {
        return [
            'No',
            'CRI RFQ Number',
            'Requestor',
            'Shipper',
            'Shipper Location',
            'Shipper Invoice',
            'Shipper Invoice Date',
            'Custom Agent Name',
            'ETA',
            'Status',
            'Delivery Location',
            'ETD Date',
            'Remark',
        ];
    }

    public function collection()
    {
        return collect($this->data);
    }

    public function map($row): array
    {
        static $srNo = 0;
        $srNo++;

        return [
            $srNo,
            $row->cri_rfq_number,
            $row->requester,
            $row->shipper,
            $row->shipper_location,
            $row->shipper_invoice,
            $row->shipper_invoice_date,
            $row->customs_agent_name,
            $row->eta_date,
            $row->status,
            $row->delivery_location,
            $row->etd_date,
            $row->remark,
        ];
    }

    public function registerEvents(): array
    {
        
        return [
            AfterSheet::class => function (AfterSheet $event) {

                $rowNumber = 2; // Excel row starts after header

                foreach ($this->data as $row) {

                    if ((int) $row->is_transit_identified == 1) {

                        $event->sheet
                            ->getStyle("A{$rowNumber}:M{$rowNumber}")
                            ->applyFromArray([
                                'fill' => [
                                    'fillType' => Fill::FILL_SOLID,
                                    'startColor' => [
                                        'rgb' => 'FFFF00',
                                    ],
                                ],
                            ]);
                    }

                    $rowNumber++;
                }
            },
        ];
    }
}
