<?php
/**
 * Class LSC_Roles
 * Manages custom WordPress roles and capabilities.
 */
class LSC_Roles {

    public function __construct() {
        // Redirect chatters away from wp-admin (but allow AJAX).
        add_action( 'admin_init', [ $this, 'restrict_chatter_admin_access' ] );
    }

    /**
     * Add the "chatter" role on plugin activation.
     */
    public static function add_roles() {
        add_role(
            'chatter',
            __( 'Chatter', 'live-support-chat' ),
            [
                'read'            => true,
                'lsc_view_chats'  => true,
                'lsc_reply_chats' => true,
            ]
        );

        // Grant all LSC capabilities to administrators.
        $admin = get_role( 'administrator' );
        if ( $admin ) {
            $admin->add_cap( 'lsc_manage_chat' );
            $admin->add_cap( 'lsc_view_chats' );
            $admin->add_cap( 'lsc_reply_chats' );
            $admin->add_cap( 'lsc_manage_users' );
        }
    }

    /**
     * Prevent chatter users from loading any real wp-admin page.
     * AJAX requests (admin-ajax.php) are always allowed.
     */
    public function restrict_chatter_admin_access() {
        // Allow all AJAX calls.
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
            return;
        }

        if ( ! is_user_logged_in() ) {
            return;
        }

        $user = wp_get_current_user();

        // Only restrict the "chatter" role – admins can access everything.
        if ( ! in_array( 'chatter', (array) $user->roles, true ) ) {
            return;
        }

        $dashboard_page = (int) get_option( 'lsc_chatter_dashboard_page', 0 );
        $redirect_url   = $dashboard_page
            ? get_permalink( $dashboard_page )
            : home_url( '/' );

        wp_safe_redirect( $redirect_url );
        exit;
    }
}
