<?php
/**
 * Capability Fix for Unregistered Post Types
 *
 * Fixes WordPress warnings when checking capabilities for comments/posts
 * associated with post types that are not currently registered.
 *
 * @package FleekDash\Core
 */

namespace FleekDash\Core;

class CapabilityFix
{
    /**
     * Initialize the capability fix
     */
    public static function init()
    {
        // Fix map_meta_cap for unregistered post types
        \add_filter('map_meta_cap', [self::class, 'fix_unregistered_post_type_capabilities'], 10, 4);
    }

    /**
     * Fix capabilities check for unregistered post types
     *
     * When WordPress tries to check capabilities for posts/comments associated
     * with unregistered post types (like 'group' from deactivated plugins),
     * this filter prevents the warning by handling the case gracefully.
     *
     * @param array  $caps    Required capabilities
     * @param string $cap     Capability being checked
     * @param int    $user_id User ID
     * @param array  $args    Additional arguments (may contain post ID)
     * @return array Required capabilities
     */
    public static function fix_unregistered_post_type_capabilities($caps, $cap, $user_id, $args)
    {
        // Only handle edit_post and edit_comment capabilities
        if (!in_array($cap, ['edit_post', 'edit_comment'], true)) {
            return $caps;
        }

        // Get post ID from args
        $post_id = isset($args[0]) ? (int) $args[0] : 0;
        if ($post_id <= 0) {
            return $caps;
        }

        // For edit_comment, get the post ID from the comment
        if ($cap === 'edit_comment') {
            $comment = \get_comment($post_id);
            if (!$comment || !$comment->comment_post_ID) {
                return $caps;
            }
            $post_id = (int) $comment->comment_post_ID;
        }

        // Get post type
        $post_type = \get_post_type($post_id);
        if (!$post_type) {
            // Post doesn't exist - return 'do_not_allow' to prevent warnings
            return ['do_not_allow'];
        }

        // Check if post type is registered
        if (!\post_type_exists($post_type)) {
            // Post type is not registered - handle gracefully
            // For unregistered post types, check if user has edit_posts capability
            // This prevents the warning while still maintaining security
            $user = \get_userdata($user_id);
            if ($user && $user->has_cap('edit_posts')) {
                // User can edit posts in general, allow for unregistered types
                return [];
            }
            // User cannot edit posts, deny access
            return ['do_not_allow'];
        }

        // Post type is registered - let WordPress handle it normally
        return $caps;
    }
}
