<?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',
        ]);
    
        $temporaryFilePath = 'livewire-tmp/' . $this->file->getFilename();
        
    
        if ($this->sendToEec) {
            $absolutePath = Storage::disk('public')->path($temporaryFilePath);
            $absolutePath = str_replace('/', '\\', $absolutePath);
            $resultEEC = $this->sendMasterFileToEcc($absolutePath);
           
        }
    
        if ($this->createPatch && $this->updatePatch) {
            session()->flash('message', 'กรุณาเลือกอย่างใดอย่างหนึ่ง Create หรือ Update.');
            return;
        }
    
        if ($this->createPatch || $this->updatePatch) {
            $absolutePath = Storage::disk('public')->path($temporaryFilePath);
            $absolutePath = str_replace('/', '\\', $absolutePath);
            $this->processFileForPatch($absolutePath);
        }
    }
    

    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 = file_get_contents($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(center_conf_exchangerate.exdate)) as month, YEAR(MAX(center_conf_exchangerate.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();

                        //DB::enableQueryLog();

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

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

                    // session()->forget('message');
                        
                    $needChkDup = false;
                }

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

                CenterConfExchangerateExport::updateOrInsert(
                    [
                        '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
                        ]);
                    }

                    if ($this->updatePatch) {
                        while(strlen($y2)<4){$y2="0".$y2;}
                        while(strlen($m2)<2){$m2="0".$m2;}
                        $UPDATECODE_update= $y2.$m2;
                        $Loop_pathcode .= '
            Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
            if($countExist!=0){
                exec_query("update conf_exchangerate SET finishdate=\''.$DATE2.'\'
                where currency=\''.$CUR.'\' and exdate =\''.$DATE1.'\'");
            }
            
            Query2Var("select count(*) as countExistEx from conf_exchangerate_export where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
            if($countExistEx!=0){
                exec_query("update conf_exchangerate_export SET finishdate=\''.$DATE2.'\'
                where currency=\''.$CUR.'\' and exdate =\''.$DATE1.'\'");
            }
            
            Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
            if($countExist==0){
                if($DBTYPE==\'MYSQL\'){
                    exec_query("insert into conf_exchangerate (currency,exdate,finishdate,rate,baht,amenddate)
                    VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$IMRATE.'\',\''.$UPDATECODE_update.'\')");
                    exec_query("insert into conf_exchangerate_export (currency,exdate,finishdate,rate,baht,amenddate)
                    VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$EXRATE.'\',\''.$UPDATECODE_update.'\')");
                }
            }
            
            Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
            if($countExist==0){
                if($DBTYPE==\'MSSQL\'){
                    exec_query("insert into conf_exchangerate ([currency],[exdate],[finishdate],[rate],[baht],[amenddate])
                    VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$IMRATE.'\',\''.$UPDATECODE_update.'\')");
                    exec_query("insert into conf_exchangerate_export ([currency],[exdate],[finishdate],[rate],[baht],[amenddate])
                    VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$EXRATE.'\',\''.$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;\nQuery2Array(\"select * from tab_patch_file where ptid='".$next_PID."'\");\nfor("."$"."i=0;"."$"."i<count("."$"."fid);"."$"."i++){\n"."$"."{'file_name_'."."$"."i}="."$"."file_name["."$"."i];\n"."$"."{'file_data_'."."$"."i}="."$"."file_data["."$"."i];\n}\n"."$"."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('patchcode_new.txt');
            // $PATCHCODE = str_replace("'", "''", $PATCHCODE);

            $UNINSTALL = Storage::get('uninstall_new.txt');
            // $UNINSTALL = str_replace("'", "''", $UNINSTALL);

            $i=0;
            $PATCHCODE_SERVER = '';
            $filePath = '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 = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
        $m = (int) $m;
        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');
    }
}
?>
