<?php

namespace App\Imports;

use App\Models\TodayPrice;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;

class TodayPriceImport implements ToArray, SkipsEmptyRows
{
    public function array(array $array)
    {
        $header = $array[0];
        unset($array[0]);
        $data = [];
        $day = date('Y-m-d');
        foreach ($array as $row) {
            $row = array_map(function ($value) {
                return trim($value);
            }, $row);
            $shopPrice = [];
            foreach ($row as $i => $v) {
                if ($i > 2) {
                    $shopPrice[$header[$i]] = $v;
                }
            }
            $data[] = [
                'day' => $day,
                'external_sku_id' => $row[1],
                'price' => $row[2],
                'shop_price' => json_encode($shopPrice, 256)
            ];
        }
        TodayPrice::query()->delete();
        $model = new TodayPrice();
        $model->batchInsert($data);
    }
}
