<?php

namespace App\Services;

use App\Models\Product;
use Exception;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

class ImportService
{
    const HEADERS_TO_FIELDS = [
        "Фото" => '',
        "Артикул образца"               => 'article',
        "Наименование по ТЗ"            => 'name_tz',
        "Тип по ТЗ"                     => 'type_tz',
        "№ по номенкл."                 => 'nomenclature_number',
        "Габаритные размеры"            => 'sizes',
        "Производитель"                 => 'manufacturer',
        "ед. изм."                      => 'unit',
        "Тип оборудования"              => 'type',
        "Цена поставки"                 => 'product_price',
        "Цена установки"                => 'installation_price',
        "Итого цена"                    => 'total_price',
        "Наименование по паспорту"      => 'manufacturer_name',
        "Примечание"                    => 'note',
    ];


    /**
     * @param string $path
     * @param int $year
     * @return void
     * @throws Exception
     */
    public function handle(string $path, int $year): void
    {
        $path = Storage::disk('upload')->path($path);

        $reader = new Xlsx();
        $spreadsheet = $reader->load($path);
        $sheet = $spreadsheet->getActiveSheet();

        $rowIterator = $sheet->getRowIterator();

        $headers = $this->rowToArray($rowIterator->current());



        if($this->checkHeaders($headers)) {
            foreach ($rowIterator as $row){
                $record = $this->rowToArray($row);
                if($record[0] === 'Фото') continue;

                Product::query()
                    ->updateOrCreate(['year' => $year, 'nomenclature_number' => $record[4]],
                    [
                        'article'           => $record[1],
                        'name_tz'           => $record[2],
                        'type_tz'           => $record[3],
                        'sizes'             => $record[5],
                        'manufacturer'      => $record[6],
                        'unit'              => $record[7],
                        'type'              => $record[8],
                        'product_price'     => $record[9],
                        'installation_price'=> $record[10],
                        'total_price'       => $record[11],
                        'manufacturer_name' => $record[12],
                        'note'              => $record[13],
                    ]);
            }
        } else {
            throw new Exception('Ошибка заголовков файла!');
        }
    }

    protected function rowToArray($row): array
    {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells, even if a cell value is not set.
        $row_content = [];
        foreach ($cellIterator as $cell) {
            $row_content[] = $cell->getValue();
        }

        return $row_content;
    }

    /**
     * @param array $headers
     * @return bool
     */
    protected function checkHeaders(array $headers): bool
    {
        return $this->getHeaders() == $headers;
    }


    /**
     * @return array
     */
    protected function getHeaders(): array
    {
        return array_keys(self::HEADERS_TO_FIELDS);
    }
}