<?php

namespace Database\Seeders;

use App\Models\Brand;
use App\Models\Category;
use App\Models\Drug;
use App\Models\DrugCategories;
use App\Models\DrugCategory;
use App\Models\DrugComposition;
use App\Models\DrugUnit;
use App\Models\Ingredient;
use App\Models\Organization;
use App\Models\Unit;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Str;

class DrugSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Drug::truncate();
        Organization::where('type', 'manufacturer')->delete();
        Ingredient::truncate();
        DrugComposition::truncate();
        DrugCategory::truncate();

        $file_path = resource_path('files/daftar_masteritem_ccp_14-06-2022.xlsx'); 
        $reader = ReaderEntityFactory::createReaderFromFile($file_path);
        $reader->open($file_path);

        $chunks = [];
        $time = now();
        $isData = false;
        $cell_map = [ // Urutan kolom di excel
            'no',
            'code',
            'name',
            'group',
            'kategori',
            'satuan',
            'nama_cetak',
            'golongan',
            'sub_golongan',
            'komposisi',
            'sediaan',
            'brand',
            'strength',
            'satuan_strength',
            'pabrikan',
            'jenis',
            'otc',
            'resep',
            'obat_terlarang',
            'pemakaian',
            'essential',
            'live_saving'
        ];
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index >= 6) {
                    $row_data = [];
                    foreach ($row->getCells() as $cell_index => $cell) {
                        $row_data[$cell_map[$cell_index]] = $cell->getValue();
                    }
                    $brand = !empty($row_data['golongan']) ? Brand::firstOrCreate([
                        'name' => $row_data['brand']
                    ], [
                        'name' => $row_data['brand']
                    ]) : null;
                    
                    $manufacturerCode = 'MAN'.str_pad(Str::initials($row_data['pabrikan']), 10, "0", STR_PAD_LEFT);
                    $manufacturer = Organization::firstOrCreate([
                        'code' => $manufacturerCode
                    ], [
                        'name' => $row_data['pabrikan'],
                        'type' => 'manufacturer',
                        'code' => $manufacturerCode
                    ]);

                    if (in_array($row_data['golongan'], ['VITAMINS & MINERALS', 'NUTRITIONS'])) {
                        $type = 'vitamin';
                    } else {
                        $type = 'drug';
                    }

                    if (!empty($row_data['komposisi'])) {
                        $ingredient = Ingredient::firstOrCreate([
                            'substance' => $row_data['komposisi']
                        ], [
                            'substance' => $row_data['komposisi']
                        ]);
                    } else {
                        $ingredient = null;
                    }

                    if (!empty($row_data['sediaan'])) {
                        $sediaan = Unit::firstOrCreate([
                            'name' => $row_data['sediaan']
                        ], [
                            'name' => $row_data['sediaan']
                        ]);
                    } else {
                        $sediaan = null;
                    }

                    $golongan = !empty($row_data['golongan']) ? Category::firstOrCreate([
                        'name' => $row_data['golongan']
                    ], [
                        'name' => $row_data['golongan']
                    ]) : null;

                    $sub_golongan = !empty($row_data['sub_golongan']) ? Category::firstOrCreate([
                        'name' => $row_data['sub_golongan']
                    ], [
                        'name' => $row_data['sub_golongan']
                    ]) : null;

                    $new_drug_data = [
                        'name' => $row_data['name'],
                        'generic_name' => $row_data['nama_cetak'],
                        'code' => $row_data['code'],
                        'description' => null,
                        'brand_id' => $brand->id ?? null,
                        // 'manufacturer_id' => $manufacturer->id ?? null,
                        'mims_class' => null,
                        'indications' => null,
                        'atc_code' => null,
                        'segmentation' => null,
                        'type' => $type,
                        'dosage' => '',
                        'remark' => '',
                        'selling_unit_id' => $sediaan->id ?? null,
                        'status' => 'active',
                        'unit_id' => $sediaan->id ?? null,
                    ];                    
                    $drug = Drug::create($new_drug_data);
                    $drug->identifiers()->create([
                        'use' => 'usual',
                        'type' => 'CCP',
                        'value' => $row_data['code'],
                    ]);

                    if ($ingredient) {
                        DrugComposition::create([
                            'drug_id' => $drug->id,
                            'ingredient_id' => $ingredient->id,
                        ]);
                    }

                    if ($golongan) {
                        DrugCategory::create([
                            'drug_id' => $drug->id,
                            'category_id' => $golongan->id,
                        ]);
                    }

                    if ($sub_golongan) {
                        DrugCategory::create([
                            'drug_id' => $drug->id,
                            'category_id' => $sub_golongan->id,
                        ]);
                    }

                    if ($manufacturer) {
                        $drug->manufacturers()->attach($manufacturer->id);
                    }

                    // $chunks[] = $row_data;
                }

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