<?php

/**
 * add_filter() calls.
 *
 * Please read the documentation at <https://developer.wordpress.org/reference/functions/add_filter/>.
 * ----------------------------------------------------------------------------
 */

remove_filter('the_content', 'wpautop');

add_filter('wp_title', 'vo_wp_title', 10, 2);
add_filter('style_loader_src', 'vo_remove_wordpress_version_from_enqueues', 9999);
add_filter('script_loader_src', 'vo_remove_wordpress_version_from_enqueues', 9999);
add_filter('the_generator', 'vo_remove_wordpress_version_from_the_generator');
add_filter('xmlrpc_enabled', '__return_false');
/**
 * Disable JSON API calls when not authenticated.
 * Some filters use has_filter() because they only exists in previous WP versions.
 */
$json_enabled = (defined('VO_ENABLE_JSON_API')) ? filter_var(VO_ENABLE_JSON_API, FILTER_VALIDATE_BOOLEAN) : false;
if (!$json_enabled) {
    add_filter('rest_authentication_errors', 'vo_only_allow_logged_in_rest_access');
    if (has_filter('json_enabled')) add_filter('json_enabled', '__return_false');
    if (has_filter('json_jsonp_enabled')) add_filter('json_jsonp_enabled', '__return_false');
    if (has_filter('rest_enabled')) add_filter('rest_enabled', '__return_false');
    if (has_filter('rest_jsonp_enabled')) add_filter('rest_jsonp_enabled', '__return_false');
}
add_filter('image_resize_dimensions', 'vo_image_upscale', 10, 6);
add_filter('the_content', 'wpautop', 99);
add_filter('the_content', 'shortcode_unautop', 100);
add_filter('acf/settings/path', 'vo_acf_settings_path');
add_filter('acf/settings/dir', 'vo_acf_settings_dir');
add_filter('acf/settings/show_admin', '__return_false');
add_filter('acf/load_field/key=key_page_builder_products_category', 'vo_add_woocommerce_categories_to_products_block');
add_filter('acf/load_field/key=key_page_builder_products_list_category', 'vo_add_woocommerce_categories_to_products_block');
add_filter('wpseo_metabox_prio', 'vo_set_wpseo_metabox_prio');
// Remove default WooCommerce styling
add_filter('woocommerce_enqueue_styles', '__return_empty_array');



/**
 * Custom functions called by add_filter() function.
 * ----------------------------------------------------------------------------
 */
add_filter('woocommerce_checkout_fields', 'vo_woocommerce_checkout_fields');
add_filter('woocommerce_order_formatted_billing_address', 'vo_woocommerce_order_formatted_billing_address', 10, 2);
add_filter('woocommerce_order_formatted_shipping_address', 'vo_woocommerce_order_formatted_shipping_address', 10, 2);
add_filter('woocommerce_formatted_address_replacements', 'vo_woocommerce_formatted_address_replacements', 10, 2);
add_filter( 'woocommerce_formatted_address_replacements', 'vo_add_new_replacement_fields',10,2 );
add_filter( 'woocommerce_localisation_address_formats', 'vo_new_address_formats' );

/**
 * @param $fields
 * @return array
 */
