<?php

// Suppression des mises à jour auto
// define('AUTOMATIC_UPDATER_DISABLED', true);

/**
 * PAGINATION ACTUALITES URL REWRITING
 */


function lp_pagination_rewrite_rule()
{
    add_rewrite_rule('(magazine|magazin)/page/?([0-9]{1,})/?$', 'index.php?pagename=$matches[1]&paged=$matches[2]', 'top');
}
add_action('init', 'lp_pagination_rewrite_rule', 10, 0);

function lp_post_rewrite_rule()
{
    add_rewrite_rule('(magazine|magazin)/([^/]+)/([^/]+)/?$', 'index.php?name=$matches[3]', 'top');
}
add_action('init', 'lp_post_rewrite_rule', 10, 0);

function lp_pagination_add_query_vars($query_vars)
{
    $query_vars[] = 'paged';
    return $query_vars;
}
add_filter('query_vars', 'lp_pagination_add_query_vars');


function lp_permalink_prefix($url, $post)
{
    // Vérifier si le post est de type article
    if ($post->post_type == 'post') {
        // Récupérer la catégorie principale du post
        $category = get_the_category($post->ID);
        if ($category) {
            $category_slug = $category[0]->slug;
            $url = get_category_link($category[0]->term_id) . $post->post_name . '/';
            // Ajouter le préfixe et la catégorie au permalien
            // $url = trailingslashit(home_url('/actualites/' . $category_slug . '/' . $post->post_name));
        }
    }
    return $url;
}
add_filter('post_link', 'lp_permalink_prefix', 10, 2);

function lp_redirect_post_permalink()
{
    // Vérifier si la requête concerne un article
    if (is_single()) {
        // Récupérer l'URL actuelle
        global $wp;
        $current_url = home_url(add_query_arg(array(), $wp->request));

        // Récupérer l'URL de l'article
        $post_permalink = get_permalink();

        // Comparer les URLs
        if ($current_url !== $post_permalink) {
            // Rediriger vers l'URL de l'article
            wp_redirect($post_permalink, 301);
            exit();
        }
    }
}
add_action('template_redirect', 'lp_redirect_post_permalink');


/* **************
** LANGUES **
************** */

load_theme_textdomain("laurentperrier", TEMPLATEPATH . '/languages');


/* ********************
** FIX ROOT PAGE - WPML BUG **
******************** */
function wpml_root_page()
{
    global $wp_query, $sitepress;
    $queriedId = $wp_query->get_queried_object_id();
    if ($queriedId > 0 && (isset($sitepress->ROOT_URL_PAGE_ID) && $queriedId == $sitepress->ROOT_URL_PAGE_ID)) {
        define('IS_ROOT_PAGE', true);
        include "lang.php";
        die();
    }
}
add_action('wp', 'wpml_root_page');


/* ********************
** GET COUNTRY VISITOR **
******************** */
function lpGetIPAddress()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // if ($ip == '::1') $ip = '';
    return $ip;
}

add_action('init', 'lp_set_country_ip_cookie');

function lp_set_country_ip_cookie()
{


    if (isset($_COOKIE['lp_country']) && !empty($_COOKIE['lp_country'])) {
        return $_COOKIE['lp_country'];
    }
    $ip = lpGetIPAddress();



    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.country.is/" . $ip);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $details = json_decode(curl_exec($ch));
        curl_close($ch);


        // $details = json_decode(file_get_contents("https://api.country.is/" . $ip));
        if (lpGetIPAddress() == '::1') {
            setcookie('lp_country', 'us', time() + 3600 * 2, '/');
            return 'us';
        } elseif (isset($details->country) && strlen($details->country) == 2) {
            $country = strtolower($details->country);
            if ($country == 'uk') $country = 'en';
            if ($country == 'gb') $country = 'en';
            setcookie('lp_country', $country, time() + 3600 * 2, '/');
            return $country;
        } else {

            return false;
        }
    } else {
        return false;
    }
}

function lp_get_country_ip()
{
    if (isset($_COOKIE['lp_country']) && !empty($_COOKIE['lp_country'])) {
        return $_COOKIE['lp_country'];
    } else {
        $ip = lpGetIPAddress();
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.country.is/" . $ip);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $details = json_decode(curl_exec($ch));
            curl_close($ch);
            // $details = json_decode(file_get_contents("https://api.country.is/".$ip));
            if (isset($details->country) && strlen($details->country) == 2) {
                $country = strtolower($details->country);
                if ($country == 'uk') $country = 'en';
                if ($country == 'gb') $country = 'en';
                return $country;
            } else {
                return false;
            }
        }
    }
    return false;
}


