<?php

namespace App\Models;

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

class BusinessStaff extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'business_staff';

    protected $fillable = [
        'business_id',
        'user_id',
        'role',
        'team_id',
        'permissions',
        'status',
        'invitation_token',
        'invited_at',
        'joined_at',
    ];

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

    public function business()
    {
        return $this->belongsTo(Business::class);
    }

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

    public function team()
    {
        return $this->belongsTo(Team::class);
    }

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

    public function scopePending($query)
    {
        return $query->where('status', 'pending_invitation');
    }

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

    public function isOwner()
    {
        return $this->role === 'owner';
    }

    public function isManager()
    {
        return $this->role === 'manager';
    }

    public function isStaff()
    {
        return $this->role === 'staff';
    }

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

    public function isPending()
    {
        return $this->status === 'pending_invitation';
    }

    public function hasPermission($permission)
    {
        if ($this->isOwner()) {
            return true; // Owner has all permissions
        }

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

    public function canManageStaff()
    {
        return $this->isOwner() || $this->isManager() || $this->hasPermission('manage_staff');
    }

    public function canManageOffers()
    {
        return $this->isOwner() || $this->isManager() || $this->hasPermission('manage_offers');
    }

    public function canManageVenues()
    {
        return $this->isOwner() || $this->isManager() || $this->hasPermission('manage_venues');
    }

    public function canViewAnalytics()
    {
        return $this->isOwner() || $this->isManager() || $this->hasPermission('view_analytics');
    }

    public function canRedeemOffers()
    {
        return $this->isOwner() || $this->isManager() || $this->isStaff() || $this->hasPermission('redeem_offers');
    }
}
