<?php

namespace App\Livewire\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Livewire\Component;
use App\Models\Faculty;
use Livewire\WithPagination;
class Faculties extends Component
{
    use WithPagination;
    public $perPage = 5;
    public $search = null;
    public $department = null;

    protected $queryString = [
        'search'=>['except'=>''],
        'department'=>['except'=>'']
    ];
    protected $listeners = [
        'deleteFacultyAction'
    ];

    public function updateSearch(){
        $this->resetPage();
    }
    public function mount()
{
    if (Auth::user()->type === 'admin') {
        $this->department = Auth::user()->department;
    }
}
   public function deleteFaculty($id){
    $this->dispatch('deleteFaculty',['id'=>$id]);
   }

   public function deleteFacultyAction($id){
    $faculty = Faculty::findOrFail($id);
    $path = "images/faculty/";
    $old_faculty_image = $faculty->profile_picture;
    if($old_faculty_image != "" && File::exists(public_path($path.$old_faculty_image))){
        File::delete(public_path($path.$old_faculty_image));
    }
    $delete = $faculty->delete();

    if($delete){
        $this->dispatch('showToastr', type: 'success', message: 'Faculty has been deleted successfully.');
    }else{
        $this->dispatch('showToastr', type: 'error', message: 'Something went wrong.');
    }
   }
    public function render()
    {
        $faculties = Faculty::latest()->search(trim($this->search))->when($this->department, function($query){
            $query->where('department', $this->department);
        })->paginate($this->perPage);
        return view('livewire.admin.faculties', compact('faculties'));
    }
}
