<?php
namespace PayCal\Permissions;

defined('ABSPATH') || exit;

class Access {
  public static function can(string $section): bool {
    if ('permissions' === $section) {
      return self::can_manage_permissions();
    }

    if (current_user_can('manage_options')) {
      return true;
    }

    if ('invoices' === $section && (current_user_can('manage_woocommerce') || current_user_can('edit_shop_orders'))) {
      return true;
    }

    if (!array_key_exists($section, PermissionsStore::CAPS)) {
      return false;
    }

    $data = PermissionsStore::get();
    $user_id = get_current_user_id();

    if ($user_id && !empty($data['users'][$user_id][$section])) {
      return true;
    }

    $user = wp_get_current_user();
    if (!$user || empty($user->roles)) {
      return false;
    }

    foreach ((array) $user->roles as $role_key) {
      if (!empty($data['roles'][$role_key][$section])) {
        return true;
      }
    }

    return false;
  }

  public static function any(array $sections): bool {
    foreach ($sections as $section) {
      if (self::can((string) $section)) {
        return true;
      }
    }

    return false;
  }

  public static function enforce(string $section): void {
    if (self::can($section)) {
      return;
    }

    $message = 'אין לך הרשאה לצפות במסך הזה של PayCal.';
    if ('permissions' === $section) {
      $message = 'מסך ההרשאות של PayCal זמין רק למשתמש הבעלים שהוגדר עבורו.';
    }

    wp_die(
      esc_html($message),
      esc_html__('אין הרשאה', 'klamra-paycal-for-aspaclaria'),
      ['response' => 403]
    );
  }

  public static function can_manage_permissions(): bool {
    if (!current_user_can('manage_options')) {
      return false;
    }

    $owner_user_id = PermissionsStore::get_owner_user_id();
    if ($owner_user_id > 0) {
      return get_current_user_id() === $owner_user_id;
    }

    return true;
  }
}
