<?php

/**
 * Custom functions.
 * ----------------------------------------------------------------------------
 */

/**
 * @param int $excerpt_length
 * @param int $id
 * @param string $excerpt_more
 * @return mixed|string
 */
function vo_get_my_excerpt($excerpt_length = 55, $id = 0, $excerpt_more = ' [...]') {
    if (!empty($id)) {
        $the_post = get_post($id);
        $text = ($the_post->post_excerpt) ? $the_post->post_excerpt : $the_post->post_content;
    } else {
        global $post;
        $text = ($post->post_excerpt) ? $post->post_excerpt : get_the_content('');
    }

    $text = strip_shortcodes($text);
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]&gt;', $text);
    $text = strip_tags($text);

    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);

    if (count($words) > $excerpt_length) {
        array_pop($words);
        $text = implode(' ', $words);
        $text = $text . $excerpt_more;
    } else {
        $text = implode(' ', $words);
    }

    return $text;
}

/**
 * @param string $string
 */
function vo_dump($string = '') {
    echo '<pre>';
    var_dump($string);
    echo '</pre>';
}

/**
 * @param int $image_id
 * @param string $image_size
 * @return string
 */
function vo_get_image_url($image_id = 0, $image_size = 'full') {
    $image_url = '';
    if (!empty($image_id)) {
        $image = wp_get_attachment_image_src($image_id, $image_size);
        if (!empty($image)) {
            $image_url = $image[0];
        }
    }
    return $image_url;
}

/**
 * Include template part with optional variables.
 *
 * For example, if you have a variable `$title` that you wish to use in your
 * template part `content-hero.php`, you can do this:
 *
 * `vo_get_template_part('content', 'hero', array('title' => $title);`
 *
 * This allows you to use $title in your template part.
 *
 * @param string      $slug The slug name for the generic template.
 * @param string|null $name Optional. The name of the specialized template.
 * @param array       $args Optional. An array of variables to be included in the template part.
 */
function vo_get_template_part($slug, $name = null, $args = []) {
    // Do action related to the template part.
    do_action("get_template_part_{$slug}", $slug, $name);

    $templates = [];
    $name = (string) $name;

    // If the template part has a name, call that template part.
    if ('' !== $name) {
        $name = str_replace('_', '-', $name);
        $templates[] = "{$slug}-{$name}.php";
    }

    // Call the template part with the slug.
    $templates[] = "{$slug}.php";

    // If the template part doesn't exist, don't do anything.
    if (locate_template($templates) == '') {
        return;
    }

    // If you passed any variables, extract them.
    if (!empty($args) && is_array($args)) {
        extract($args);
    }

    // Include the template part.
    include(locate_template($templates));
}

/**
 * @param $text
 * @param array $tags
 * @return string
 */
function vo_kses($text, $tags = array()) {
    if (empty($tags)) {
        $tags = array(
            'br' => array()
        );
    }
    return wp_kses($text, $tags);
}


/**
 * Return a Base64-encoded version of a file.
 *
 * @param  string $url  URL of the file to be encoded.
 * @param  string $mime Optional. MIME type of the file. Default MIME type from mime_content_type/empty.
 * @return string|void Base-64 encoded version of the file if not empty.
 */
function vo_get_data_uri($url, $mime = '') {
    if (empty($url)) {
        return;
    }

    // If $mime is not passed, try to get it automatically with mime_content_type.
    if (empty($mime)) {
        // Convert URL to path (relative link with first '/' removed).
        $path = ltrim(wp_make_link_relative(esc_url($url)), '/');
        $mime = function_exists('mime_content_type') ? mime_content_type($path) : '';
    }

    // Initiate cURL.
    $ch = curl_init();
    // Set URL.
    curl_setopt($ch, CURLOPT_URL, esc_url($url));
    // Return the transfer as a string.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // $output contains the output string.
    $output = curl_exec($ch);
    // Close cURL resource to free up system resources.
    curl_close($ch);

    if (!empty($ch)) {
        return 'data: ' . esc_attr($mime) . ';base64,' . base64_encode($output);
    } else {
        return '';
    }
}

