<?php
/**
** activation theme
**/
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
 wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
 wp_enqueue_style( 'main-styles',
   get_stylesheet_directory_uri() . '/style.css',
   [ 'parent-style' ],
   wp_get_theme()->get('Version')
 );
}

/* on gère avec Polylang cet enfer */

function cw2b_content_copy( $content ) {
        if ( isset( $_GET['from_post'] ) ) {
                $my_post = get_post( $_GET['from_post'] );
                if ( $my_post )
                        return $my_post->post_content;
        }
return $content;
}
add_filter( 'default_content', 'cw2b_content_copy' );

function cw2b_editor_title( $title ) {    
    if ( isset( $_GET['from_post'] ) ) {
        $my_post = get_post( $_GET['from_post'] );
        if ( $my_post )
            return $my_post->post_title;
    }
    return $title;
}
add_filter( 'default_title', 'cw2b_editor_title' );

/* COOKIES */
/* add script blocker for GDPR cookie consent plugin (new GA4 cookies since 09.21) */
function scripts_list() {
    $scripts = array(
        array(
            'id' => '_ga_VQ7XH9070S',
            'label' => 'Google Analytics 4',
            'key' => array('https://www.googletagmanager.com/gtag/js?id=G-VQ7XH9070S'),
            'category' => 'performance',
            'status' => 'yes'
        ),
    );
    return $scripts;
}
add_filter('cli_extend_script_blocker', 'scripts_list', 10, 1);


/* Permet le blocage de script POLYLANG */
add_action( 'plugins_loaded', function() {
  if ( empty( $_COOKIE['pll_language'] ) ) {
    define( 'PLL_COOKIE', false );
  }
}, 0 );


/* Plugin Temporary Login Without Password > Additional Expiry Option  */
add_filter( 'tlwp_expiry_options', 'add_tlwp_expiry_option', 10, 1);
function add_tlwp_expiry_option( $options ) {

    $options['5_minutes'] = array(

        'label' => __('5 Minutes', 'text-domain'),
        'timestamp' => MINUTE_IN_SECONDS * 5,
        'order' => 1 // dropdown options will be sort with this number

    );

    return $options;

}

/*================================================
#Load custom Filterable Portfolio Module
================================================*/

function divi_custom_filterable_portfolio_module() {
    get_template_part( '/includes/custom-FilterablePortfolio' );
    $dcfm = new custom_ET_Builder_Module_Filterable_Portfolio();
    remove_shortcode( 'et_pb_filterable_portfolio' );
    add_shortcode( 'et_pb_filterable_portfolio', array( $dcfm, '_shortcode_callback' ) );
}

add_action( 'et_builder_ready', 'divi_custom_filterable_portfolio_module' );


function divi_custom_filterable_portfolio_class( $classlist ) { 
    // Blog Module 'classname' overwrite. 
    $classlist['et_pb_filterable_portfolio'] = array( 'classname' => 'custom_ET_Builder_Module_Filterable_Portfolio',); 
    return $classlist; 
} 

add_filter( 'et_module_classes', 'divi_custom_filterable_portfolio_class' );

/* ACCES SECURISE (non actif) */
/* (TEST à garder si besoin) Bloque l'accès au dossier sécurisé /uploads/protected-pdf pour la levé de capital > devrait fonctionner mais fonction comblé par le plugin Prevent Direct Access (pb réglé avec changement de plugin de cache W3 total cache posant problème aux 2 méthodes) */

// 1. Déclarer l'endpoint
function register_secure_pdf_endpoint() {
    add_rewrite_rule('^secure-pdf/([a-zA-Z0-9\-_]+)?$', 'index.php?secure_pdf=$matches[1]', 'top');
}
add_action('init', 'register_secure_pdf_endpoint');

// 2. Ajouter la variable de requête
function add_secure_pdf_query_var($vars) {
    $vars[] = 'secure_pdf';
    return $vars;
}
add_filter('query_vars', 'add_secure_pdf_query_var');

// 3. Gérer la requête
function serve_secure_pdf_file() {
    $pdf = get_query_var('secure_pdf');
    if (!$pdf) return;

    if (!is_user_logged_in()) {
        auth_redirect();
        exit;
    }

    $filename = sanitize_file_name($pdf) . '.pdf';
    $filepath = WP_CONTENT_DIR . '/uploads/protected-pdf/' . $filename;

    if (!file_exists($filepath)) {
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
        nocache_headers();
        include get_query_template('404');
        exit;
    }

    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
    exit;
}
add_action('template_redirect', 'serve_secure_pdf_file');

/* Bloque l'accès admin à l'admin "temp" (dans le cadre de l'espace sécurisé investisseurs) + accès à la top bar (évite de le faire manuellement à chaque création de connexion temporaire) */

add_action('init', function() {
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();

        // Vérifier si l'utilisateur est "temp"
        if ($current_user->user_login === 'temp') {

            // Bloquer l'accès à l'admin et rediriger vers l'accueil
            add_action('admin_init', function() {
                wp_redirect(home_url());
                exit;
            });

            // Désactiver la barre admin sur le front
            add_filter('show_admin_bar', '__return_false');

            // Forcer la désactivation dans le profil utilisateur
            update_user_meta($current_user->ID, 'show_admin_bar_front', 'false');
        }
    }
});

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