<?php

namespace App\Livewire\Admin;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Livewire\Component;
use App\Models\User;
use Livewire\WithPagination;

class Author extends Component
{
    use WithPagination;
    public $perPage = 5;
    public $search = null;
    public $department = null;
    protected $queryString = [
        'search' => ['except' => ''],
        'department' => ['except' => '']
    ];
    protected $listeners = [
        'deleteAuthorAction'
    ];
    public function updateSearch()
    {
        $this->resetPage();
    }
    public function mount()
    {
        if (Auth::user()->type === 'admin') {
            $this->department = Auth::user()->department;
        }
    }
    public function deleteAuthor($id)
    {
        $this->dispatch('deleteAuthor', ['id' => $id]);
    }
    public function deleteFacultyAction($id)
    {
        $authorUser = User::findOrFail($id);
        $path = "images/authors/";
        $old_faculty_image = $authorUser->picture;
        if ($old_faculty_image != "" && File::exists(public_path($path . $old_faculty_image))) {
            File::delete(public_path($path . $old_faculty_image));
        }
        $delete = $authorUser->delete();

        if ($delete) {
            $this->dispatch('showToastr', type: 'success', message: 'Author has been deleted successfully.');
        } else {
            $this->dispatch('showToastr', type: 'error', message: 'Something went wrong.');
        }
    }

    public function render()
    {
        $data = [
            'author_active' => User::latest()
                ->search(trim($this->search))
                ->where('type', 'author')
                ->where('status', 'active')
                ->when($this->department, function ($query) {
                    $query->where('department', $this->department);
                })
                ->paginate($this->perPage),

            'author_not' => User::latest()->search(trim($this->search))->when($this->department, function ($query) {
                $query->where('department', $this->department)->where('type', 'author')->whereNot('status', 'active');
            })->paginate($this->perPage)
        ];


        return view('livewire.admin.author', $data);
    }
}