/**
 * Get the price of a variation.
 *
 * @param int $id ID of the variation
 * @return int Variation price.
 */
function vo_get_variation_price($id) {
    if (empty($id)) return;

    $product = wc_get_product($id);

    if (!$product) return;

    return $product->get_price_html();
}

/**
 * The WooCommerce Wholesale plugin does only
 * apply price filters on the get_price_html
 * function. So we need this ugly function to
 * turn the HTML price to a float which we can
 * use to do calculations :-(
 */
function vo_html_price_to_float($priceHtml) {
    // strip HTML
    $priceHtml = strip_tags($priceHtml);
    // replace , for points
    $priceHtml = str_replace(',', '.', $priceHtml);

    // if there are more than 1 point (.), remove all except the last one
    $numberOfPoints = substr_count($priceHtml, '.');
    if ($numberOfPoints > 1) {
        $priceHtml = preg_replace('/'.preg_quote('.', '/').'/', '', $priceHtml, ($numberOfPoints - 1));
    }

    // remove any other characters other than numbers and points (.)
    $priceHtml = preg_replace("/[^0-9,.]/", "", $priceHtml);

    return floatval(trim($priceHtml));
}

/**
 * @param string $field
 * @return mixed
 */
function vo_get_option($field = '') {
    $value = get_option('options_' . $field);
    return $value;
}

/*
 * ACF HELPERS
 * ---------------------------------------------------------------------------------------------------------------------
 */

/**
 * Check for Gravity Forms in ACF select field
 * @param string $key
 * @param string $name
 * @param array $conditional_logic
 * @return array
 */
function vo_acf_select_gravity_form($key = 'key_forms_id', $name = 'form_id', $conditional_logic = array()) {
    if (function_exists('is_plugin_active') && is_plugin_active('gravityforms/gravityforms.php')) {
        $forms = GFAPI::get_forms();
        $forms_arr = [];
        foreach ($forms as $index => $form) {
            if ($index === 0) {
                $forms_arr[0] = __('Select a form', THEME_SLUG);
            }
            $forms_arr[$form['id']] = $form['title'];
        }
        $form_field_select = array(
            'key' => $key,
            'name' => $name,
            'label' => __('Form', THEME_SLUG),
            'type' => 'select',
            'choices' => $forms_arr,
            'conditional_logic' => $conditional_logic
        );
    } else {
        $form_field_select = array(
            'key' => $key . '_error',
            'name' => 'form_error',
            'label' => __('Error', THEME_SLUG),
            'message' => __('To enable this block, you need to install Gravity Forms.', THEME_SLUG),
            'type' => 'message',
            'conditional_logic' => $conditional_logic
        );
    }

    return $form_field_select;
}

/**
 * Validate Gravity Forms form id
 * @param int $form_id
 * @return bool
 */
function vo_validate_gravity_form_id($form_id = 0) {
    $valid = !empty($form_id) && $form_id !== 0 && function_exists('gravity_form') ? true : false;
    return $valid;
}

/**
 * @param $prefix
 * @return array
 */
