<?php

namespace App\Jobs;

use App\Models\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class ImportXlsxJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */

    protected $filename;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $xls = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($this->filename);
        $xls->setReadDataOnly(true);
        $sheet = $xls->load($this->filename);
        $tmpfile = $this->filename . '.txt';

        // read xls to array
        $goods = $sheet->setActiveSheetIndex(0)->toArray();
        unset($sheet, $xls);

        $series = '';
        $i = $created = $updated = 0;
        $no_image = [];

        foreach ($goods as $good) {
            // check first line and skip it
            if ($good[0] === '№п/п' && $good['3'] === 'Наименование') continue;

            // check the line is name of series
            if ($good[0] == NULL && $good[1] == NULL && $good[2] == NULL && is_string($good[3])) {
                $series = $good[3];
                continue;
            }

            // get article from 3rd column
            $tmp = explode("\n", $good[3]);
            if (!isset($tmp[1])) {
                $good[3] = preg_replace('!\s+!', ' ', $good[3]);
                $tmp = explode(' ', $good[3], 2);
            }
            $images = $this->find_images($tmp[0]);
            $data = [
                'series' => $series,
                'name' => (isset($tmp[1])) ? $tmp[1] : 'error',
                'name_for_form' => $good[2],
                'product_group' => $good[1],
                'price' => $good[5],
                'characteristics' => $good[4],
                'tech_description' => $good[7],
                'tech_description_short' => $good[8],
                'image_path' => (!empty($images)) ? $images[0] : $images,
            ];

            $a = Product::query()->updateOrCreate(['article' => $tmp[0]], $data);
            if ($a->wasRecentlyCreated) $created++; else $updated++;
            //echo $i++ . '. Серия: ' . $series . ', артикул: ' . $tmp[0] . '<br>';
            $i++;
            if ($data['image_path'] == '') $no_image[] = $tmp[0];
            $info = ['count' => $i, 'updated' => $updated, 'created' => $created, 'no_image' => $no_image];
            $f = fopen($tmpfile, 'w+');
            fwrite($f, serialize($info));
            fclose($f);
        }
        $info['finished'] = true;
        $f = fopen($tmpfile, 'w+');
        fwrite($f, serialize($info));
        fclose($f);

    }

    private $allfiles; // remember files list

    private function find_images($article)
    {
        $path = base_path('www/') . env('IMAGES_PATH', '---') . '/';
        if (!isset($this->allfiles) || empty($this->allfiles)) {
            $this->allfiles = scandir($path);
        }
        $images = [];
        foreach ($this->allfiles as $filename) {
            if ((mb_strpos($filename, $article) === 0) || (
                    mb_strpos(Str::lower($filename), Str::slug($article)) === 0))
                $images[] = $filename;
        }
        return (!empty($images)) ? $images : '';
    }
}
