<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    use HasFactory;

    protected $table = 'staff';

    protected $fillable = [
        'user_id',
        'device_id',
        'staff_user_id',
        'staff_name',
        'staff_email',
        'staff_phone',
        'role',
        'permissions',
        'status',
        'last_login_at',
    ];

    protected $casts = [
        'permissions' => 'array',
        'last_login_at' => 'datetime',
    ];

    // Relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function staffUser()
    {
        return $this->belongsTo(User::class, 'staff_user_id');
    }

    public function device()
    {
        return $this->belongsTo(Device::class);
    }

    public function assignedTickets()
    {
        return $this->hasMany(SupportTicket::class, 'assigned_staff_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeForDevice($query, $deviceId)
    {
        return $query->where('device_id', $deviceId);
    }

    public function scopeByRole($query, $role)
    {
        return $query->where('role', $role);
    }

    // Methods
    public function hasPermission($permission)
    {
        if ($this->role === 'manager') {
            return true; // Managers have all permissions
        }

        if (!$this->permissions) {
            return false;
        }

        return in_array($permission, $this->permissions);
    }

    public function isActive()
    {
        return $this->status === 'active';
    }

    public function canAccessTickets()
    {
        return $this->isActive() && $this->hasPermission('view_tickets');
    }

    public function canReplyTickets()
    {
        return $this->isActive() && $this->hasPermission('reply_tickets');
    }

    public function canManageContacts()
    {
        return $this->isActive() && $this->hasPermission('manage_contacts');
    }

    public function updateLastLogin()
    {
        $this->last_login_at = now();
        $this->save();
    }
}
