<?php

namespace App\Livewire;

use App\Models\User;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;

class UserPhotoUpload extends Component
{
    use WithFileUploads;

    public $photo;
    public $existingPhoto;
    public $tempPhoto;
    public $userId;

    protected $listeners = ['photoUpdated' => 'refreshPhoto'];

    public function mount($existingPhoto = null, $userId = null)
    {
        $this->existingPhoto = $existingPhoto;
        $this->userId = $userId;
    }

    public function uploadPhoto()
    {
        $this->validate([
            'photo' => 'image|max:2048|mimes:jpg,png,jpeg,gif',
        ]);

        $this->tempPhoto = $this->photo->temporaryUrl();
    }

    public function updatedPhoto()
    {
        $this->validate([
            'photo' => 'image|max:2048|mimes:jpg,png,jpeg,gif',
        ]);

        $this->tempPhoto = $this->photo->temporaryUrl();

        // Emitir evento con la foto temporal
        $this->emit('photoUploaded', $this->photo->getRealPath());
    }

    public function removePhoto()
    {
        $this->reset('photo', 'tempPhoto');
    }

    public function deletePhoto()
    {
        if ($this->existingPhoto) {
            Storage::delete('public/photos/' . $this->existingPhoto);
            
            if ($this->userId) {
                $user = User::find($this->userId);
                $user->update(['profile_photo_path' => null]);
            }
            
            $this->existingPhoto = null;
            $this->emit('photoDeleted');
        }
    }

    public function refreshPhoto()
    {
        $this->existingPhoto = User::find($this->userId)->profile_photo_path;
    }

    public function render()
    {
        return view('livewire.user-photo-upload', [
            //'photo' => $this->photo,
            'tempPhoto' => $this->tempPhoto,
            'existingPhoto' => $this->existingPhoto,
        ]);
    }
}
