
/**
 * Replaces the default "hire service" function to allow freelancers to buy services,
 * but prevents them from buying their own.
 *
 * Add this code using the "Code Snippets" plugin.
 */

// Step 1: Remove the theme's original function to prevent it from running.
add_action('init', 'remove_original_hire_service_action', 99);
function remove_original_hire_service_action() {
    remove_action( 'wpfi_ajax_wp_freeio_ajax_hire_service', array('WP_Freeio_Service', 'process_hire_service') );
}

// Step 2: Add our own custom function in its place.
add_action( 'wpfi_ajax_wp_freeio_ajax_hire_service', 'custom_process_hire_service' );
function custom_process_hire_service() {
    
    // --- Start of function (with our modifications) ---

    if ( !is_user_logged_in() ) {
        $return = array( 'status' => false, 'msg' => esc_html__('You do not have permission to buy this service. Please log in to continue.', 'wp-freeio') );
        wp_send_json($return);
    }

    // MODIFICATION 1: Allow both Employers and Freelancers to buy.
    if ( !WP_Freeio_User::is_employer() && !WP_Freeio_User::is_freelancer() ) {
        $return = array( 'status' => false, 'msg' => esc_html__('You do not have permission to buy this service.', 'wp-freeio') );
        wp_send_json($return);
    }

    $service_id = !empty($_POST['service_id']) ? sanitize_text_field($_POST['service_id']) : '';
    $user_id = get_current_user_id();
    $service_author_id = WP_Freeio_Service::get_author_id($service_id);

    // MODIFICATION 2: Block a user from buying their own service.
    if ( $user_id == $service_author_id ) {
        $return = array( 'status' => false, 'msg' => esc_html__('You cannot purchase your own service.', 'wp-freeio') );
        wp_send_json($return);
    }

    // --- The rest of this function is an exact copy of the theme's original code ---

    $service_package = !empty($_POST['service_package']) ? sanitize_text_field($_POST['service_package']) : 0;

    do_action('wp-freeio-before-hire-service-action', $service_id);

    $product_id = wp_freeio_get_option('services_woocommerce_product_id');

    if( !empty( $product_id )) {
        if ( class_exists('WooCommerce') ) {
            global $woocommerce;
            $woocommerce->cart->empty_cart(); //empty cart before update cart
            
            $cart_meta      = array();
            $addon_data     = array();

            $service_package_content = '';
            $meta_obj = WP_Freeio_Service_Meta::get_instance($service_id);
            if ( $meta_obj->check_post_meta_exist('price_type') && $meta_obj->get_post_meta('price_type') === 'package' ) {
                if ( !$meta_obj->check_post_meta_exist('price_packages') ) {
                    return false;
                }
                $price_packages = $meta_obj->get_post_meta( 'price_packages' );
                if ( $price_packages && is_array($price_packages) ) {
                    if ( isset($price_packages[$service_package]) ) {
                        $service_price = $single_service_price = $price_packages[$service_package]['price'];
                        $service_package_content = $price_packages[$service_package];
                    }
                } else {
                    return false;
                }
            } else {
                if ( !$meta_obj->check_post_meta_exist('price') ) {
                    return false;
                }
                $service_price = $single_service_price = $meta_obj->get_post_meta( 'price' );
            }

            $service_addons = !empty($_POST['service_addons']) ? array_map( 'sanitize_text_field', $_POST['service_addons']) : array();
            if ( !empty($service_addons) ) {
                foreach ($service_addons as $addon_id) {
                    $addon_price = get_post_meta($addon_id, WP_FREEIO_SERVICE_ADDON_PREFIX.'price', true);
                    $service_price += $addon_price;

                    $addon_data[$addon_id]['id']    = $addon_id;
                    $addon_data[$addon_id]['price'] = $addon_price;
                }
            }

            if ( !$meta_obj->check_post_meta_exist('delivery_time') ) {
                $delivery_time = '';
            } else {
                $delivery_time = $meta_obj->get_post_meta( 'delivery_time' );
            }
            $admin_shares = 0.0;
            $freelancer_shares = 0.0;

            if ( !empty( $service_price ) ) {
                $options = [
                    'type' => wp_freeio_get_option('freelancers_service_commission_fee', 'none'),
                    'fixed_amount' => wp_freeio_get_option('freelancers_service_commission_fixed_amount', 10),
                    'percentage' => wp_freeio_get_option('freelancers_service_commission_percentage', 20),
                    'comissions_tiers' => wp_freeio_get_option('freelancers_service_comissions_tiers'),
                ];
                $service_fee = WP_Freeio_Mixes::process_commission_fee($service_price, $options);
                if( !empty( $service_fee ) ){
                    $admin_shares = !empty($service_fee['admin_shares']) ? $service_fee['admin_shares'] : 0.0;
                    $freelancer_shares = !empty($service_fee['freelancer_shares']) ? $service_fee['freelancer_shares'] : $service_price;
                } else{
                    $admin_shares = 0.0;
                    $freelancer_shares = $service_price;
                }

                $admin_shares = number_format($admin_shares, 2, '.', '');
                $freelancer_shares = number_format($freelancer_shares, 2, '.', '');
            }
            
            $options = [
                'type' => wp_freeio_get_option('employers_service_commission_fee', 'none'),
                'fixed_amount' => wp_freeio_get_option('employers_service_commission_fixed_amount', 10),
                'percentage' => wp_freeio_get_option('employers_service_commission_percentage', 20),
                'comissions_tiers' => wp_freeio_get_option('employers_service_comissions_tiers'),
            ];
            $employer_service_fee = WP_Freeio_Mixes::employer_hiring_payment_setting($service_price, $options);
            
            $cart_meta['service_id']        = $service_id;
            $cart_meta['delivery_time']     = $delivery_time;
            $cart_meta['price']             = $service_price;
            $cart_meta['processing_fee']    = !empty( $employer_service_fee['commission_amount'] ) ? $employer_service_fee['commission_amount'] : 0.0;
            $cart_meta['service_price']     = $single_service_price;
            $cart_meta['addons']            = $addon_data;
            $cart_meta['service_package_content'] = $service_package_content;

            $freelancer_id = WP_Freeio_Service::get_author_id($service_id);

            $cart_data = array(
                'product_id'        => $product_id,
                'cart_data'         => $cart_meta,
                'price'             => WP_Freeio_Price::format_price($service_price, false),
                'payment_type'      => 'hiring_service',
                'admin_shares'      => $admin_shares,
                'freelancer_shares' => $freelancer_shares,
                'employer_id'       => $user_id,
                'freelancer_id'     => $freelancer_id,
                'current_project'   => $service_id,
            );
            
            $woocommerce->cart->empty_cart();
            WC()->cart->add_to_cart($product_id, 1, null, null, $cart_data);
            
            $return = array( 'status' => true, 'msg' => esc_html__('Please wait you are redirecting to the checkout page.', 'wp-freeio'), 'checkout_url' => wc_get_checkout_url() );
            wp_send_json($return);
            
        } else {
            $return = array( 'status' => false, 'msg' => esc_html__('Please install WooCommerce plugin to process this order.', 'wp-freeio') );
            wp_send_json($return);
        }
    } else{
        $return = array( 'status' => false, 'msg' => esc_html__('Hiring settings is missing, please contact to administrator.', 'wp-freeio') );
        wp_send_json($return);
    }
}
