<?php

namespace App\Http\Livewire\Pages\ServerLicense;

use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use Livewire\Component;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use ZipArchive;
use Livewire\WithPagination;

class ServerLicenseEdit extends Component
{
    use WithPagination;
    public $perPage = 10;
    public $tab = 'form';
    public $phpVersions = [];
    public $teams = [];
    public $sizings = [];
    public $customerTypes = [];
    public $dbTypes = [];
    public $ownerTypes = [];

    public $serverKey;
    public $teamId;
    public $customerSize;
    public $customerType;
    public $company;
    public $branch;
    public $status;
    public $licenseDate;
    public $phpVersionId;
    public $currentVersion;
    public $installDate;
    public $installVersion;
    public $databaseType;
    public $ownerType;
    public $hscodeMethod;
    public $customerUrl;
    public $contact;
    public $contactCustomerName;
    public $licenseId;
    public $message, $messages = [];
    protected $listeners = ['gotoModal'];
    public $modalLoaded = false;
    public $SNKEY;
    public $selectDateOrg;
    public $orgList = [];
    public $allDate;
    public $mappingList = [], $labelList = [], $userInterfaceList = [], $globalList = [], $parameterList = [], $onloadList = [], $validateList = [], $mapToList = [], $fileNameList = [];
    protected  $historyPatchList;
    public $sortHistoryField = 'TaskDate';
    public $sortHistoryDirection = 'asc';
    public $globalListGroup = [];
    public $fieldList = ['mapId', 'mapName', 'mapType', 'mapTo', 'mapConfig'];
    public $backupFeedback, $info = [];
    public $mainvarCode;
    public $fileDownloads = [];


    public function loadModal()
    {
        $this->modalLoaded = true;
    }
    public function mount($editId)
    {
        $this->licenseId  = $editId;
        $this->loadData();
    }


    public function loadData()
    {
        $license = ConfServerLicense::find($this->licenseId);

        if ($license) {
            $this->serverKey = $license->SNKEY;
            $this->teamId = $license->NBTEAM;
            $this->customerSize = $license->CUSTOMERSIZE;
            $this->customerType = $license->CUSTOMERTYPE;
            $this->company = $license->COMPANY;
            $this->branch = $license->BRANCH;
            $this->status = $license->STATUS;
            $this->licenseDate = $license->LICENSEDATE;
            $this->phpVersionId = $license->PHP_VERSION_ID;
            $this->currentVersion = $license->CUR_VERSION;
            $this->installDate = $license->INSTALL_DATE;
            $this->installVersion = $license->INSTALL_VERSION;
            $this->databaseType = $license->DATABASETYPE;
            $this->ownerType = $license->OWNERTYPE;
            $this->hscodeMethod = $license->HSCODEMETHOD;
            $this->customerUrl = $license->CUSTOMERURL;
            $this->contact = $license->CONTACT;
            $this->contactCustomerName = $license->CONTACTCUSTOMERNAME;

            if ($license && !empty($license->BACKUP_FEEDBACK)) {
                $compressedData = gzuncompress(base64_decode($license->BACKUP_FEEDBACK));
                $this->backupFeedback = $compressedData;
                $currentEncoding = mb_detect_encoding($compressedData, mb_detect_order(), true);

                $this->info = null;
                eval('$this->info = ' . trim($compressedData) . ';');
            }
        }

        $this->phpVersions  = DB::table('master_php_ver')
            ->orderBy('id', 'asc')
            ->get();

        $this->teams = DB::table('master_team')
            ->orderBy('id', 'asc')
            ->get();

        $this->sizings = DB::table('master_size')
            ->orderBy('id', 'asc')
            ->get();

        $this->customerTypes  = DB::table('master_sizeType')
            ->orderBy('id', 'asc')
            ->get();

        $this->dbTypes  = DB::table('master_dbtype')
            ->orderBy('id', 'asc')
            ->get();

        $this->ownerTypes  = DB::table('conf_server_ownertype')
            ->orderBy('owntypeid', 'asc')
            ->get();
    }
    public function updateLicense()
    {
        // dd( $this->teamId);
        $license = ConfServerLicense::find($this->licenseId);

        if ($license) {
            $license->update([
                'SNKEY' => $this->serverKey,
                'NBTEAM' => $this->teamId,
                'CUSTOMERSIZE' => $this->customerSize,
                'CUSTOMERTYPE' => $this->customerType,
                'COMPANY' => $this->company,
                'BRANCH' => $this->branch,
                'STATUS' => $this->status,
                'LICENSEDATE' => $this->licenseDate,
                'PHP_VERSION_ID' => $this->phpVersionId,
                'CUR_VERSION' => $this->currentVersion,
                'INSTALL_DATE' => $this->installDate,
                'INSTALL_VERSION' => $this->installVersion,
                'DATABASETYPE' => $this->databaseType,
                'OWNERTYPE' => $this->ownerType,
                'HSCODEMETHOD' => $this->hscodeMethod,
                'CUSTOMERURL' => $this->customerUrl,
                'CONTACT' => $this->contact,
                'CONTACTCUSTOMERNAME' => $this->contactCustomerName,
            ]);

            $message = 'Server License updated successfully!';
            $this->message = $message;
            // session()->flash('message', 'Server License updated successfully!');
        }
    }
    public function loadPage($page)
    {
        $this->emit('menuChanged', $page);
    }
    public function updatedSelectDateOrg()
    {
        $this->loadOrganize();
    }

