<?php

namespace App\Http\Livewire\Pages\ManualResponse;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Http\Controllers\ManualResponse\GenXmlController;
use App\Http\Controllers\ManualResponse\SpnConfigController;
use App\Models\ManualResponse\MasterMessages;
use App\Models\ManualResponse\MasterResponseTemplates;
use App\Models\ManualResponse\MasterDocTypes;
use App\Models\ManualResponse\TabManualResponseLog;
use App\Models\ManualResponse\UsersConnectSpn;
use Carbon\Carbon;
use CURLFile;

class ManualResponse extends Component
{
    public $displayCustomizeDiv = false;

    public $messageTypes = [];
    public $messageId;
    public $responseTemplates = [];
    public $templateId;

    public $templateList;

    public $docTypes = [];
    public $docType;

    public $xmlContent;
    public $xmlData = [];
    public $xmlWithData = [];

    public $activeLoader = false;
    public $changeBtnColor;

    public $lockData;
    public $disableLockData = true;
    public $structureXML;

    protected $rules = [
        'messageId' => 'required|string',
        'templateId' => 'required|string'
    ];

    protected $messages = [
        'messageId.required' => '*Message cannot be empty.',
        'templateId.required' => '*Template cannot be empty.'
    ];

    public function mount()
    {
        $this->messageTypes = MasterMessages::pluck('value', 'id')->toArray();
        $this->docTypes = MasterDocTypes::pluck('name', 'code')->toArray();
        $this->changeBtnColor = "bg-[#A020F0] hover:bg-[#B34FEF] text-white font-bold";
        $this->lockData = false;
        $this->disableLockData = true;
    }

    public function render()
    {
        if ($this->messageId != '') {
            $this->responseTemplates = MasterResponseTemplates::where('mid', $this->messageId)->get()->mapWithKeys(function ($record) {
                $description = $record->description != '' ? ' ' . ' (' . $record->description . ')' : '';
                return [$record->id => $record->code . ': ' . $record->name . $description];
            })->toArray();
            $this->docTypes = MasterDocTypes::where('mid', $this->messageId)->pluck('name', 'code')->toArray();
        }

        return view('livewire.pages.manual-response.manual-response-index');
    }

    public function updatedMessageId()
    {
        $this->templateId = '';
        $this->responseTemplates = [];
        $this->docTypes = [];
        $this->xmlData = [];
        $this->xmlContent = '';
        $this->displayCustomizeDiv = false;
    }

    public function updatedXmlTagInputList()
    {
        if ($this->xmlData === null) {
            $this->xmlContent = '';
        }
    }

    public function gotoCustomize()
    {
        $this->disableLockData = false;
        $tmp_xmlData = $this->xmlData;
        $this->xmlData = [];
        $this->xmlContent = '';
        $this->validate();

        //Default documentType in case messsage is export/import
        if(empty($this->docType)){
            if($this->messageId == 1){
                $this->docType = 1;
            }else if($this->messageId == 2){
                $this->docType = 0;
            }
        }

        $xmlGenerator = new GenXmlController();
        $xml = $xmlGenerator->generateXML($this->templateId, $this->docType, $this->lockData);
        if ($xml == null) {
            session()->flash('templateNotFound', 'Template is not found!');
        } else {
            $this->displayCustomizeDiv = true;
            $this->xmlContent = $xml['xmlContent'];
            $this->xmlData = $xml['xmlWithData'];

            if($this->lockData){
                foreach($this->xmlData as $key => $val){
                    if(isset($tmp_xmlData[$key]) && $key != 'Message'){
                        $this->xmlData[$key] = $tmp_xmlData[$key];
                    }
                }
            }
            
            $this->reGenerateXML();
        }

        $this->changeBtnColor = "bg-slate-150 font-medium text-slate-800 hover:bg-slate-200 focus:bg-slate-200 active:bg-slate-200/80 rounded-md border border-[#e5e7eb] ";
    }

    public function reGenerateXML()
    {
        $xmlGenerator = new GenXmlController();
        $xml = $xmlGenerator->updateXmlValues($this->xmlContent, $this->xmlData);
        $this->xmlContent = $xml;
    }

    public function mockUpXML()
    {
        $this->xmlData = $this->xmlWithData;
    }

    public function generateAndUploadXml()
    {
        $this->reGenerateXML();

        // Generate XML file from string
        $now = Carbon::now();
        $filename = 'manual_response_' . $now->format('Ymd_His') . ".xml";
        Storage::disk('local')->put($filename, $this->xmlContent);
        $filePath = storage_path('app/' . $filename);

        $currentUser = Auth::user();
        $userConnect = UsersConnectSpn::where('uid', $currentUser->id)->first();
        if(!isset($userConnect)){
            $this->dispatchBrowserEvent('open-modal', [
                'name' => 'alert-modal',
                'message' => 'SPN config is not found!',
                'status' => 'failed'
            ]);
            return;
        }

        $spnConfigController = new SpnConfigController();
        $spnConfig = $spnConfigController->init_connection($userConnect);

        if($spnConfig != null && $spnConfig['success'] == 'true'){
            $uid = $spnConfig['uid'];
            $ucode = $spnConfig['ucode'];

            $ch = curl_init();

            $cfile = new CURLFile($filePath, 'application/xml', $filename);
            $postData = [
                'UID' => $uid,
                'UCODE' => $ucode,
                'SERVICENAME' => 'imcoreservice',
                'ACTION' => 'get_response_customs',
                'profilecode' => '',
                'API_PLACE_FILE' => 'Y',
                'file' => $cfile
            ];

            curl_setopt($ch, CURLOPT_URL, $userConnect->link . "/IE5DEV.shippingnet/data_defaulttemplate.php");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);

            TabManualResponseLog::create([
                'uid' => $currentUser->id,
                'title' => 'Send Manual Response',
                'detail' => "Username: " . $userConnect->username . "\nLink: " . $userConnect->link,
                'xml_content' => base64_encode($this->xmlContent),
                'reference_number' => $this->xmlData['ReferenceNumber'],
                'declaration_number' => $this->xmlData['DeclarationNumber'],
                'link' => $userConnect->link
            ]);

            if ($error) {
                //Cannot send response to SPN
                $this->dispatchBrowserEvent('open-modal', [
                    'name' => 'alert-modal',
                    'message' => 'Cannot send response to SPN',
                    'status' => 'failed'
                ]);
            } else {
                $this->dispatchBrowserEvent('open-modal', [
                    'name' => 'alert-modal',
                    'message' => 'Send response successfully',
                    'status' => 'success'
                ]);
                Storage::disk('local')->delete($filename);
            }
        }else if($spnConfig != null && $spnConfig['success'] == 'false'){
            $this->dispatchBrowserEvent('open-modal', [
                'name' => 'alert-modal',
                'message' => $spnConfig['message'],
                'status' => 'failed'
            ]);
        }else{
            //Cannot get UID/UCODE from SPN
            $this->dispatchBrowserEvent('open-modal', [
                'name' => 'alert-modal',
                'message' => 'Cannot connect to SPN',
                'status' => 'failed'
            ]);
        }
    }
}
