<?php

namespace App\Livewire;

use App\Models\User;
use App\Traits\HasNotifications;
use Livewire\Component;
use Livewire\WithPagination;

class StaffTable extends Component
{
    use HasNotifications, WithPagination;

    public $search = '';
    public $perPage = 10;
    public $roleFilter = '';
    public $statusFilter = 'active';

    protected $queryString = [
        'search' => ['except' => ''],
        'roleFilter' => ['except' => ''],
        'statusFilter' => ['except' => 'active']
    ];

    public function mount()
    {
        $this->perPage = (int) $this->perPage;
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingRoleFilter()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function deleteStaff($staffId)
    {
        try {
            $staff = User::findOrFail($staffId);
            $staffName = $staff->name;
            
            app(\App\Services\StaffService::class)->deleteStaff($staff);
            
            session()->flash('toast', [
                'type' => 'success',
                'message' => "Staff {$staffName} deleted successfully"
            ]);
            
        } catch (\Exception $e) {
            session()->flash('toast', [
                'type' => 'error',
                'message' => 'Failed to delete staff: ' . $e->getMessage()
            ]);
        }
    }

    public function deactivateStaff($staffId)
    {
        try {
            $staff = User::findOrFail($staffId);
            $newStatus = !$staff->active;
            $staff->update(['active' => $newStatus]);
            
            $status = $newStatus ? 'activated' : 'deactivated';
            session()->flash('toast', [
                'type' => 'success',
                'message' => "Staff {$status} successfully"
            ]);
            
        } catch (\Exception $e) {
            session()->flash('toast', [
                'type' => 'error',
                'message' => 'Failed to update staff status: ' . $e->getMessage()
            ]);
        }
    }

    public function render()
    {
        $staff = User::whereHas('roles')
            ->with(['roles', 'classes'])
            ->where('id', '!=', auth()->id())
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('firstname', 'like', '%' . $this->search . '%')
                      ->orWhere('surname', 'like', '%' . $this->search . '%')
                      ->orWhere('email', 'like', '%' . $this->search . '%')
                      ->orWhere('phone', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->roleFilter, function ($query) {
                $query->whereHas('roles', function ($q) {
                    $q->where('name', $this->roleFilter);
                });
            })
            ->when($this->statusFilter, function ($query) {
                if ($this->statusFilter === 'active') {
                    $query->where('active', true);
                } elseif ($this->statusFilter === 'inactive') {
                    $query->where('active', false);
                }
            })
            ->orderBy('firstname')
            ->paginate((int) $this->perPage);

        $roles = \App\Models\Role::orderBy('display_name')->get();
        return view('livewire.staff-table', compact('staff', 'roles'));
    }
}