<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;

class SerialExport extends DefaultValueBinder implements FromCollection, WithHeadings, WithCustomValueBinder
, WithColumnFormatting
{
    /**
    * @return \Illuminate\Support\Collection
    */

    protected $itemCode;
    protected $fromSerial;
    protected $toSerial;

    public function __construct($itemCode, $fromSerial, $toSerial)
    {
        $this->itemCode = $itemCode;
        $this->fromSerial = $fromSerial;
        $this->toSerial = $toSerial;
    }

    public function bindValue(Cell $cell, $value)
    {
        $cell->setValueExplicit((string) $value, DataType::TYPE_STRING);

        return true;
    }

    public function collection()
    {
        $rows = [];

        for ($i = $this->fromSerial; $i <= $this->toSerial; $i++) {
            $rows[] = [
                'item_code' => $this->itemCode,
                'serial_number' => str_pad($i, 6, '0', STR_PAD_LEFT),
            ];
        }

        return new Collection($rows);
    }

    public function columnFormats(): array
    {
        return [
            'B' => NumberFormat::FORMAT_TEXT,
        ];
    }

    public function headings(): array
    {
        return [
            'Item Code',
            'Serial Number',
        ];
    }
}
