<?php

namespace App\Livewire;

use App\Models\Document;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Project;
use App\Models\Folder;

class FileUpload extends Component
{

    use WithFileUploads;

    public Project $project;
    public Folder|null $folder;
    public $files = [];
    public $previews = [];
    public $maxSize = 50; // MB
    public $folderId;

    protected $listeners = ['folderChanged' => 'updateFolder'];

    public function updateFolder($folderId)
    {
        $this->folder = Folder::find($folderId);
    }

    public function updatedFiles()
    {
        $this->validate([
            'files.*' => "max:{$this->maxSize}1024|mimes:pdf,docx,xlsx,jpg,png,svg",
            'folderId' => 'required|exists:folders,id'
        ]);

        $this->previews = [];
        foreach ($this->files as $file) {
            $this->previews[] = [
                'name' => $file->getClientOriginalName(),
                'type' => $file->getMimeType(),
                'size' => $file->getSize(),
                'preview' => str_starts_with($file->getMimeType(), 'image/') 
                    ? $file->temporaryUrl() 
                    : null
            ];

            Document::create([
                'name' => $file->getClientOriginalName(),
                'file_path' => $file->store("projects/{$this->folderId}"),
                'folder_id' => $this->folderId
            ]);
        }
    }

    public function save()
    {
        $this->validate([
            'files.*' => "required|max:{$this->maxSize}1024|mimes:pdf,docx,xlsx,jpg,png,svg"
        ]);

        foreach ($this->files as $file) {
            $path = $file->store("projects/{$this->project->id}/documents", 'public');
            
            $this->project->documents()->create([
                'name' => $file->getClientOriginalName(),
                'file_path' => $path,
                'folder_id' => $this->folder?->id,
                'size' => $file->getSize(),
                'type' => $file->getMimeType()
            ]);
        }

        $this->reset(['files', 'previews']);
        $this->emit('documentsUpdated');
    }
    
    public function render()
    {
        return view('livewire.file-upload');
    }
}
