<?php

namespace Database\Seeders;

use App\Models\Icd;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class IcdSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $file_path = resource_path('files/ICD-X-Halodoc.csv'); 
        $reader = ReaderEntityFactory::createReaderFromFile($file_path);
        $reader->open($file_path);

        Icd::truncate();

        $chunks = [];
        $time = now();
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index != 1) {
                    $row_data = [
                        'rev' => 'X',
                        'version' => 'Halodoc',
                        'created_at' => $time,
                    ];
                    foreach ($row->getCells() as $cell_index => $cell) {
                        if ($cell_index == 0) {
                            $row_data['code'] = $cell->getValue();
                        } else if ($cell_index == 1) {
                            $row_data['name'] = $cell->getValue();
                        }
                    }

                    $exploded_code = explode('.', $row_data['code']);
                    if (count($exploded_code) > 1) {
                        $row_data['parent_code'] = $exploded_code[0];
                    } else {
                        $row_data['parent_code'] = NULL;
                    }

                    $chunks[] = $row_data;
                }

                if ($chunks && count($chunks) == 100) {
                    Icd::insert($chunks);
                    $chunks = [];
                }
            }
        }
        if ($chunks && count($chunks) > 0) {
            Icd::insert($chunks);
            $chunks = [];
        }
    }
}
