<?php

namespace Database\Seeders;

use App\Models\Chemical;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class updateDangerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $filePath = storage_path('danger.csv');
        $file = fopen($filePath, 'r');
        $header = fgetcsv($file);
        $header = $this->removeBOM($header);
        $json = file_get_contents(storage_path('danger.json'));
        $data = json_decode($json, true);
        while (($row = fgetcsv($file)) !== false) {
            //轉換編碼
            $row = array_map(function ($value) {
                return mb_convert_encoding($value, 'UTF-8', 'BIG5');
            }, $row);
            //尋找資料庫有無cas_no
            $casNo = trim($row[0]);
            $findChemical = Chemical::where('cas_no', $casNo)->first();
            //處理工廠危險物品名稱字串
            $chemicalName = trim($row[1]);
            $chemicalNameEx = preg_split('/、|：/', $chemicalName);
            $chemicalNameAfter = count($chemicalNameEx) > 1 ? $chemicalNameEx[1] : $chemicalName;
            $match = collect($data)->firstWhere(function ($item) use ($chemicalNameAfter) {
                return Str::contains($item['name']['name'], $chemicalNameAfter);
            });
            //處理工廠危險物品種類字串
            $chemicalClass = trim($row[2]);
            $chemicalClassEx = explode('、', $chemicalClass);
            $chemicalClassAfter = count($chemicalClassEx) > 1 ? $chemicalClassEx[1] : $chemicalClass;
            if ($match && isset($match['class'])) {
                $matchClass = collect($match['class'])->filter(function ($item) use ($chemicalClassAfter,$row) {
                    $chemExArr = preg_split('/：|:|、|\(|\)/u', $chemicalClassAfter);
                    $chemKeyword = trim($chemExArr[0]);
                    $chemKeyword = rtrim($chemKeyword, '。');
                    $checkClass = trim($item['name']) === $chemKeyword;
                    if(!$checkClass){
                        return Str::contains($item['name'], $chemKeyword);
                    }else{
                        return $checkClass;
                    }
                    
                })->first();
            }
            //處理管理量
            preg_match('/(\d+)(\D+)/', $row[4], $matches);
            preg_match('/\d+/', $row[4], $num);
            $dangerClassId = null;
            $dangerVolume = isset($num[0]) ? $num[0] : 0;
            $dangerNameId = $match['name']['id'] ?? null;
            if ($matches) {
                $water = $matches[2] == '公斤' ? 'kg' : ($matches[2] == '公升' ? 'L' : ($matches[2] == '立方公尺或冷凍能力' ? 'm³' : ''));
            }
            $dangerClassId = $matchClass['id'] ?? null;
            
            if ($findChemical) {
                $findChemical->update([
                    'danger' => 1,
                    'danger_name' => $dangerNameId,
                    'danger_class' => $dangerClassId,
                    'danger_water' => $row[3] == '水溶性液體' ? '1' : ($row[3] == '非水溶性液體' ? '0' : '0'),
                    'danger_unit' => $water,
                    'danger_volume' => $dangerVolume,
                ]);
            } else {
                Chemical::create([
                    'cas_no' => trim($row[0]),
                    'ch_name' => trim($row[5]) ?? null,
                    'en_name' => str_replace(["\r", "\n"], '', trim($row[6])),
                    'toxic_moenv' => 0,
                    'hazards' => 0,
                    'priority' => 0,
                    'control' => 0,
                    'pioneer' => 0,
                    'water_poll' => 0,
                    'concerned' => 0,
                    'pub_hazard' => 0,
                    'solv' => 0,
                    'monitor' => 0,
                    'chem_spec' => 0,
                    'lead' => 0,
                    'four_lead' => 0,
                    'ccd_health' => 0,
                    'expose_conc' => 0,
                    'list_priority' => '0000',
                    'toxic_class' => '0000',
                    'transport_icon' => '00000000000000000000000',
                    'danger' => 1,
                    'danger_name' => $dangerNameId,
                    'danger_class' => $dangerClassId,
                    'danger_water' => $row[3] = '水溶性液體' ? '1' : ($row[3] = '非水溶性液體' ? '0' : ''),
                    'danger_unit' => $water,
                    'danger_volume' => $dangerVolume,
                ]);
            }
        }
    }

    private function removeBOM($header)
    {
        // 檢查是否包含 BOM 字符 (FEFF)
        foreach ($header as &$value) {
            $value = preg_replace('/^\xEF\xBB\xBF/', '', $value); // 移除 BOM
        }
        return $header;
    }
    function convertToBinaryString($input)
    {
        $numbers = explode(",", $input); // 以逗號分割字串
        $binary = 0;

        foreach ($numbers as $num) {
            $binary |= (1 << (4 - intval($num))); // 讓對應的 bit 設為 1
        }

        return str_pad(decbin($binary), 4, "0", STR_PAD_LEFT);
    }
}
