<?php

namespace App\Http\Controllers;


use App\Http\Services\ChemicalReviewService;
use App\Http\Services\SdsReviewService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ChemicalReviewController extends Controller
{
    function __construct(protected ChemicalReviewService $chemical, protected SdsReviewService $sdsReview) {}

    function index(){
        return $this->chemical->all();
    }

    function store(Request $request)
    {
        $request->validate([
            'cas_no' => 'required|string|max:255',
            'ch_name' => 'nullable|string|max:255',
            'en_name' => 'required|string|max:255',
            'ChSDS_id.*' => 'nullable|file|mimes:pdf,docx,doc',
            'ENSDS_id.*' => 'nullable|file|mimes:pdf,docx,doc',
            ], [
                'cas_no.required' => '請填寫 CAS 編號。',
                'cas_no.string' => 'CAS 編號必須是文本格式。',
                'cas_no.max' => 'CAS 編號不能超過 255 個字元。',
                'ch_name.string' => '中文名稱必須是文本格式。',
                'ch_name.max' => '中文名稱不能超過 255 個字元。',
                'en_name.required' => '請填寫英文名稱。',
                'en_name.string' => '英文名稱必須是文本格式。',
                'en_name.max' => '英文名稱不能超過 255 個字元。',
                'ChSDS_id.*.file' => '請上傳有效的文件。',
                'ChSDS_id.*.mimes' => '文件類型必須是 pdf, docx, doc',
                'ENSDS_id.*.file' => '請上傳有效的文件。',
                'ENSDS_id.*.mimes' => '文件類型必須是 pdf, docx, doc',
            ]);

        $priorityMolList = $this->chemical->generateBitString($request, 'list_priority', 4);

        $toxicityClassificationList = $this->chemical->generateBitString($request, 'toxic_class', 4);

        $transIconList = $this->chemical->generateBitString($request, 'trans_icon', 22);
        $casno = trim($request->cas_no);


        // $chemical = $this->chemical->store(array_map(function($value){
        //     return $value === null ? '':$value;
        // },
        $chemical = $this->chemical->store([
            'cas_no' => $casno,
            'created_user' => Auth::user()->id,
            'ch_name' => trim($request->ch_name),
            'en_name' => trim($request->en_name),
            'hazards' => (int)$request->hazards,
            'priority' => (int)$request->priority,
            'list_priority' => $priorityMolList,
            'control' => (int)$request->control,
            'pioneer' => (int)$request->pioneer,
            'listNo' => trim($request->listNo),
            'water_poll' => (int)$request->water_poll,
            'concerned' => (int)$request->concerned,
            'list_concerned' => (int)$request->list_concerned,
            'toxic_moenv' => (int)$request->toxic_moenv,
            'toxic_class' => $toxicityClassificationList,
            'conc' => $request->conc,
            'graded' => $request->graded,
            'boil' => $request->boil,
            'melt' => $request->melt,
            'formula' => $request->formula,
            'molecular' => $request->molecular,
            'ingredient' => $request->ingredient,
            'pub_hazard' => (int)$request->pub_hazard,
            'solv' => (int)$request->solv,
            'monitor' => (int)$request->monitor,
            'chem_spec' => (int)$request->chem_spec,
            'lead' =>(int)$request->lead,
            'four_lead' => (int)$request->four_lead,
            'ccd_health' => (int)$request->ccd_health,
            'expose_conc' => (int)$request->expose_conc,
            'pel_solide' => $request->pel_solide,
            'pel_liquid' => $request->pel_liquid,
            'a201' => $request->a201,
            'a202' => $request->a202,
            'a203' => $request->a203,
            'a204' => $request->a204,
            'a205' => $request->a205,
            'a206' => $request->a206,
            'a207' => $request->a207,
            'a208' => $request->a208,
            'a209' => $request->a209,
            'a210' => $request->a210,
            'a211' => $request->a211,
            'a212' => $request->a212,
            'a213' => $request->a213,
            'a214' => $request->a214,
            'a215' => $request->a215,
            'a216' => $request->a216,
            'a217' => $request->a217,
            'a217a' => $request->a217a,
            'a217b' => $request->a217b,
            'a217c' => $request->a217c,
            'a218' => $request->a218,
            'a219' => $request->a219,
            'a220' => $request->a220,
            'a221' => $request->a221,
            'a222' => $request->a222,
            'a223' => $request->a223,
            'a224a' => $request->a224a,
            'a224b' => $request->a224b,
            'a225' => $request->a225,
            'a225a' => $request->a225a,
            'a226' => $request->a226,
            'a226a' => $request->a226a,
            'a227' => $request->a227,
            'a228' => $request->a228,
            'a229' => $request->a229,
            'transport_icon' => $transIconList,
            'created_at' => Carbon::now(),
            'review'=>'0',
            'company_id' => $this->chemical->companyID(),
            'updated_user' => Auth::user()->id,
            'danger'=>(int)$request->danger,
            'danger_volume'=>$request->danger_volume,
            'danger_unit'=>$request->danger_unit,
            'danger_name'=>$request->danger_name,
            'danger_class'=>$request->danger_class,
            'danger_water'=>(int)$request->danger_water,
        ]);

        if ($request->hasFile('ChSDS_id')) {

            $files = $request->file('ChSDS_id');

            if (!is_array($files)) {
                $files = [$files];
            }
            foreach ($files as $file) {
                $fileName = $chemical . '_' . date('Y-m-d') . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('public/sdsReview/ch/'. $fileName);
                $this->sdsReview->store([
                    'chemical_id' => $chemical,
                    'name' => $fileName,
                    'path' => $filePath,
                    'language' => 'ch',
                ]);
            }
        }

        if ($request->hasFile('ENSDS_id')) {
            $files = $request->file('ENSDS_id');
            if (!is_array($files)) {
                $files = [$files];
            }
            foreach ($files as $file) {
                $fileName = $chemical . '_' . date('Y-m-d') . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('public/sdsReview/en/'. $fileName);
                $this->sdsReview->store([
                    'chemical_id' => $chemical,
                    'name' => $fileName,
                    'path' => $filePath,
                    'language' => 'en',
                ]);
            }
        }

        return response()->json([
            'message' => '化學品資料新增成功',
            'chemical' => $chemical
        ], 200);
    }

    function search()
    {
        $list = $this->chemical->search();
    
        return response()->json($list);
    }

    function show($id)
    {
        $chemical = $this->chemical->find($id);
        $priority_array = str_split($chemical->list_priority);
        $priority_bool = array_map(function ($value) {
            return (bool) $value;
        }, $priority_array);

        foreach (range(1, 4) as $i) {
            $chemical['list_priority_' . $i] = $priority_bool[$i - 1];
        };

        $toxi_array = str_split($chemical->toxic_class);
        $toxi_bool = array_map(function ($value) {
            return (bool) $value;
        }, $toxi_array);

        foreach (range(1, 4) as $i) {
            $chemical['toxic_class_' . $i] = $toxi_bool[$i - 1];
        };

        $trans_array = str_split($chemical->transport_icon);
        $trans_bool = array_map(function ($value) {
            return (bool) $value;
        }, $trans_array);

        foreach (range(1, 22) as $i) {
            $chemical['trans_icon_' . $i] = $trans_bool[$i - 1];
        };

        $sdsReview = $chemical->SDSReview;
        if ($sdsReview === null) {
            $sdsReview = []; 
        } else {
            $sdsReview = $sdsReview->toArray(); 
        }
        $filenames = array_column($sdsReview,'name');

        $newfilenames = $this->chemical->processMultipleFilenames($filenames);

        $sdsReview = array_map(function($item,$newName){
            $item['name'] = $newName;
            $item['url'] = config('app.asset_url') . Storage::url($item['path']);
            return $item;
        },$sdsReview,$newfilenames);

        $chemical->SDSReview = $sdsReview;

        $filteredChemical = array_filter($chemical->toArray(), function ($value) {
            return !is_null($value);
        });
    
        return response()->json($filteredChemical);
    }

    function update($id, Request $request)
    {
        $request->validate([
            'cas_no' => 'required|string|max:255',
            'ch_name' => 'nullable|string|max:255',
            'en_name' => 'required|string|max:255',
            'ChSDS_id.*' => 'nullable|file|mimes:pdf,docx,doc',
            'ENSDS_id.*' => 'nullable|file|mimes:pdf,docx,doc',
            ], [
                'cas_no.required' => '請填寫 CAS 編號。',
                'cas_no.string' => 'CAS 編號必須是文本格式。',
                'cas_no.max' => 'CAS 編號不能超過 255 個字元。',
                'ch_name.string' => '中文名稱必須是文本格式。',
                'ch_name.max' => '中文名稱不能超過 255 個字元。',
                'en_name.required' => '請填寫英文名稱。',
                'en_name.string' => '英文名稱必須是文本格式。',
                'en_name.max' => '英文名稱不能超過 255 個字元。',
                'ChSDS_id.*.file' => '請上傳有效的文件。',
                'ChSDS_id.*.mimes' => '文件類型必須是 pdf, docx, doc',
                'ENSDS_id.*.file' => '請上傳有效的文件。',
                'ENSDS_id.*.mimes' => '文件類型必須是 pdf, docx, doc',
            ]);
        $data = $request->all();

        $data['list_priority'] = $this->chemical->generateBitString($request, 'list_priority', 4);
        $data['toxic_class'] = $this->chemical->generateBitString($request, 'toxic_class', 4);
        $data['transport_icon'] = $this->chemical->generateBitString($request, 'trans_icon', 22);
        $data['company_id'] =  $this->chemical->companyID();
        $data['updated_user'] = Auth::user()->id;
        $data['review'] = 3;
        $cc = $this->chemical->find($id);
        $chemical_cas = $cc->cas_no;

        if ($request->cas_no !== $chemical_cas) {
            $existcas = $this->chemical->all()->where('cas_no',$request->cas_no)->first();
            if($existcas){
                return response()->json([
                    'message' => 'Cas No重複'
                ],400);
            }
            $data['cas_no'] = $request->cas_no;
        } else {
            unset($data['cas_no']);
        }

        if ($request->hasFile('ChSDS_id')) {

            $files = $request->file('ChSDS_id');

            if (!is_array($files)) {
                $files = [$files];
            }
            foreach ($files as $file) {
                $fileName = $id . '_' . date('Y-m-d') . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('public/sdsReview/ch/'. $fileName);
                $this->sdsReview->store([
                    'chemical_id' => $id,
                    'name' => $fileName,
                    'path' => $filePath,
                    'language' => 'ch',
                ]);
            }
        }

        if ($request->hasFile('ENSDS_id')) {
            $files = $request->file('ENSDS_id');
            if (!is_array($files)) {
                $files = [$files];
            }
            foreach ($files as $file) {
                $fileName = $id . '_' . date('Y-m-d') . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('public/sdsReview/en/'. $fileName);
                $this->sdsReview->store([
                    'chemical_id' => $id,
                    'name' => $fileName,
                    'path' => $filePath,
                    'language' => 'en',
                ]);
            }
        }

        $this->chemical->update($id, $data);

        return response()->json([
            'message' => '重新申請成功',
            'chemical' => $data
        ], 200);
    }


    function mutidelete(Request $request)
    {
        $ids = $request->input('ids');
        $this->chemical->destroy($ids);
        return response()->json([
            'message' => '化學品資料刪除成功'
        ], 200);
    }

    function reject($id){
        $stat = $this->chemical->find($id);
        $stat->review = '2';
        $stat->save();
        return response()->json([
            'message' => '拒絕'
        ], 200);
    }
}