function is_display_buy_buttons()
{
    $my_current_lang = apply_filters('wpml_current_language', NULL);
    $country_ip = lp_get_country_ip();

    if ($country_ip !== false && strtolower($country_ip) == strtolower($my_current_lang) && in_array(strtolower($my_current_lang), ['fr', 'en'])) {
        return true;
    } else {
        //cas localhost
        if (lpGetIPAddress() == '::1') {
            return true;
        } else {
            return false;
        }
    }
}

/* **************
** JAVASCRIPTS **
************** */
function my_load_scripts($hook)
{
    wp_enqueue_script('scripts', get_template_directory_uri() . '/dist/app.js', array('jquery'), true);
    wp_enqueue_script('gmap', get_template_directory_uri() . '/dist/storelocator.js', array('jquery'), '2.33');

    wp_localize_script(
        'scripts',
        'lpscripts',
        array(
            'country' => lp_get_country_ip(),
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('lp-application-ajax-nonce'),
            'wpmlLang' => ICL_LANGUAGE_CODE,
        )
    );
    wp_register_style('styles', get_stylesheet_directory_uri() . '/dist/app.css', array(), '1.3', 'all');
    wp_enqueue_style('styles');
}
add_action('wp_enqueue_scripts', 'my_load_scripts');


function my_admin_load_scripts($hook)
{
    wp_register_style('admin-styles', get_stylesheet_directory_uri() . '/dist/admin.css');
    wp_enqueue_style('admin-styles');
}
add_action('admin_enqueue_scripts', 'my_admin_load_scripts');


@ini_set('upload_max_size', '256M');
@ini_set('post_max_size', '256M');
@ini_set('max_execution_time', '800');


/* **********************
** WORDPRESS THUMBNAIL **
********************** */

add_theme_support('post-thumbnails');
add_image_size('home', 1400, 760, true);
add_image_size('page', 650, 0, false);
add_image_size('aside', 80, 50, true);
add_image_size('small', 300, 300, false);
add_image_size('lg', 1000, 10000, false);

if (!get_option("large_crop"))
    add_option("large_crop", "1");
else
    update_option("large_crop", "1");


/* ********************
** WORDPRESS SIDEBAR **
******************** */
// if (function_exists('register_sidebar')) {
//     register_sidebar(array(
//         'id' => 'sidebar-1',
//         'name' => 'sidebar',
//         'before_widget' => '<div class="bloc">',
//         'after_widget' => '</div>',
//         'before_title' => '<h3>',
//         'after_title' => '</h3>'
//     ));
// }


/* *****************
** WORDPRESS EXCERPT **
****************** */
function custom_excerpt_length($length)
{
    return 30;
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);


/* *****************
** WORDPRESS MENU **
****************** */
if (function_exists('register_nav_menus')) {
    register_nav_menus(
        array(
            'menu' => 'Primary menu',
            'footer' => 'Footer menu'
        )
    );
}
// remove container wp_nav
function my_wp_nav_menu_args($args = '')
{
    $args['container'] = false;
    return $args;
}
add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args');

// add wrapper for submenu
class WPSE_78121_Sublevel_Walker extends Walker_Nav_Menu
{
    function start_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<div class='sub-menu-wrap'><ul class='sub-menu'>\n";
    }
    function end_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul></div>\n";
    }
}


add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args');
// add wrapper for submenu
class WPSE_new_header_Walker extends Walker_Nav_Menu
{
    // function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
    // {
    //     global $wp_query;
    //     $indent = ($depth > 0 ? str_repeat("\t", $depth) : ''); // code indent

    //     // Depth-dependent classes.
    //     $depth_classes = array(
    //         ($depth == 0 ? 'main-menu-item' : 'sub-menu-item'),
    //         ($depth >= 2 ? 'sub-sub-menu-item' : ''),
    //         ($depth % 2 ? 'menu-item-odd' : 'menu-item-even'),
    //         'menu-item-depth-' . $depth
    //     );
    //     $depth_class_names = esc_attr(implode(' ', $depth_classes));

    //     // Passed classes.
    //     $classes = empty($item->classes) ? array() : (array) $item->classes;
    //     $class_names = esc_attr(implode(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item)));

    //     // Build HTML.
    //     $output .= $indent . '<li id="nav-menu-item-' . $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">';