function vo_woocommerce_checkout_fields($fields) {
    // Billing
    $fields['billing']['billing_house_number'] = array(
        'label' => __('House Number', 'woocommerce'),
        'placeholder' => _x('House Number', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-last'),
        'clear' => true
    );
    $fields['billing']['billing_addition'] = array(
        'label' => __('Addition', 'woocommerce'),
        'placeholder' => _x('Addition', 'placeholder', 'woocommerce'),
        'required' => false,
        'class' => array('form-row-last'),
        'clear' => true
    );
    // Shipping
    $fields['shipping']['shipping_house_number'] = array(
        'label' => __('House Number', 'woocommerce'),
        'placeholder' => _x('House Number', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-last'),
        'clear' => true
    );
    $fields['shipping']['shipping_addition'] = array(
        'label' => __('Addition', 'woocommerce'),
        'placeholder' => _x('Addition', 'placeholder', 'woocommerce'),
        'required' => false,
        'class' => array('form-row-last'),
        'clear' => true
    );

    // Remove Address_2 Fields
    unset($fields['billing']['billing_address_2']);
    unset($fields['shipping']['shipping_address_2']);

    // Make Address_1 Fields Half Width
    $fields['billing']['billing_address_1']['class'] = array('form-row-first');
    $fields['shipping']['shipping_address_1']['class'] = array('form-row-first');

    // Billing: Sort Fields
    $newfields['billing']['billing_first_name'] = $fields['billing']['billing_first_name'];
    $newfields['billing']['billing_last_name'] = $fields['billing']['billing_last_name'];
    $newfields['billing']['billing_company'] = $fields['billing']['billing_company'];
    $newfields['billing']['billing_email'] = $fields['billing']['billing_email'];
    $newfields['billing']['billing_phone'] = $fields['billing']['billing_phone'];
    $newfields['billing']['billing_country'] = $fields['billing']['billing_country'];
    $newfields['billing']['billing_address_1'] = $fields['billing']['billing_address_1'];
    $newfields['billing']['billing_house_number'] = $fields['billing']['billing_house_number'];
    $newfields['billing']['billing_addition'] = $fields['billing']['billing_addition'];
    $newfields['billing']['billing_city'] = $fields['billing']['billing_city'];
    $newfields['billing']['billing_postcode'] = $fields['billing']['billing_postcode'];
    $newfields['billing']['billing_state'] = $fields['billing']['billing_state'];

    // Shipping: Sort Fields
    $newfields['shipping']['shipping_first_name'] = $fields['shipping']['shipping_first_name'];
    $newfields['shipping']['shipping_last_name'] = $fields['shipping']['shipping_last_name'];
    $newfields['shipping']['shipping_company'] = $fields['shipping']['shipping_company'];
    $newfields['shipping']['shipping_country'] = $fields['shipping']['shipping_country'];
    $newfields['shipping']['shipping_address_1'] = $fields['shipping']['shipping_address_1'];
    $newfields['shipping']['shipping_house_number'] = $fields['shipping']['shipping_house_number'];
    $newfields['shipping']['shipping_addition'] = $fields['shipping']['shipping_addition'];
    $newfields['shipping']['shipping_city'] = $fields['shipping']['shipping_city'];
    $newfields['shipping']['shipping_state'] = $fields['shipping']['shipping_state'];
    $newfields['shipping']['shipping_postcode'] = $fields['shipping']['shipping_postcode'];

    $checkout_fields = array_merge($fields, $newfields);
    return $checkout_fields;
}

/**
 * @param $fields
 * @param $order
 * @return mixed
 */
function vo_woocommerce_order_formatted_billing_address($fields, $order) {
    $fields['billing_house_number'] = get_post_meta($order->id, '_billing_house_number', true);
    $fields['billing_addition'] = get_post_meta($order->id, '_billing_addition', true);
    return $fields;
}

/**
 * @param $fields
 * @param $order
 * @return mixed
 */
function vo_woocommerce_order_formatted_shipping_address($fields, $order) {
    $fields['shipping_house_number'] = get_post_meta($order->id, '_shipping_house_number', true);
    $fields['shipping_addition'] = get_post_meta($order->id, '_shipping_addition', true);
    return $fields;
}

/**
 * @param $replacements
 * @param $address
 * @return mixed
 */
function vo_woocommerce_formatted_address_replacements($replacements, $address) {
    $replacements['{billing_house_number}'] = isset($address['billing_house_number']) ? $address['billing_house_number'] : '';
    $replacements['{billing_addition}'] = isset($address['billing_addition']) ? $address['billing_addition'] : '';
    $replacements['{shipping_house_number}'] = isset($address['shipping_house_number']) ? $address['shipping_house_number'] : '';
    $replacements['{shipping_addition}'] = isset($address['shipping_addition']) ? $address['shipping_addition'] : '';
    return $replacements;
}

/**
 * @param $replacements
 * @param $address
 * @return mixed
 */
function vo_add_new_replacement_fields($replacements, $address) {
    $replacements['{billing_houseno}'] = isset($address['billing_house_number']) ? $address['billing_house_number'] : '';
    $replacements['{billing_addition}'] = isset($address['billing_addition']) ? $address['billing_addition'] : '';
    $replacements['{shipping_houseno}'] = isset($address['shipping_house_number']) ? $address['shipping_house_number'] : '';
    $replacements['{shipping_addition}'] = isset($address['shipping_addition']) ? $address['shipping_addition'] : '';
    return $replacements;
}

/**
 * @param $formats
 * @return mixed
 */
function vo_new_address_formats($formats) {
    $formats['NL'] = "{name}\n{company}\n{address_1} {billing_houseno} {billing_addition} {shipping_houseno} {shipping_addition}\n{city}\n{state}\n{postcode}\n{country}";
    return $formats;
}

/**
 * Create a nicely formatted and more specific title element text for output
 * in head of document, based on current view.
 *
 * @param string $title
 * @param string $sep
 * @return string
 */
function vo_wp_title($title = '', $sep = '') {
    global $paged, $page;

    if (is_feed()) {
        return $title;
    }

    // Add the site name.
    $title .= get_bloginfo('name', 'display');

    // Add the site description for the home/front page.
    $site_description = get_bloginfo('description', 'display');

    if ($site_description && (is_home() || is_front_page())) {
        $title = "$title $sep $site_description";
    }

    // Add a page number if necessary.
    if ($paged >= 2 || $page >= 2) {
        $title = "$title $sep " . sprintf(__('Page %s', THEME_SLUG), max($paged, $page));
    }

    return $title;
}

/**
 * @param string $src
 * @return string
 */
function vo_remove_wordpress_version_from_enqueues($src = '') {
    if (strpos($src, 'ver=' . get_bloginfo('version'))) {
        $src = remove_query_arg('ver', $src);
    }

    return $src;
}

/**
 * @return string
 */
function vo_remove_wordpress_version_from_the_generator() {
    return '';
}

/**
 * Disable JSON API calls when not authenticated.
 *
 * @param $access
 * @return WP_Error
 */
function vo_only_allow_logged_in_rest_access($access) {
    if (!is_user_logged_in()) {
        return new WP_Error('rest_cannot_access', __('Only authenticated users can access the REST API.', THEME_SLUG), array('status' => rest_authorization_required_code()));
    }
    return $access;
}

/**
 * @param string $path
 * @return string
 */
function vo_acf_settings_path($path = '') {
    return THEME_DIR_VENDOR . '/advanced-custom-fields-pro/';
}

/**
 * @param string $dir
 * @return string
 */
function vo_acf_settings_dir($dir = '') {
    return THEME_URI_VENDOR . '/advanced-custom-fields-pro/';
}

/**
 * Always force upscaling images to be able to crop them
 *
 * @param $default, $orig_w, $orig_h, $new_w, $new_h, $crop
 * @return mixed
 */
function vo_image_upscale($default, $orig_w, $orig_h, $new_w, $new_h, $crop) {
    if (!$crop) {
        return null;
    }
    $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
    $crop_w = round($new_w / $size_ratio);
    $crop_h = round($new_h / $size_ratio);
    $s_x = floor(($orig_w - $crop_w) / 2);
    $s_y = floor(($orig_h - $crop_h) / 2);
    return array(0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h);
}

/**
 * @param string $high
 * @return string
 */
function vo_set_wpseo_metabox_prio($high = '') {
    return 'low';
}

/**
 * Add WooCommerce categories to ACF select field.
 *
 * @param $field
 */
function vo_add_woocommerce_categories_to_products_block($field) {
    if (!is_admin()) return;

    $categories = get_terms([
        'taxonomy' => 'product_cat',
        'hide_empty' => false]
    );

    $field['choices'] = array_reduce($categories, function($result, $category) {
        $result[$category->term_id] = $category->name;
        return $result;
    });

    return $field;
}
