<?php

namespace App\Http\Livewire\Pages\Exchangerate;

use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;
use App\Models\CenterConfExchangerate;
use App\Models\CenterConfExchangerateExport;
use App\Models\ConfSmartupdate;
use Illuminate\Support\Facades\DB;

class ExchangerateUpload extends Component
{
    use WithFileUploads;

    public $file;
    public $createPatch = false;
    public $updatePatch = false;
    public $sendToEec = false;

    public function upload()
    {
        $this->validate([
            'file' => 'required|mimes:csv,txt|max:2048',
        ]);

        $filePath = $this->file->store('uploads');

        if ($this->sendToEec) {
            $resultEEC = $this->sendMasterFileToEcc($filePath);
            if ($resultEEC['http_code'] == 200) {
                session()->flash('message', 'Send MasterFile To EEC successfully!');
            } else {
                session()->flash('message', 'Failed to send MasterFile To EEC.');
            }
        }

        if ($this->createPatch && $this->updatePatch) {
            session()->flash('message', 'กรุณาเลือกอย่างใดอย่างหนึ่ง Create หรือ Update.');
            return;
        }

        if ($this->createPatch || $this->updatePatch) {
            $this->processFileForPatch($filePath);
        }
    }

    private function sendMasterFileToEcc($filePath)
    {
        $url = env('URL_MASTERFILE_EEC');
        $postData = [
            'type' => 'exchange-rate',
            'file' => curl_file_create(Storage::path($filePath)),
            'timestamp' => now()->format('Y-m-d')
        ];

        $curl = curl_init();

        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => [
                "cache-control: no-cache",
                "content-type: multipart/form-data"
            ],
        ];

        curl_setopt_array($curl, $options);	
        $response = curl_exec($curl);
        $err = curl_error($curl);
        $info = curl_getinfo($curl);

        curl_close($curl);