function vo_acf_focal_point_fields($prefix) {
    $focal_point = [
        'key' => 'key_' . $prefix . '_focal_point',
        'name' => 'focal_point',
        'label' => __('Focal Point', THEME_SLUG),
        'instructions' => __('Fill in a number between 0 and 100. <br>To align image top fill in a value between 0 and 50. <br>To align image center leave field blank or fill in 50. <br>To align image bottom fill in a value between 50 and 100.', THEME_SLUG),
        'type' => 'group',
        'layout' => 'block',
        'sub_fields' => [
            [
                'key' => 'key_' . $prefix . '_focal_point_mobile',
                'name' => 'mobile',
                'label' => __('Mobile', THEME_SLUG),
                'type' => 'group',
                'layout' => 'block',
                'wrapper' => [
                    'width' => '33',
                ],
                'sub_fields' => [
                    [
                        'key' => 'key_' . $prefix . '_focal_point_mobile_value',
                        'name' => 'value',
                        'label' => __('Position', THEME_SLUG),
                        'type' => 'number',
                    ],
                ],
            ],
            [
                'key' => 'key_' . $prefix . '_focal_point_tablet',
                'name' => 'tablet',
                'label' => __('Tablet', THEME_SLUG),
                'type' => 'group',
                'layout' => 'block',
                'wrapper' => [
                    'width' => '33',
                ],
                'sub_fields' => [
                    [
                        'key' => 'key_' . $prefix . '_focal_point_tablet_value',
                        'name' => 'value',
                        'label' => __('Position', THEME_SLUG),
                        'type' => 'number',
                    ],
                ],
            ],
            [
                'key' => 'key_' . $prefix . '_focal_point_desktop',
                'name' => 'desktop',
                'label' => __('Desktop', THEME_SLUG),
                'type' => 'group',
                'layout' => 'block',
                'wrapper' => [
                    'width' => '33',
                ],
                'sub_fields' => [
                    [
                        'key' => 'key_' . $prefix . '_focal_point_desktop_value',
                        'name' => 'value',
                        'label' => __('Position', THEME_SLUG),
                        'type' => 'number',
                    ],
                ],
            ],
        ],
    ];

    return $focal_point;
}

/**
 * @param $prefix
 * @param string $section_class_name
 * @return string
 */
function vo_get_focal_point_section_prefix_class_name($prefix, $section_class_name = 'focal-point') {
    $section_prefix_class_name  = $section_class_name . '--' . $prefix;
    $class = $section_class_name . ' ' . $section_prefix_class_name;
    return $class;
}

/**
 * @param $prefix
 * @param string $key
 * @param string $child_background
 * @return string
 */
function vo_get_focal_point_style($prefix, $key = 'focal_point', $child_background = '') {
    // Layout
    $breakpoints = [
        'mobile' => 0,
        'tablet' => '40em',
        'desktop' => '64em'
    ];

    $section_class              = '.focal-point';
    $section_prefix_class       = $section_class . '--' . $prefix;
    $focal_point_class          = $section_prefix_class;

    if (!empty($child_background)) {
        $focal_point_class .= ', ' . $focal_point_class . ' .' . $child_background;
    }

    $position_mobile   = get_post_meta(get_the_ID(), $key . '_mobile_value', true);
    $position_mobile   = !empty($position_mobile) ? $position_mobile : 50;
    $position_tablet   = get_post_meta(get_the_ID(), $key . '_tablet_value', true);
    $position_tablet   = !empty($position_tablet) ? $position_tablet : 50;
    $position_desktop  = get_post_meta(get_the_ID(), $key . '_desktop_value', true);
    $position_desktop  = !empty($position_desktop) ? $position_desktop : 50;
    ob_start();
    ?>
    <style type="text/css">
        <?php if (!empty($position_mobile)) : ?>
        <?php echo $focal_point_class ; ?> {
            background-position: 50% <?php echo $position_mobile . '%'; ?> !important;
        }
        <?php endif; ?>
        <?php if (!empty($position_tablet)) : ?>
        @media print, screen and (min-width: <?php echo $breakpoints['tablet'] ?>) {
        <?php echo $focal_point_class ; ?> {
            background-position: 50% <?php echo $position_tablet . '%'; ?> !important;
        }
        }
        <?php endif; ?>
        <?php if (!empty($position_desktop)) : ?>
        @media print, screen and (min-width: <?php echo $breakpoints['desktop'] ?>) {
        <?php echo $focal_point_class ; ?> {
            background-position: 50% <?php echo $position_desktop . '%'; ?> !important;
        }
        }
        <?php endif; ?>
    </style>
    <?php
    return ob_get_clean();
}

