<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use App\Models\Album;
use App\Models\Photo;
use Illuminate\Support\Facades\File;
class AlbumPhotos extends Component
{
    public $album;
    public $photos;

    protected $listeners = [
        'refreshPhotos' => 'refreshPhoto',
        'deletePhotoAction' => 'deletePhoto'
    ];

    public function mount(Album $album)
    {
        $this->album = $album;
        $this->photos = Photo::where('album_id', $album->id)->get();
    }
    public function render()
    {
        return view('livewire.admin.album-photos');
    }
    public function refreshPhoto()
    {
        $this->photos = Photo::where('album_id', $this->album->id)->get();
    }
     public function confirmDelete($id)
    {
        $this->dispatch('deletePhoto', ['id' => $id]);
    }
    public function deletePhoto($id)
{
    // Find the photo by ID
    $photo = Photo::findOrFail($id);

    // Get the full path of the photo file
    $photoPath = public_path('/images/albums/' . $photo->photo_path);

    // If the file exists, delete it
    if (File::exists($photoPath)) {
        File::delete($photoPath);
    }

    // Delete the photo record from the database
    $photo->delete();

    // Dispatch a success message to the frontend
    $this->dispatch('showToastr', type: 'success', message: 'Photo deleted successfully.');
}

}
