<?php

namespace App\Http\Livewire\Pages\Patch;

use Livewire\Component;
use App\Models\ConfSmartUpdate;
use App\Models\TabPatchFile;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class PatchEdit extends Component
{
    public $patchId;

    public $searchProject = '';
    public $selectedBranch , $selectedPatch;
    public $selectedProject;
    public $projects = [];
    public $branches = [];
    public $fileChanges = [];
    public $startCommit;
    public $endCommit;
    public $PATCHNAME;
    public $PDATE;
    public $PHP_VERSION;
    public $PLEVEL;
    public $PCODE;
    public $MAJOR_VERSION;
    public $PDESC;
    public $Remark;
    public $POWNER;
    public $PAPPROVEDATE;
    public $PTYPE;
    public $PATCHCODE;
    public $UNINSTALL;
    public $PATCHCODE_SERVER;
    public $filePathChanges = [];
    protected $listeners = [ 'gotoModal', 'reloadComponent'];
    public function mount($editPid)
    {
        $this->patchId = $editPid;
        $this->loadPatchData();
    }
    public function reloadComponent($id)
    {
        $this->patchId = $id;
        $this->loadPatchData();
        $this->render();
    }
    public function loadPatchData()
    {
        $patch = ConfSmartUpdate::findOrFail($this->patchId);
        $this->PATCHNAME = $patch->PATCHNAME;
        $this->PDATE = $patch->PDATE;
        $this->PHP_VERSION = $patch->PHP_VERSION;
        $this->PLEVEL = $patch->PLEVEL;
        $this->PCODE = $patch->PCODE;
        $this->MAJOR_VERSION = $patch->MAJOR_VERSION;
        $this->PDESC = $patch->PDESC;
        $this->Remark = $patch->Remark;
        $this->POWNER = $patch->POWNER;
        $this->PAPPROVEDATE = $patch->PAPPROVEDATE;
        $this->PTYPE = $patch->PTYPE;
        $this->PATCHCODE = $patch->PATCHCODE;
        $this->UNINSTALL = $patch->UNINSTALL;
        $this->PATCHCODE_SERVER = $patch->PATCHCODE_SERVER;

        $filePath = TabPatchFile::where("ptid", $this->patchId)->get()->toArray();
        $filePath = $this->buildTree($filePath);
       
        $this->fileChanges = $filePath ;
    }

    public function save()
    {
        
        $this->validate([
            'PATCHNAME' => 'required|string|max:255',
            'PDATE' => 'required|date',
            'PHP_VERSION' => 'required|integer',
            'PLEVEL' => 'required|string|max:255',
            'PCODE' => 'required|string|max:255',
            'MAJOR_VERSION' => 'required|string|max:255',
            'PDESC' => 'required|string|max:255',
            'Remark' => 'required|string|max:255',
            'POWNER' => 'required|string|max:255',
            'PAPPROVEDATE' => 'required|date',
            'PTYPE' => 'required|string|max:255',
            'PATCHCODE' => 'required|string',
            'UNINSTALL' => 'required|string|max:255',
            'PATCHCODE_SERVER' => 'required|string',
        ]);

        $confSmartUpdate = ConfSmartUpdate::findOrFail($this->patchId);
        $confSmartUpdate->PATCHNAME = $this->PATCHNAME;
        $confSmartUpdate->PDATE = $this->PDATE;
        $confSmartUpdate->PHP_VERSION = $this->PHP_VERSION;
        $confSmartUpdate->PLEVEL = $this->PLEVEL;
        $confSmartUpdate->PCODE = $this->PCODE;
        $confSmartUpdate->MAJOR_VERSION = $this->MAJOR_VERSION;
        $confSmartUpdate->PDESC = $this->PDESC;
        $confSmartUpdate->Remark = $this->Remark;
        $confSmartUpdate->POWNER = $this->POWNER;
        $confSmartUpdate->PAPPROVEDATE = $this->PAPPROVEDATE;
        $confSmartUpdate->PTYPE = $this->PTYPE;
        $confSmartUpdate->PATCHCODE = $this->PATCHCODE;
        $confSmartUpdate->UNINSTALL = $this->UNINSTALL;
        $confSmartUpdate->PATCHCODE_SERVER = $this->PATCHCODE_SERVER;
        $confSmartUpdate->save();
 
        if (count($this->filePathChanges) > 0) {
            foreach ($this->filePathChanges as $file) {
                
                if(strpos($file, 'SPN/') !== false ) {
                    $filePath =  str_replace("SPN/", "../SPN/", $file);
                }else if(strpos($file, 'spn/' ) !== false) {
                    $filePath =  str_replace("spn/", "../spn/", $file);
                }else{
                    $filePath = str_replace("IE5DEV.shippingnet", ".", $file);
                }

             
                $filedata = $this->getFileContentFromGit($filePath, $this->endCommit);

                $filepath = new TabPatchFile;
                $filepath->ptid = $confSmartUpdate->PID;
                $filepath->file_name = $filePath;
                $filepath->file_data = base64_encode($filedata);
                $filepath->save();
            }
        }

        session()->flash('message', 'Patch details and file changes updated successfully.');
    }

    private function getFileContentFromGit($filePath, $commit)
    {
        $token = env('GITLAB_API_TOKEN');

        $client = new Client([
            'base_uri' => 'https://idemo.netbay.co.th/gitlab/api/v4/',
            'headers' => [
                'Authorization' => "Bearer $token",
                'Accept' => 'application/json',
            ],
            'verify' => false,
        ]);

        try {
            $response = $client->get("projects/$this->selectedProject/repository/files/" . urlencode($filePath) . "/raw", [
                'query' => ['ref' => $commit]
            ]);
            $statusCode = $response->getStatusCode();
            $content = $response->getBody()->getContents();

            if ($statusCode == 200) {
                return $content;
            } else {
                throw new \Exception("Failed to fetch file. Status code: $statusCode");
            }
        } catch (RequestException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    private function buildTree($files)
    {
        $tree = [];
        foreach ($files as $file) {
          
            if(strpos($file['file_name'],  "../SPN/" ) !== false ) {
                $filePath =  str_replace("../SPN/", "SPN/",  $file['file_name']);
            }else if(strpos($file['file_name'],  "../spn/" ) !== false) {
                $filePath =  str_replace("../spn/", "spn/",  $file['file_name']);
            }else{
                $filePath = "IE5DEV.shippingnet" . substr($file['file_name'], 1);
            }
         
            $pathParts = explode('/', $filePath);
            $current = &$tree;
    
            foreach ($pathParts as $part) {
                if (!isset($current[$part])) {
                    $current[$part] = [];
                }
                $current = &$current[$part];
            }
    
            $current['id'] = $file['fid'];
        }

        return $tree;
    }
    public function loadPage($page) {
        $this->emit('menuChanged', $page);
    }

    


    public function render()
    {
        return view('livewire.pages.patch.patch-edit');
    }


}