    //     // Link attributes.
    //     $attributes  = !empty($item->attr_title) ? ' title="'  . esc_attr($item->attr_title) . '"' : '';
    //     $attributes .= !empty($item->target)     ? ' target="' . esc_attr($item->target) . '"' : '';
    //     $attributes .= !empty($item->xfn)        ? ' rel="'    . esc_attr($item->xfn) . '"' : '';
    //     $attributes .= !empty($item->url)        ? ' href="'   . esc_attr($item->url) . '"' : '';
    //     $attributes .= 'data-collapse="collapse-' . $item->ID . '"';
    //     $attributes .= $depth == 0 ? 'data-toggle="collapse"' : '';
    //     $attributes .= '"class="menu-link ' . ($depth > 0 ? 'sub-menu-link' : 'main-menu-link') . '"';

    //     // Build HTML output and pass through the proper filter.
    //     $item_output = sprintf(
    //         '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
    //         $args->before,
    //         $attributes,
    //         $args->link_before,
    //         apply_filters('the_title', $item->title, $item->ID),
    //         $args->link_after,
    //         $args->after
    //     );
    //     $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    // }

    function start_lvl(&$output, $depth = 0, $args = array())
    {

        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<div class='sub-menu-wrap'><ul class='sub-menu'>\n";
    }

    function end_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul></div>\n";
    }
}



/* ***************************
** WORDPRESS AJAX REQUESTS **
*************************** */
include_once('includes/ajax_requests.php');

/* ***************************
** WORDPRESS ADMIN **
*************************** */
include_once('includes/custom_admin.php');

/* ***************************
** STORE LOCATOR **
*************************** */
include_once('includes/countries.php');
//include_once('includes/stores.php');
include_once('includes/store_locator.php');



/* ********************
** WORDPRESS GALLERY **
******************** */
add_filter('use_default_gallery_style', '__return_false');
// modify attr
remove_shortcode('gallery');
add_shortcode('gallery', 'my_own_gallery_shortcode');
function my_own_gallery_shortcode($attr)
{
    $attr['itemtag']      = 'div';
    $attr['icontag']      = 'span';
    $attr['captiontag']   = 'figcaption';
    $attr['size']         = 'square';
    $output = gallery_shortcode($attr);
    $output = preg_replace(array('/<br[^>]*>/', '/<span[^>]*>/', '/<\/span>/'), '', $output);
    return $output;
}



function getIDFromString($str)
{
    $id = strtolower(preg_replace('/\s+/', '-', $str));
    $unwanted_array = array(
        'Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
        'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U',
        'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o',
        'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y'
    );
    $id = strtr($id, $unwanted_array);
    $id = preg_replace('/[^a-zA-Z0-9-_\.]/', '', $id);
    return $id;
}

/**
 * Responsive Image Helper Function
 *
 * @param string $image_id the id of the image (from ACF or similar)
 * @param string $image_size the size of the thumbnail image or custom image size
 * @param string $max_width the max width this image will be shown to build the sizes attribute
 */

function acf_responsive_image($image_id, $image_size, $max_width, $srcset = true)
{

    // check the image ID is not blank
    if ($image_id != '') {
        // set the default src image size
        $image_src = wp_get_attachment_image_url($image_id, $image_size);
        // set the srcset with various image sizes
        if ($srcset) {
            $image_srcset = wp_get_attachment_image_srcset($image_id, $image_size);
            echo 'src="' . $image_src . '"  srcset="' . $image_srcset . '" sizes="(max-width: ' . $max_width . ') 100vw, ' . $max_width . '"';
        } else {
            echo 'src="' . $image_src . '"';
        }
        // generate the markup for the responsive image
    } else {
        echo 'src="pixel.gif"';
    }
}



function my_acf_add_local_field_groups()
{
    remove_filter('acf_the_content', 'wpautop');
}
add_action('acf/init', 'my_acf_add_local_field_groups');


/* Autoriser les fichiers SVG */
function wpc_mime_types($mimes)
{
    $mimes['svg'] = 'image/svg xml';
    return $mimes;
}
add_filter('upload_mimes', 'wpc_mime_types');



@ini_set('upload_max_size', '64M');
@ini_set('post_max_size', '64M');
@ini_set('max_execution_time', '300');


$my_current_lang = apply_filters('wpml_current_language', NULL);


add_filter('wpseo_meta_author', '__return_false');
add_filter('wpseo_meta_twitter:data1', '__return_false');
add_filter('wpseo_meta_twitter:label1', '__return_false');


add_filter('plugins_auto_update_enabled', '__return_false');
add_filter('themes_auto_update_enabled', '__return_false');
define('automatic_updater_disabled', true);
