<?php

namespace App\Http\Livewire\Pages\Parameter;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\ConfParameter;
use App\Models\TabParameterInfo;
use App\Models\TabSpnpage;
use App\Models\TabParameterImg;
use App\Models\TabUser;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

class ParameterEdit extends Component
{
    use WithFileUploads;

    public $parameterId;
    public $name, $value, $description, $active, $detail, $pageCode = [];
    public $searchByPage = [];
    public $images = [];
    public $newImage;
    public $imgdetail, $category = '1';

    protected $rules = [
        'name' => 'required|string|max:30',
        'value' => 'required|string|max:50',
        'description' => 'required|string|max:100',
        'active' => 'required',
        'detail' => 'required',
        'pageCode' => 'required|array',
        'newImage' => 'nullable|image|max:1024',
        'imgdetail' => 'nullable|string|max:255',
        'category' => 'nullable|string|max:100',
    ];

    public function mount($editPid)
    {
        $parameter = ConfParameter::where('PID', $editPid)->firstOrFail();
        $this->parameterId = $parameter->PID;
        $this->name = $parameter->name;
        $this->value = $parameter->value;
        $this->description = $parameter->description;
        $this->active = $parameter->active;

        $parameterInfo = TabParameterInfo::where('parameterName', $parameter->name)->first();
        if ($parameterInfo) {
            $this->detail = $parameterInfo->detail;
            $this->pageCode = explode(',', $parameterInfo->pageCode);
        } else {
            $this->detail = '';
            $this->pageCode = [];
        }
        $this->searchByPage = TabSpnpage::select('pagecode', 'pagename')->get()->toArray();
        $this->images = TabParameterImg::where('parameterCode', $parameter->name)->get();
    }

    public function updateParameter()
    {
        $this->validate();

        ConfParameter::where('PID', $this->parameterId)->update([
            'name' => $this->name,
            'value' => $this->value,
            'description' => $this->description,
            'active' => $this->active,
        ]);

        $pageCodesString = implode(',', $this->pageCode);

        $parameterInfo = TabParameterInfo::where('parameterName', ConfParameter::where('PID', $this->parameterId)->value('name'))->first();
        if ($parameterInfo) {
            $parameterInfo->update([
                'parameterName' => $this->name,
                'pageCode' => $pageCodesString,
                'detail' => $this->detail,
            ]);
        } else {
            TabParameterInfo::create([
                'parameterName' => $this->name,
                'pageCode' => $pageCodesString,
                'detail' => $this->detail,
            ]);
        }

        if ($this->newImage) {
            $this->uploadImage();
        }

        session()->flash('message', 'Parameter updated successfully!');
        $this->emit('loadPage', 'list');
    }

    public function uploadImage()
    {
        $this->validate([
            'newImage' => 'nullable|image|max:1024',
            'category' => 'nullable|string|max:100',
        ]);

        $user = Auth::user();
        if (!$user) {
            session()->flash('error', 'User not authenticated.');
            return;
        }

        if ($this->newImage) {
            $imagePath = base64_encode(file_get_contents($this->newImage->getRealPath()));

            TabParameterImg::create([
                'parameterCode' => $this->name,
                'imgdetail' => $imagePath,
                'category' => $this->category,
                'uploadBy' => $user->USERNAME,
                'uploadTime' => now(),
            ]);

            $this->images = TabParameterImg::where('parameterCode', $this->name)->get();
            $this->reset(['newImage', 'category']); // Reset the input fields
            $this->emit('clearFileInput');
        }
    }

    public function deleteImage($imgid)
    {
        $image = TabParameterImg::where('imgid', $imgid)->first();
        if ($image) {
            $image->delete();
            $this->images = TabParameterImg::where('parameterCode', $this->name)->get();
        }
    }

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