<?php
namespace App\Livewire\Admin;

use Livewire\Component;
use App\Models\CarouselImage as ModelCarouselImage;
use Illuminate\Support\Facades\File;

class CarouselImage extends Component
{
    public $images;

    protected $listeners = [
        'refreshCarousel' => 'refreshImages',
        'deleteCarouselImageAction' => 'deleteImage'
    ];

    public function mount()
    {
        $this->refreshImages();
    }

    public function render()
    {
        return view('livewire.admin.carousel-image');
    }

    public function refreshImages()
    {
        $this->images = ModelCarouselImage::latest()->get();
    }

    public function confirmDelete($id)
    {
        $this->dispatch('confirmDeleteCarouselImage', ['id' => $id]);
    }

    public function deleteImage($id)
    {
        $image = ModelCarouselImage::findOrFail($id);
        $path = public_path('/images/carousel/' . $image->image_path);

        if (File::exists($path)) {
            File::delete($path);
        }

        $image->delete();
        $this->dispatch('showToastr', type: 'success', message: 'Image deleted.');
        $this->refreshImages();
    }
}

