<?php

namespace App\View\Components;

use Illuminate\View\Component;

class PermissionCheck extends Component
{
    public $permission;
    public $role;
    public $branchCode;

    /**
     * Create a new component instance.
     */
    public function __construct($permission = null, $role = null, $branchCode = null)
    {
        $this->permission = $permission;
        $this->role = $role;
        $this->branchCode = $branchCode ?? auth()->user()?->branch_code;
    }

    /**
     * Determine if the component should be rendered.
     */
    public function shouldRender(): bool
    {
        if (!auth()->check()) {
            return false;
        }

        $user = auth()->user();

        // Check permission if provided
        if ($this->permission) {
            if (is_array($this->permission)) {
                return $user->hasAnyPermission($this->permission, $this->branchCode);
            }
            return $user->hasPermission($this->permission, $this->branchCode);
        }

        // Check role if provided
        if ($this->role) {
            if (is_array($this->role)) {
                return $user->hasAnyRole($this->role, $this->branchCode);
            }
            return $user->hasRole($this->role, $this->branchCode);
        }

        return true;
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render()
    {
        return view('components.permission-check');
    }
}
