<?php

namespace Wpcafe_Multivendor\Core\Hooks;

defined( "ABSPATH" ) || exit;

use WpCafe\Traits\Wpc_Singleton;

/**
 * Discount Hooks Handler
 *
 * Handles all discount-related vendor permissions and filtering for wpcafe-pro controllers
 * using filter hooks to maintain clean separation between plugins.
 */
class Discount_Hooks {

    use Wpc_Singleton;

    /**
     * Initialize all discount filters
     */
    public function init() {
        add_filter( 'wpcafe_pro_discount_create_permission', [ $this, 'can_create_discount' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_read_permission', [ $this, 'can_read_discounts' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_query_args', [ $this, 'filter_discount_query' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_item_permission', [ $this, 'can_access_discount_item' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_update_permission', [ $this, 'can_update_discount' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_delete_permission', [ $this, 'can_delete_discount' ], 10, 2 );
        add_filter( 'wpcafe_pro_discount_bulk_delete_check', [ $this, 'can_bulk_delete_discounts' ], 10, 3 );
        add_filter( 'wpcafe_pro_discount_prepare_data', [ $this, 'prepare_discount_data' ], 10, 2 );
        add_filter( 'wpcafe_pro_applicable_discount_rules', [ $this, 'filter_applicable_discount_rules' ], 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 discount query args for vendors
     *
     * @param array $args Query arguments
     * @param \WP_REST_Request $request Request object
     * @return array
     */
    public function filter_discount_query($args, $request) {
        if ($this->is_vendor_only()) {
            $args['author'] = get_current_user_id();
        }
        return $args;
    }

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

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

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

        if (!wpc_user_is_dokan_vendor()) {
            return false;
        }

        // Check if Discount_Model class exists
        if (!class_exists('\WpCafePro\Models\Discount_Model')) {
            return false;
        }

        $id = intval($request['id']);
        $discount = \WpCafePro\Models\Discount_Model::find($id);

        if (!$discount) {
            return false;
        }

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

    /**
     * Check if user can update discount
     *
     * @param bool $default_permission Default permission
     * @param \WP_REST_Request $request Request object
     * @return bool
     */
    public function can_update_discount($default_permission, $request) {
        return $this->can_access_discount_item($default_permission, $request);
    }

    /**
     * Check if user can delete discount
     *
     * @param bool $default_permission Default permission
     * @param \WP_REST_Request $request Request object
     * @return bool
     */
    public function can_delete_discount($default_permission, $request) {
        return $this->can_access_discount_item($default_permission, $request);
    }

    /**
     * Check if user can bulk delete discounts
     *
     * @param bool $default_permission Default permission
     * @param array $ids Array of discount IDs
     * @param \WP_REST_Request $request Request object
     * @return bool
     */
    public function can_bulk_delete_discounts($default_permission, $ids, $request) {
        if ($this->is_admin()) {
            return true;
        }

        if (!wpc_user_is_dokan_vendor()) {
            return false;
        }

        // Check if Discount_Model class exists
        if (!class_exists('\WpCafePro\Models\Discount_Model')) {
            return false;
        }

        $current_user_id = get_current_user_id();

        foreach ($ids as $id) {
            $discount = \WpCafePro\Models\Discount_Model::find($id);
            if ($discount && (int) $discount->post_author !== $current_user_id) {
                return false; // Found a discount not owned by vendor
            }
        }

        return true;
    }

    /**
     * Prepare discount data for database storage
     *
     * @param array $data Prepared data
     * @param \WP_REST_Request $request Request object
     * @return array
     */
    public function prepare_discount_data($data, $request) {
        if ($this->is_vendor_only()) {
            $data['post_author'] = get_current_user_id();
        }
        return $data;
    }

    /**
     * Filter applicable discount rules to ensure vendor discounts only apply to vendor's own products
     *
     * @param array $discount_rules Array of discount rule arrays
     * @param int $product_id Product ID being checked
     * @return array Filtered discount rules (vendor rules if available, otherwise admin rules)
     */
    public function filter_applicable_discount_rules($discount_rules, $product_id) {
        if ( empty( $discount_rules ) || ! is_array( $discount_rules ) ) {
            return $discount_rules;
        }

        if ( ! $product_id ) {
            return $discount_rules;
        }

        $product_post = get_post( $product_id );
        if ( ! $product_post ) {
            return $discount_rules;
        }

        $product_author_id = (int) $product_post->post_author;
        $vendor_rules = [];
        $admin_rules = [];
        $other_rules = [];

        foreach ( $discount_rules as $rule_id => $rule ) {
            if ( ! is_array( $rule ) || ! isset( $rule['post_author'] ) ) {
                $other_rules[ $rule_id ] = $rule;
                continue;
            }

            $discount_author_id = (int) $rule['post_author'];

            $is_admin_discount = user_can( $discount_author_id, 'manage_options' );

            if ( $is_admin_discount ) {
                $admin_rules[ $rule_id ] = $rule;
            } elseif ( $discount_author_id === $product_author_id ) {
                $vendor_rules[ $rule_id ] = $rule;
            }
        }

        if ( ! empty( $vendor_rules ) ) {
            return array_merge( $vendor_rules, $other_rules );
        }

        return array_merge( $admin_rules, $other_rules );
    }
}