        return $info;
    }

    private function processFileForPatch($filePath)
    {
        $fileContent = Storage::get($filePath);
        $lines = explode("\n", $fileContent);
        $needChkDup = true;
        $array_cur = [];
        $Loop_pathcode = '';

        foreach ($lines as $line) {
            $CUR = substr($line, 0, 3);
            if ($CUR != '') {
                if (!in_array($CUR, $array_cur, true)) {
                    $array_cur[] = $CUR;
                }

                $DATE1 = substr($line, 3, 8);
                $d1 = substr($DATE1, 0, 2);
                $m1 = substr($DATE1, 2, 2);
                $y1 = substr($DATE1, 4, 4);
                $DATE1 = "$y1-$m1-$d1";

                $DATE2 = substr($line, 11, 8);
                $d2 = substr($DATE2, 0, 2);
                $m2 = substr($DATE2, 2, 2);
                $y2 = substr($DATE2, 4, 4);
                $DATE2 = "$y2-$m2-$d2";

                $EXRATE = trim(substr($line, 19, 13));
                $IMRATE = trim(substr($line, 32, 13));
                $FACT = trim(substr($line, 45, 7));
                $AMMENDDATE = now()->format('Ymd') + 543;

                if ($needChkDup && $this->createPatch) {
                    $latestRecord = CenterConfExchangerate::selectRaw('MONTH(MAX(exdate)) as month, YEAR(MAX(exdate)) as year')
                        ->join('center_conf_exchangerate_export', function($join) {
                            $join->on('center_conf_exchangerate.currency', '=', 'center_conf_exchangerate_export.currency')
                                 ->on('center_conf_exchangerate.exdate', '=', 'center_conf_exchangerate_export.exdate')
                                 ->on('center_conf_exchangerate.finishdate', '=', 'center_conf_exchangerate_export.finishdate');
                        })->first();

                    $chk = ConfSmartupdate::whereMonth('PDATE', $m2)
                        ->whereYear('PDATE', $y2)
                        ->where('PTYPE', 'UPDATE MASTER NEW')
                        ->exists();

                    if ($chk) {
                        session()->flash('message', 'ไม่สามารถเพิ่ม Patch เดือน '.$m2.' ปี '.$y2.' ได้เนื่องจากได้มีการเพิ่มข้อมูลไว้ในระบบเรียบร้อยแล้ว.');
                        return;
                    }
                    $needChkDup = false;
                }

                CenterConfExchangerate::updateOrCreate(
                    [
                        'currency' => $CUR,
                        'exdate' => $DATE1,
                        'finishdate' => $DATE2
                    ],
                    [
                        'baht' => $IMRATE,
                        'rate' => $FACT,
                        'amenddate' => $AMMENDDATE
                    ]
                );

                CenterConfExchangerateExport::updateOrCreate(
                    [
                        'currency' => $CUR,
                        'exdate' => $DATE1,
                        'finishdate' => $DATE2
                    ],
                    [
                        'baht' => $EXRATE,
                        'rate' => $FACT,
                        'amenddate' => $AMMENDDATE
                    ]
                );

                if ($this->updatePatch) {
                    $y2 = str_pad($y2, 4, '0', STR_PAD_LEFT);
                    $m2 = str_pad($m2, 2, '0', STR_PAD_LEFT);
                    $UPDATECODE_update = $y2 . $m2;

                    $countExist = CenterConfExchangerate::where('exdate', $DATE1)
                        ->where('currency', $CUR)
                        ->count();

                    if ($countExist != 0) {
                        CenterConfExchangerate::where('currency', $CUR)
                            ->where('exdate', $DATE1)
                            ->update(['finishdate' => $DATE2]);
                    }

                    $countExistEx = CenterConfExchangerateExport::where('exdate', $DATE1)
                        ->where('currency', $CUR)
                        ->count();

                    if ($countExistEx != 0) {
                        CenterConfExchangerateExport::where('currency', $CUR)
                            ->where('exdate', $DATE1)
                            ->update(['finishdate' => $DATE2]);
                    }

                    $countExist = CenterConfExchangerate::where('exdate', $DATE1)
                        ->where('currency', $CUR)
                        ->count();

                    if ($countExist == 0) {
                        CenterConfExchangerate::create([
                            'currency' => $CUR,
                            'exdate' => $DATE1,
                            'finishdate' => $DATE2,
                            'rate' => $FACT,
                            'baht' => $IMRATE,
                            'amenddate' => $UPDATECODE_update
                        ]);

                        CenterConfExchangerateExport::create([
                            'currency' => $CUR,
                            'exdate' => $DATE1,
                            'finishdate' => $DATE2,
                            'rate' => $FACT,
                            'baht' => $EXRATE,
                            'amenddate' => $UPDATECODE_update
                        ]);
                    }
                }
            }
        }

        //GEN Patch
        $ins_addMonth = $m2;
        $ins_addYear = $y2;
        $ins_addDay = $d1;

        if ($this->updatePatch) {
            $PDESC = "(UPDATE) อัตราแลกเปลี่ยนของขาเข้า และขาออก เดือน ". $this->monthToThai($m2) ."ปี $y2";
            $PTYPE = "Specific Customer";
            $PDATE = now()->format('Y-m-d H:i:s');
            $PLEVEL = "Critical";
            $PCODE = "";
            $MAJOR_VERSION = 'All';
            $POWNER = auth()->user()->id;

            $PATCHCODE = $Loop_pathcode.' $PATCH_STATUS="OK";';
            $PATCHCODE = str_replace("'", "\'", $PATCHCODE);
            $UNINSTALL='$b=1';

            $next_PID = DB::table('information_schema.tables')
                ->where('table_name', 'conf_smartupdate')
                ->value('AUTO_INCREMENT');

            // Using Eloquent to get the data
            $patchFiles = DB::table('tab_patch_file')->where('ptid', $next_PID)->get();
            $PATCHCODE_SERVER = "$a=1;\n";
            foreach ($patchFiles as $index => $file) {
                $PATCHCODE_SERVER .= "\$file_name_{$index}=\"{$file->file_name}\";\n";
                $PATCHCODE_SERVER .= "\$file_data_{$index}=\"{$file->file_data}\";\n";
            }
            $PATCHCODE_SERVER .= "\$max=count(\$fid);";

            $PATCHCODE_SERVER = str_replace("'", "''", $PATCHCODE_SERVER);
            $PATCHCODE_SERVER = str_replace("\\", "\\\\", $PATCHCODE_SERVER);

            $arr_cur_str = "[".implode(",",$array_cur)."]";
            $PATCHNAME="Update : Exchange Rate Import & Export $m2 / $y2 ".$arr_cur_str;

            ConfSmartupdate::create([
                'PATCHNAME' => $PATCHNAME,
                'PDATE' => $PDATE,
                'PLEVEL' => $PLEVEL,
                'PCODE' => $PCODE,
                'MAJOR_VERSION' => $MAJOR_VERSION,
                'PDESC' => $PDESC,
                'POWNER' => $POWNER,
                'PTYPE' => $PTYPE,
                'PATCHCODE' => $PATCHCODE,
                'UNINSTALL' => $UNINSTALL,
                'PATCHCODE_SERVER' => $PATCHCODE_SERVER,
                'PAPPROVEDATE' => now()
            ]);

            session()->flash('message', 'อัพเดท Patch เดือน '.$m2.' ปี '.$y2.' ในระบบเรียบร้อยแล้ว.');
        }

        if ($this->createPatch) {
            $PDESC = "อัตราแลกเปลี่ยนของขาเข้า และขาออก เดือน ". $this->monthToThai($ins_addMonth) ."ปี $ins_addYear";
            $PTYPE = "UPDATE MASTER NEW";
            $PDATE = "$ins_addYear-$ins_addMonth-$ins_addDay 00:00:00";
            $PLEVEL = "AUTO";
            $PCODE = "SHIPPINGNET";
            $MAJOR_VERSION = 'All';
            $POWNER = auth()->user()->id;

            $PATCHCODE = Storage::get($this->findHTX('patchcode_new.txt'));
            $PATCHCODE = str_replace("'", "''", $PATCHCODE);

            $UNINSTALL = Storage::get($this->findHTX('uninstall_new.txt'));
            $UNINSTALL = str_replace("'", "''", $UNINSTALL);

            $i=0;
            $PATCHCODE_SERVER = '';
            $filePath = $this->findHTX('patchcode_server_new.txt');
            $fileContent = Storage::get($filePath);
            foreach (explode("\n", $fileContent) as $tmp) {
                if ($i==0) {
                    $PATCHCODE_SERVER .= '$MONTH="'.$ins_addYear.'-'.$ins_addMonth.'-%";';
                } else if ($i==1) {
                    $PATCHCODE_SERVER .= '$UPDATECODE='."'".$ins_addYear.$ins_addMonth."'".';';
                } else {
                    $PATCHCODE_SERVER .= $tmp;
                }
                $i++;
            }
            $PATCHCODE_SERVER = str_replace("'", "''", $PATCHCODE_SERVER);

            $PATCHNAME = "Exchange Rate Import & Export $ins_addMonth / $ins_addYear";

            ConfSmartupdate::create([
                'PATCHNAME' => $PATCHNAME,
                'PDATE' => $PDATE,
                'PLEVEL' => $PLEVEL,
                'PCODE' => $PCODE,
                'MAJOR_VERSION' => $MAJOR_VERSION,
                'PDESC' => $PDESC,
                'POWNER' => $POWNER,
                'PTYPE' => $PTYPE,
                'PATCHCODE' => $PATCHCODE,
                'UNINSTALL' => $UNINSTALL,
                'PATCHCODE_SERVER' => $PATCHCODE_SERVER,
                'PAPPROVEDATE' => now()
            ]);

            session()->flash('message', 'สร้าง Patch เดือน '.$ins_addMonth.' ปี '.$ins_addYear.' ในระบบเรียบร้อยแล้ว.');
        }
    }

    private function monthToThai($m)
    {
        $thai_n = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
        return $thai_n[$m-1];
    }

    private function findHTX($filename)
    {
        // Implement findHTX logic based on your requirements
        return $filename;
    }

    public function render()
    {
        return view('livewire.pages.exchangerate.exchangerate-upload');
    }
}
?>
