<?php

namespace Database\Seeders;

use App\Models\OLDLMS\Healthcare;
use App\Models\OLDLMS\Kota;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Str;

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

        $chunks = [];
        $time = now();
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index != 1) {
                    $row_data = [
                        'timezone' => 'Asia/Jakarta',
                        'nIDType' => 2,
                        'nIDCountry' => 1,
                        'sMoto' => 'Memberikan Kesehatan Pelayanan Terbaik',
                        'sStatus' => 1,
                        'sCreateBy' => 9999999,
                    ];

                    $row_data['nIDHealthCareCategory'] = 1; // RS

                    foreach ($row->getCells() as $cell_index => $cell) {
                        if ($cell_index == 2) {
                            $namaKota = $cell->getValue();
                            $kota = Kota::where('sKota', 'LIKE', '%'.$namaKota.'%')->first();
                            if ($kota) {
                                $row_data['nIDKota'] = $kota->nID;
                                $row_data['nIDProvinsi'] = $kota->nIDProvinsi;
                            }
                        }
                        else if ($cell_index == 3) {
                            $row_data['sHealthCare'] = $cell->getValue();
                            $row_data['sSlug'] = Str::slug($row_data['sHealthCare']);
                        }
                        else if ($cell_index == 4) {
                            $row_data['sAlamat'] = $cell->getValue();
                        }
                        else if ($cell_index == 5) {
                            $row_data['sTelp'] = $cell->getValue();
                        }
                    }

                    // $chunks[] = $row_data;
                    try {
                        // Transaction
                        Healthcare::create($row_data);
                    
                    }
                    catch(\Exception $e) {
                        dd($row_data);
                    }
                }

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