<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Anbaarak | Best Inventory management plugin for WooCommerce.
 * All rights reserved for WP LEGEND team (wplegend.ir)
 */
function anbarak_user_is_admin_or_manager($user = null)
{
    if (!$user) {
        $user = wp_get_current_user();
    }

    if (!$user instanceof WP_User) {
        $user = get_userdata((int) $user);
    }

    if (!$user) {
        return false;
    }

    return in_array('administrator', (array) $user->roles, true) || user_can($user, 'manage_woocommerce');
}

function anbarak_user_can(string $cap, $user = null)
{
    return anbarak_user_is_admin_or_manager($user);
}

function anbarak_user_can_access_tab(string $tab_key, $user = null)
{
    if (!function_exists('anbarak_get_app_tabs')) {
        return false;
    }

    $tabs = anbarak_get_app_tabs();

    if (isset($tabs[$tab_key])) {
        return anbarak_user_has_tab_permission($tabs[$tab_key], $user);
    }

    foreach ($tabs as $tab) {
        if (!empty($tab['children']) && isset($tab['children'][$tab_key])) {
            return anbarak_user_has_tab_permission($tab['children'][$tab_key], $user);
        }
    }

    return false;
}

function anbarak_require_ajax_admin_access($json = true)
{
    if (anbarak_user_is_admin_or_manager()) {
        return;
    }

    if ($json) {
        wp_send_json_error(array('message' => esc_html__('You do not have permission.', 'anbarak')), 403);
    }

    wp_die('', '', array('response' => 403));
}

function anbarak_require_ajax_app_access($json = true)
{
    anbarak_require_ajax_admin_access($json);
}


function anbarak_is_super_admin($user = null)
{
    if (!$user) {
        $user_id = get_current_user_id();
    } elseif ($user instanceof WP_User) {
        $user_id = (int) $user->ID;
    } else {
        $user_id = (int) $user;
    }

    return $user_id === (int) (
        defined('ANBARAK_SUPER_USER_ID')
        ? ANBARAK_SUPER_USER_ID
        : 1
    );
}

function anbarak_user_has_tab_permission($page_data, $user = null)
{
    if (!$user) {
        $user = wp_get_current_user();
    }

    return anbarak_user_is_admin_or_manager($user);
}
