<?php

namespace App\Http\Livewire\Pages\FormatFileMaster;

use App\Models\ConfFormatFile;
use Livewire\Component;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileEdit extends Component
{
    public $editId;
    public $file;
    public $name;
    protected $rules = [
        'role.name' => 'required',
    ];
    public function mount($editId)
    {
        $this->editId = $editId;
        $fileFormat = ConfFormatFile::findOrFail($this->editId);
        $this->name = $fileFormat->name;
    }
    public function render()
    {
      
        return view('livewire.pages.format-file-master.file-edit');
    }

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

        $filePath = null;
        if ($this->file) {
            if ($this->isEditMode && $this->editId) {
                $oldFile = ConfFormatFile::find($this->editId)->file;
                if ($oldFile && Storage::disk('public')->exists($oldFile)) {
                    Storage::disk('public')->delete($oldFile);
                }
            }

            $filePath = $this->file->store('runtime/format', 'public');
        }

        $date = date("Ymd");
        $timestamp = date("His");

        if ($this->isEditMode && $this->editId) {
            $fileFormat = ConfFormatFile::findOrFail($this->editId);
        } else {
            $fileFormat = new ConfFormatFile;
        }

        $fileFormat->name = $this->name;

        if ($filePath) {
            $fileFormat->file = $filePath;
        }

        $fileFormat->date = $date;
        $fileFormat->timestamp = $timestamp;
        $fileFormat->save();

        $this->reset(['name', 'file']);
       
        return redirect()->route('format-file-master.index')->with('message', 'Format File saved successfully.');
    }
    public function goBack()
    {
        $this->emit('showRoleList', '');
    }
}
