<?php
/**
 * Hide the toolbar for subscribers
 * and disable the profile toolbar checkbox.
 */
if (!defined('WPINC')) die;

if (!function_exists('custausu_subscriber_hide_frontend_toolbar')) {
  function custausu_subscriber_hide_frontend_toolbar(): void {
    if (wp_doing_ajax() || (defined('REST_REQUEST') && REST_REQUEST)) {
      return;
    }

    if (current_user_can('subscriber')) {
      show_admin_bar(false);
    }
  }
}

if (!function_exists('custausu_subscriber_profile_restrictions')) {
  function custausu_subscriber_profile_restrictions(): void {
    if (wp_doing_ajax() || (defined('REST_REQUEST') && REST_REQUEST)) {
      return;
    }

    if (current_user_can('subscriber')) {
      add_filter('user_can_richedit', '__return_false');
      add_filter('pre_option_show_admin_bar_front', '__return_false');
    }
  }
}

if (!function_exists('custausu_subscriber_enqueue_profile_style')) {
  function custausu_subscriber_enqueue_profile_style(string $hook): void {
    if ($hook !== 'profile.php' || !current_user_can('subscriber')) {
      return;
    }

    $style_path = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-subscriber-profile.css';

    wp_enqueue_style(
      'custausu-subscriber-profile',
      CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-subscriber-profile.css',
      [],
      is_readable($style_path) ? (string) filemtime($style_path) : CUSTAUSU_VERSION
    );
  }
}

add_action('after_setup_theme', 'custausu_subscriber_hide_frontend_toolbar');
add_action('admin_init', 'custausu_subscriber_profile_restrictions');
add_action('admin_enqueue_scripts', 'custausu_subscriber_enqueue_profile_style');
