<?php

namespace App\Livewire\Folder;

use Livewire\Component;
use App\Models\Folder;

class CreateModal extends Component
{

    public $project;
    public $parentFolder;
    public $folderName = '';
    public $showModal = false;

        protected $listeners = [
        'openCreateFolderModal' => 'openForRoot',
        'openCreateSubfolderModal' => 'openForParent'
    ];

    public function openForRoot($projectId)
    {
        $this->project = Project::find($projectId);
        $this->parentFolder = null;
        $this->showModal = true;
    }

    public function openForParent($parentFolderId)
    {
        $this->parentFolder = Folder::find($parentFolderId);
        $this->project = $this->parentFolder->project;
        $this->showModal = true;
    }

    public function createFolder()
    {
        $this->validate([
            'folderName' => 'required|max:255|unique:folders,name'
        ]);

        Folder::create([
            'name' => $this->folderName,
            'project_id' => $this->project->id,
            'parent_id' => $this->parentFolder?->id
        ]);

        $this->reset(['folderName', 'showModal']);
        $this->emit('folderCreated');
    }

    public function render()
    {
        return view('livewire.folder.create-modal');
    }
}
