<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use App\Models\Facilities;
use App\Models\FacilitiesPhoto as modelFacilitiesPhoto;
use Illuminate\Support\Facades\File;
class FacilitiesPhoto extends Component
{

    public $facilities;
    public $facilityPhoto;


    protected $listeners = [
        'refreshPhotos' => 'refreshPhoto',
        'deletePhotoAction' => 'deletePhoto'
    ];
    public function mount(Facilities $facilities): void
    {
        $this->facilities = $facilities;
        $this->facilityPhoto = modelFacilitiesPhoto::where('facility_id', $facilities->id)->get();
    }

    public function refreshPhoto()
    {
        $this->facilityPhoto = modelFacilitiesPhoto::where('facility_id',operator:  $this->facilities->id)->get();
    }
    public function confirmDelete($id)
    {
        $this->dispatch('deletePhoto', ['id' => $id]);
    }
    public function deletePhoto($id)
{
    // Find the photo by ID
    $photo = modelFacilitiesPhoto::findOrFail($id);

    // Get the full path of the photo file
    $photoPath = public_path('/images/facility/' . $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.');
}
    public function render()
    {
        return view('livewire.admin.facilities-photo');
    }
}
