<?php

use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $fmt = new NumberFormatter( 'pl_PL', NumberFormatter::FRACTION_DIGITS);

        $data = $this->process_csv('data/wartosci-odzywcze.csv');
        foreach ($data as $row) {
            $row['kcal'] = (int) $row['kcal'];
            $row['carbohydrates'] = $fmt->parse($row['carbohydrates']);
            $row['protein'] = $fmt->parse($row['protein']);
            $row['fat'] = $fmt->parse($row['fat']);

           Product::create($row);
        }
    }

    public function process_csv($file)
    {
        $file = file($file, FILE_SKIP_EMPTY_LINES);
        $csv = array_map("str_getcsv", $file, array_fill(0, count($file), ';'));
        $keys = array_shift($csv);

        foreach ($csv as $i => $row) {
            $csv[$i] = array_combine($keys, $row);
        }

        $this->multi_rename_key($csv,
            ['Nazwa', 'Kcal', 'Węglowodany', 'Białko', 'Tłuszcz'],
            ['name', 'kcal', 'carbohydrates', 'protein', 'fat']
        );

        return $csv;
    }

    public function multi_rename_key(&$array, $old_keys, $new_keys)
    {
        if (!is_array($array)) {
            ($array == "") ? $array = [] : false;
            return $array;
        }
        foreach ($array as &$arr) {
            if (is_array($old_keys)) {
                foreach ($new_keys as $k => $new_key) {
                    (isset($old_keys[$k])) ? true : $old_keys[$k] = NULL;
                    $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
                    unset($arr[$old_keys[$k]]);
                }
            } else {
                $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
                unset($arr[$old_keys]);
            }
        }
        return $array;
    }
}