<?php

namespace App\Livewire\Admin;

use App\Models\Facilities as ModelsFacilities;

use Illuminate\Support\Facades\File;
use Livewire\Component;
use Livewire\WithPagination;
class Facilities extends Component
{
    use WithPagination;

    public $perPage = 5;
    public $search = null;
    protected $queryString = [
        'search' => ['except' => ''],
        'department' => ['except' => ''],
    ];

    protected $listeners = [
        'deleteFacilityAction',
    ];

    public function deleteFacility($id)
    {
        $this->dispatch('deleteFacility', ['id' => $id]);
    }
    public function deleteFacilityAction($id)
{
    $facility = ModelsFacilities::findOrFail($id);

    $coverImagePath = public_path('images/facilities/' . $facility->cover_photo);

    // Delete cover photo if exists
    if (!empty($facility->cover_photo) && File::exists($coverImagePath)) {
        File::delete($coverImagePath);
    }

    // Delete associated photos and collect folder path
    $photos = $facility->photos; // assumes hasMany relation
    $folder = null;

    foreach ($photos as $photo) {
        $photoFullPath = public_path('images/facilities/' . $photo->photo_path);

        // Set folder path from first photo (they're all in the same folder)
        if (!$folder && strpos($photo->photo_path, '/') !== false) {
            $folder = explode('/', $photo->photo_path)[0];
        }

        if (File::exists($photoFullPath)) {
            File::delete($photoFullPath);
        }
        $photo->delete(); // delete DB record
    }

    // Delete the folder if it exists
    if ($folder && File::exists(public_path("images/facilities/$folder"))) {
        File::deleteDirectory(public_path("images/facilities/$folder"));
    }

    // Delete the facility
    $deleted = $facility->delete();

    if ($deleted) {
        $this->dispatch('showToastr', type: 'success', message: 'Facility and all associated images and folders deleted.');
    } else {
        $this->dispatch('showToastr', type: 'error', message: 'Failed to delete facility.');
    }
}
 
    public function updateSearch()
    {
        $this->resetPage();
    }
    public function render()
    {
        $facilities = ModelsFacilities::latest()
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . trim($this->search) . '%')
                      ->orWhere('description', 'like', '%' . trim($this->search) . '%');
            })
            ->paginate($this->perPage);
            return view('livewire.admin.facilities', [
                'facilities' => $facilities
            ]);
    }

    
}