    public function loadOrganize()
    {
        $this->tab = 'organize';
        $license = ConfServerLicense::find($this->licenseId);
        $this->SNKEY = $license->SNKEY;

        $this->allDate = DB::table('conf_server_license_orgcontrol')
            ->select('id', 'createDate')
            ->where('SNKEY', $this->SNKEY)
            ->orderByDesc('id')
            ->get();
        if (empty($this->selectDateOrg)) {
            if (isset($this->allDate)) {
                foreach ($this->allDate as $date) {
                    $this->selectDateOrg = $date->id ?? '';
                    break;
                }
            }
        }

        $this->orgList = DB::table('conf_server_license_orglist')
            ->where('controlId', $this->selectDateOrg)
            ->orderBy('id')
            ->get()
            ->toArray();

        foreach ($this->orgList as $orgData) {
            $profileList = DB::table('conf_server_license_orglist_profile')
                ->where('orglistId', $orgData->id)
                ->get();
            $orgData->profileList = $profileList ? $profileList : '';

            // Fetch document type by org
            $docTypeList = DB::table('conf_server_license_orglist_doctype as a')
                ->join('u01r_doctype as b', 'a.docType', '=', 'b.DTNAME')
                ->where('a.orglistId', $orgData->id)
                ->get();
            $orgData->docTypeList = $docTypeList ? $docTypeList : '';
        }
    }
    public function loadMapping()
    {
        $this->tab = 'csvMapping';

        if ($this->info && isset($this->info['DATA']['conf_mapping'])) {
            $this->mappingList =  $this->info['DATA']['conf_mapping'];
            foreach ($this->mappingList['mapConfig'] as $index => $config) {
                $this->mappingList['mapConfig'][$index] = base64_decode($config);
            }
        }
    }
    public function saveMapping()
    {
        $fieldList = ['mapId', 'mapName', 'mapType', 'mapTo', 'mapConfig'];
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->mappingList[$field] as $index => $value) {
                if ($field == 'mapConfig') {
                    $DATA[$field][] = base64_encode(htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES));
                } else {
                    $DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
                }
            }
        }

        $this->info['DATA']['conf_mapping'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Mapping data saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadMapping();
        $message = 'CSV Mapping updated successfully!';
        $this->message = $message;
    }


    public function loadPrintForm()
    {
        $this->tab = 'printForm';

        if ($this->info && isset($this->info['DATA']['conf_label_form'])) {
            $this->labelList =  $this->info['DATA']['conf_label_form'];
        }
    }
    public function savePrintForm()
    {
        $fieldList = array('lid', 'form_name', 'l_name', 'l_value', 'x', 'y', 'parentId', 'editLayout', 'width', 'height', 'type', 'format');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->mappingList[$field] as $index => $value) {
                $DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
            }
        }

        $this->info['DATA']['conf_label_form'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Print form saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadPrintForm();
        $message = 'Print form updated successfully!';
        $this->message = $message;
    }

    public function loadUserInterface()
    {
        $this->tab = 'userInterface';

        if ($this->info && isset($this->info['DATA']['conf_ui'])) {
            $this->userInterfaceList =  $this->info['DATA']['conf_ui'];
        }
    }
    public function saveUserInterface()
    {

        $fieldList = array('pageCode', 'name', 'tname', 'required', 'type', 'spec', 'manual', 'user_note', 'js_before_focus', 'cannotImport', 'fname', 'reportFlag', 'reportOrderBy', 'reportCondition', 'reportTable', 'reportType', 'reportFormat', 'reportAlign', 'user_default');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->userInterfaceList[$field] as $index => $value) {
                if ($field == 'user_default') {
                    $DATA[$field][] = base64_encode(htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES));
                } else {
                    $DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
                }
            }
        }

        $this->info['DATA']['conf_ui'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'User Interface saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }

        $this->loadData();
        $this->loadPrintForm();
        $message = 'User Interface updated successfully!';
        $this->message = $message;
    }

    public function loadGlobal()
    {
        $this->tab = 'global';

        if ($this->info && isset($this->info['DATA']['conf_global'])) {
            $this->globalList =  $this->info['DATA']['conf_global'];
        }

        $groupedData = [];
        $globalTemp = $this->globalList;
        if(!empty($globalTemp)) {
            foreach ($globalTemp['profilecode'] as $index => $profileCode) {
                if (isset($globalTemp['name'][$index]) && isset($globalTemp['value'][$index])) {
                    if (!isset($groupedData[$profileCode])) {
                        $groupedData[$profileCode] = [];
                    }
                    $groupedData[$profileCode][] = [
                        'name' => $globalTemp['name'][$index],
                        'value' => $globalTemp['value'][$index],
                        'profilecode' => $profileCode
                    ];
                }
            }
        }
     

        $this->globalListGroup =  $groupedData;
    }
    public function saveGlobal()
    {

        $fieldList = array('name', 'value', 'profilecode');
        $DATA = [];

        foreach ($this->globalListGroup as $profileCode => $profileData) {
            foreach ($profileData as $index => $item) {
                foreach ($fieldList as $field) {
                    if (isset($item[$field])) {
                        $DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $item[$field]), ENT_QUOTES);
                    }
                }
            }
        }

        $this->info['DATA']['conf_global'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Global saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadPrintForm();
        $message = 'Global updated successfully!';
        $this->message = $message;
    }
    public function loadParameter()
    {
        $this->tab = 'parameter';

        if ($this->info && isset($this->info['DATA']['conf_parameter'])) {
            $this->parameterList =  $this->info['DATA']['conf_parameter'];
        }
        //   dd($this->parameterList);

    }
    public function saveParameter()
    {

        $fieldList = array('PID', 'name', 'value', 'description', 'active');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->parameterList[$field] as $index => $value) {
                $DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
            }
        }
        //   
        $this->info['DATA']['conf_parameter'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Parameter saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }

        $this->loadData();
        $this->loadParameter();
        $message = 'Parameter updated successfully!';
        $this->message = $message;
    }

    public function loadOnload()
    {
        $this->tab = 'onload';

        if ($this->info && isset($this->info['DATA']['conf_onload'])) {
            $this->onloadList =  $this->info['DATA']['conf_onload'];
        }
        //    dd($this->onloadList);
    }
    public function saveOnload()
    {

        $fieldList = array('SKEY', 'SERVNAME', 'ACT', 'ONLOAD');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->onloadList[$field] as $index => $value) {
                $DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
            }
        }

        $this->info['DATA']['conf_onload'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Onload saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadOnload();
        $message = 'Onload updated successfully!';
        $this->message = $message;
    }

    public function loadValidate()
    {
        $this->tab = 'validate';

        if ($this->info && isset($this->info['DATA']['conf_validate'])) {
            $this->validateList =  $this->info['DATA']['conf_validate'];
        }
        //    dd($this->validateList);
    }
    public function saveValidate()
    {

        $fieldList = array('id', 'step', 'level', 'name', 'desc', 'validateCode', 'doctype', 'active');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->validateList[$field] as $index => $value) {
                $DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
            }
        }

        $this->info['DATA']['conf_validate'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Validate saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadValidate();


        $message = 'Validate updated successfully!';
        // $this->message = $message;
        $this->setMessage($message);
    }

    public function loadMapTo()
    {
        $this->tab = 'mapTo';

        if ($this->info && isset($this->info['DATA']['conf_mapto'])) {
            $this->mapToList =  $this->info['DATA']['conf_mapto'];
        }
    }
    public function saveMapTo()
    {

        $fieldList = array('id', 'name', 'code', 'type');
        $DATA = [];

        foreach ($fieldList as $field) {
            foreach ($this->mapToList[$field] as $index => $value) {
                if ($field == 'code') {
                    $DATA[$field][] = base64_encode(htmlspecialchars_decode($value, ENT_QUOTES));
                } else {
                    $DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
                }
            }
        }
        $this->info['DATA']['conf_mapto'] = $DATA;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Map To saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadMapTo();


        $message = 'MapTo updated successfully!';
        // $this->message = $message;
        $this->setMessage($message);
    }

    public function loadMainVar()
    {
        $this->tab = 'mainVar';

        if ($this->info && isset($this->info['MAINVAR'])) {
            $this->mainvarCode =  $this->info['MAINVAR'];
        }
    }
    public function saveMainVar()
    {

        $this->info['MAINVAR'] = $this->mainvarCode;

        $newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));

        $license = ConfServerLicense::find($this->licenseId);
        if ($license) {
            $updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
            if ($updatedRows > 0) {
                $message =  'Main Var saved successfully!';
            } else {
                $message =  'No changes were made.';
            }
        }
        $this->loadData();
        $this->loadMainVar();

        $message = 'Main Var updated successfully!';
        $this->setMessage($message);
    }

    public function loadFileDownload()
    {
        $this->tab = 'fileDownload';

        if ($this->info && isset($this->info['FileDownload'])) {
            $this->fileDownloads =  $this->info['FileDownload'] ?? [];
            $this->fileNameList = $this->info['Filename'] ?? [];
        }
    }

    public function downloadAllFile()
    {
        $dateCurrent = now()->format('Y-m-d H:i:s');

        $zip = new ZipArchive();
        $dateExport = now()->format('Ymd');
        $zipName = "{$this->SNKEY}_{$dateExport}.zip";
        $zipFilePath = storage_path("app/temp/{$zipName}");

        if (!Storage::exists('temp')) {
            Storage::makeDirectory('temp');
        }

        if ($zip->open($zipFilePath, ZipArchive::CREATE) !== true) {
            return response()->json(['error' => "Cannot open <$zipFilePath>"], 500);
        }

        $fileDownloads = $this->info['FileDownload'] ?? [];
        $filenames = $this->info['Filename'] ?? [];
        $textLog = "\n{$dateCurrent} {$this->SNKEY} ??TempUser?? [ ";

        foreach ($fileDownloads as $key => $codeFile) {
            $filename = $filenames[$key] ?? 'unknown_file' . $key . '.txt';
            $filename = ltrim($filename, './');
            $tempFilePath = storage_path('app/temp/' . $filename);

            $dirname = dirname($tempFilePath);
            if (!is_dir($dirname)) {
                mkdir($dirname, 0777, true);
            }

            if (file_put_contents($tempFilePath, $codeFile) !== false) {
                $tempFiles[] = $tempFilePath;
                if (!$zip->addFile($tempFilePath, $filename)) {
                    session()->flash('error', "Failed to add $filename to ZIP");
                    return;
                }
            } else {
                session()->flash('error', "Failed to create temporary file for $filename");
                return;
            }


            $textLog .= " {$filename} |";
        }
        $zip->close();

        foreach ($tempFiles as $file) {
            if (file_exists($file)) {
                unlink($file);
            }
        }

        if (file_exists($zipFilePath)) {
            $textLog = rtrim($textLog, '|') . " ]";
            $logPath = storage_path("logs/patchGetFile_{$dateExport}.txt");
            file_put_contents($logPath, $textLog, FILE_APPEND);

            return response()->download($zipFilePath)->deleteFileAfterSend(true);
        } else {
            session()->flash('error', 'Zip file not found.');
        }
    }

    public function loadHistoryPatch()
    {
        $this->tab = 'historyPatch';
    }
    public function loadHistoryPatchData()
    {
        $this->historyPatchList = DB::table('conf_server_pendding as cp')
            ->join('conf_smartupdate as cs', 'cp.PatchID', '=', 'cs.PID')
            ->select(
                'cp.TaskDate',
                'cp.TaskStatus',
                'cp.TaskRunner',
                'cp.TaskFinish',
                'cs.PID',
                'cs.PATCHNAME',
                'cs.PAPPROVEDATE',
                'cs.PDESC',
                DB::raw("CASE WHEN cp.TaskStatus = 999 THEN 'Success' 
                WHEN cp.TaskStatus = 0 THEN 'Waiting Receive' 
                WHEN cp.TaskStatus = 1 THEN 'See Patch' 
                WHEN cp.TaskStatus = 2 THEN 'Error Recieved' 
                
                ELSE cp.TaskStatus END as TaskStatusLabel")
            )
            ->where('cp.ServerID', $this->licenseId)
            ->orderBy($this->sortHistoryField, $this->sortHistoryDirection)
            ->paginate($this->perPage);
             
    }
    public function sortHistoryBy($field)
    {
        if ($this->sortHistoryField === $field) {
            $this->sortHistoryDirection = $this->sortHistoryDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortHistoryField = $field;
            $this->sortHistoryDirection = 'asc';
        }
    }

    public function setMessage($message)
    {
        $this->messages[] = $message;
    }
    public function render()
    {
        $this->loadHistoryPatchData();

        return view('livewire.pages.server-license.server-license-edit', [
            'historyPatchList' => $this->historyPatchList,
        ]);
    }
}
