<?php

namespace Wpcafe_Multivendor\Core\Hooks;

defined( "ABSPATH" ) || exit;

use WpCafe\Traits\Wpc_Singleton;

/**
 * Handles all product-related vendor permissions and filtering for wpcafe controllers
 * using filter hooks to maintain clean separation between plugins.
 */
class Product_Hooks {

    use Wpc_Singleton;

    /**
     * Initialize all product filters
     */
    public function init() {
        add_filter( 'wpcafe_product_read_permission', [ $this, 'can_read_products' ], 10, 2 );
        add_filter( 'wpcafe_product_query_args', [ $this, 'filter_product_query' ], 10, 2 );
        add_filter( 'wpcafe_product_item_permission', [ $this, 'can_access_product_item' ], 10, 2 );
    }

    /**
     * Check if user is admin
     *
     * @return bool
     */
    private function is_admin() {
        return current_user_can('manage_options');
    }

    /**
     * Check if user is vendor but not admin
     *
     * @return bool
     */
    private function is_vendor_only() {
        return wpc_user_is_dokan_vendor() && !$this->is_admin();
    }

    /**
     * Filter product query args for vendors
     *
     * @param array $args Query arguments
     * @param \WP_REST_Request $request Request object
     * @return array
     */
    public function filter_product_query($args, $request) {
        if ($this->is_vendor_only()) {
            $args['author'] = get_current_user_id();
        }
        return $args;
    }

    /**
     * Check if user can read products
     *
     * @param bool $default_permission Default permission
     * @param \WP_REST_Request $request Request object
     * @return bool
     */
    public function can_read_products($default_permission, $request) {
        return $default_permission || wpc_user_is_dokan_vendor();
    }

    /**
     * Check if user can access specific product item
     *
     * @param bool $default_permission Default permission
     * @param \WP_REST_Request $request Request object
     * @return bool
     */
    public function can_access_product_item($default_permission, $request) {
        if ( $this->is_admin() ) {
            return true;
        }

        if ( ! wpc_user_is_dokan_vendor() ) {
            return $default_permission;
        }

        $id = intval( $request['id'] );
        $product = wc_get_product( $id );

        if ( ! $product ) {
            return false;
        }

        // Get the post object to check author
        $post = get_post( $product->get_id() );

        if ( ! $post ) {
            return false;
        }

        return (int) $post->post_author === get_current_user_id();
    }
}
