<?php
/* CALL STYLES FROM PARENT */
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

/***** JQUERY *****/
function customjs(){
    /* JS CUSTOM */
    wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/js/custom.js', array(), '1.0.0', true);

    /* CSS OWL CAROUSEL */
    wp_enqueue_script('owlcarouseljs', get_stylesheet_directory_uri() . '/js/owl.carousel.min.js', '', '', true);
}
add_action('wp_enqueue_scripts', 'customjs');

/***** CUSTOM CSS *****/
function customcss(){
    /* CSS CUSTOM */
    wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/css/custom.css' );
    // wp_enqueue_style( 'custom-min-style', get_stylesheet_directory_uri() . '/css/custom-min.css' );

    /* JS OWL CAROUSEL */
    wp_enqueue_style('owlcarousel-css', get_stylesheet_directory_uri() . '/css/owl.carousel.min.css'); 

    /* CDN FONT AWESOME */
    // wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css', array(), '6.0.0-beta3');
   
}
add_action('wp_enqueue_scripts','customcss');

/***** MISCELANEOUS *****/

/*  CHANGE LOGO IN LOGIN */
function mostrar_logo_divi_en_login() {
    $logo_id = et_get_option( 'divi_logo' );
    if ( $logo_id && is_string($logo_id) ) {
        $logo_url = $logo_id ;
    } else {
        $logo_url = 'https://ecolohosting.com/images/logo-noborrar.png';
    }
    echo '<style type="text/css">
            body.login div#login h1 a {
                background-image: url("' . esc_url( $logo_url ) . '");
                background-size: contain;
                background-repeat: no-repeat;
                width: 100%;
            }
        </style>';
}
add_action( 'login_enqueue_scripts', 'mostrar_logo_divi_en_login' );


/***** PRACTICAL SHORTCODES *****/

/* CALL MENU BY SHORTCODE */
/* [menu name="-your menu name-" class="-your class-"] */
add_filter( 'the_title', function( $title, $item_id ) {
    if ( 'nav_menu_item' === get_post_type( $item_id ) ) {
        return do_shortcode( $title );
    }
    return $title;
}, 10, 2 );
function print_menu_shortcode($atts, $content = null) {
extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts));
return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) );
}
add_shortcode('menu', 'print_menu_shortcode');

/* CALL SITE DOMAIN BY SHORTCODE TO AVOID ABSOLUTE LINKS */
/* [url page="slug"] */
function url_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'page' => '',
    ), $atts );
    
    return home_url( '/' . $atts['page'] );
}
add_shortcode('url', 'url_shortcode');

/* CALL YEAR BY SHORTCODE */
/* [year] */
function year_shortcode() {
    return date('Y');
}
add_shortcode('year', 'year_shortcode');

/* SHORTCODE INSIDE MODULES */ 
/* [showmodule id="module id number"] */ 
function showmodule_shortcode($moduleid) {
    extract(shortcode_atts(array('id' =>'*'),$moduleid)); 
    return do_shortcode('[et_pb_section global_module="'.$id.'"][/et_pb_section]');
}
add_shortcode('showmodule', 'showmodule_shortcode');



/***** WP HIDE ERRORS *****/

/* REMOVE LOGIN ERRORS */
function login_errors_message() {
    return 'Ooooops!';
}
add_filter('login_errors', 'login_errors_message');

/* LIMIT THE USER FOR WRONG LOGIN ATTEMPTS */ 
function limit_login_attempts() {
    if (!session_id()) {
        session_start();
    }

    $max_attempts = 5;
    $lockout_time = 15 * 60;

    if (isset($_SESSION['login_lockout']) && time() < $_SESSION['login_lockout']) {
        $time_remaining = $_SESSION['login_lockout'] - time();
        $minutes = ceil($time_remaining / 60);
        $message = "Has alcanzado el número máximo de intentos de inicio de sesión fallidos. Inténtalo de nuevo en $minutes minutos.";
        return new WP_Error('too_many_attempts', $message);
    }

    add_action('wp_login_failed', function($username) use ($max_attempts, $lockout_time) {
        if (!isset($_SESSION['login_attempts'])) {
            $_SESSION['login_attempts'] = 0;
        }

        $_SESSION['login_attempts']++;

        if ($_SESSION['login_attempts'] >= $max_attempts) {
            $_SESSION['login_lockout'] = time() + $lockout_time;
        }
    });

    add_action('wp_login', function() {
        unset($_SESSION['login_attempts']);
        unset($_SESSION['login_lockout']);
    });
}
add_action('init', 'limit_login_attempts');


/*  REMOVE CRAP FROM HEADER */
remove_action( 'wp_head',               'adjacent_posts_rel_link',       10, 0);
remove_action( 'wp_head',               'feed_links',                    2     );
remove_action( 'wp_head',               'feed_links_extra',              3     );
remove_action( 'wp_head',               'rsd_link'                             );
remove_action( 'wp_head',               'wlwmanifest_link'                     );
remove_action( 'wp_head',               'index_rel_link'                       );
remove_action( 'wp_head',               'parent_post_rel_link',          10, 0 );
remove_action( 'wp_head',               'start_post_rel_link',           10, 0 );
remove_action( 'wp_head',               'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action( 'wp_head',               'locale_stylesheet'                    );
remove_action( 'publish_future_post',   'check_and_publish_future_post', 10, 1 );
remove_action( 'wp_head',               'wp_generator'                         );
remove_action( 'wp_footer',             'wp_print_footer_scripts'              );
remove_action( 'wp_head',               'wp_shortlink_wp_head',          10, 0 );
remove_action( 'template_redirect',     'wp_shortlink_header',           11, 0 );
remove_action( 'wp_head',               'print_emoji_detection_script', 7);
remove_action( 'wp_print_styles',       'print_emoji_styles');



/* DEACTIVATE HTML ON COMMENTS */
add_filter('pre_comment_content', 'wp_specialchars');

/* REMOVE WP VERSION FROM RSS*/
add_filter('the_generator', '__return_empty_string');

/* REMOVE SCRIPTS VERSIONS */
function shapeSpace_remove_version_scripts_styles($src) {
    if (strpos($src, 'ver=')) {
        $src = remove_query_arg('ver', $src);
    }
    return $src;
}
add_filter('style_loader_src', 'shapeSpace_remove_version_scripts_styles', 9999);
add_filter('script_loader_src', 'shapeSpace_remove_version_scripts_styles', 9999);

/* PROTECT SYSTEM FILES */
function protect_important_files() {
    if ( !is_admin() && !is_user_logged_in() ) {
        $blocked_files = array( '.htaccess', 'wp-config.php' );
        foreach ( $blocked_files as $file ) {
            if ( file_exists( ABSPATH . $file ) ) {
                @chmod( ABSPATH . $file, 0644 );
            }
        }
    }
}
add_action('init', 'protect_important_files');

/* PROTECTS USERS FOR BEING NUMBERED */
if (!is_admin()) {
    add_action('init', 'block_user_enum');
    function block_user_enum() {
        if (!empty($_GET['author'])) {
            $author_id = absint($_GET['author']);
            if ($author_id && eh_is_admin_user($author_id)) {
                wp_redirect(site_url());
                exit;
            }
        }
    }
}



/**
 * Seguridad: ocultar usuarios en URLs y en la REST API
 */

/**
 * Utilidades de comprobación de administradores
 */
function eh_is_admin_user($user_id) {
    $user = get_userdata($user_id);
    return $user && user_can($user, 'manage_options');
}

function eh_get_admin_user_ids() {
    return get_users(array(
        'role'   => 'Administrator',
        'fields' => 'ID',
    ));
}

/**
 * 1) Bloquear archivos de autor y ?author= (URL públicas) solo si el autor es admin
 */
add_action('template_redirect', function () {
    if (is_admin()) {
        return;
    }

    // Bloquear archivo de autor: /author/xxx/
    if (is_author()) {
        $author = get_queried_object();
        if ($author instanceof WP_User && user_can($author, 'manage_options')) {
            wp_redirect(home_url('/'), 301);
            exit;
        }
    }

    // Bloquear enumeración tipo ?author=1 solo si ese autor es admin
    if (isset($_GET['author']) && $_GET['author'] !== '') {
        $author_id = absint($_GET['author']);
        if ($author_id && eh_is_admin_user($author_id)) {
            wp_redirect(home_url('/'), 301);
            exit;
        }
    }
});

/**
 * 2) Añadir meta noindex a archivos de autor (por si algún plugin los muestra)
 */
add_action('wp_head', function () {
    if (is_author()) {
        $author = get_queried_object();
        if ($author instanceof WP_User && user_can($author, 'manage_options')) {
            echo '<meta name="robots" content="noindex,nofollow" />' . "\n";
        }
    }
});

/**
 * 3) Ocultar administradores en la REST API para visitantes
 */
add_filter('rest_user_query', function ($args, $request) {
    if (!is_user_logged_in()) {
        $admin_ids = eh_get_admin_user_ids();
        if (!empty($admin_ids)) {
            $args['exclude'] = array_merge((array) ($args['exclude'] ?? array()), $admin_ids);
        }
    }
    return $args;
}, 10, 2);

add_filter('rest_pre_dispatch', function ($result, $server, $request) {
    if (!is_user_logged_in() && preg_match('#^/wp/v2/users/(\d+)$#', $request->get_route(), $matches)) {
        $user_id = absint($matches[1]);
        if ($user_id && eh_is_admin_user($user_id)) {
            return new WP_Error('rest_forbidden', 'No permission to view this user.', array('status' => 403));
        }
    }
    return $result;
}, 10, 3);

/**
 * 4) Quitar información de autor en las respuestas de posts/páginas de la REST API solo si el autor es admin
 */
function eh_ocultar_author_en_rest($response, $post, $request) {
    // Si está logueado y quieres que vea todo, comenta estas 2 líneas
    if (is_user_logged_in()) {
        return $response;
    }

    $author_id = isset($post->post_author) ? absint($post->post_author) : 0;
    if (!eh_is_admin_user($author_id)) {
        return $response;
    }

    // Quitar campo "author" del data
    $data = $response->get_data();
    if (isset($data['author'])) {
        unset($data['author']);
    }
    $response->set_data($data);

    // Quitar link de "author" en _links
    if (method_exists($response, 'remove_link')) {
        $response->remove_link('author');
    }

    return $response;
}
add_filter('rest_prepare_post',  'eh_ocultar_author_en_rest', 10, 3);
add_filter('rest_prepare_page',  'eh_ocultar_author_en_rest', 10, 3);
// Si usas CPTs vía REST, puedes añadir filtros similares para cada tipo

/**
 * 5) Quitar author_name y author_url de respuestas oEmbed solo si el autor es admin
 */
add_filter('oembed_response_data', function ($data, $post, $width, $height) {
    if (!eh_is_admin_user(isset($post->post_author) ? absint($post->post_author) : 0)) {
        return $data;
    }

    unset($data['author_name'], $data['author_url']);
    return $data;
}, 10, 4);



/**
 * Open Graph Meta Tags Básicas
 * Añade etiquetas OG básicas al head para mejorar compartición en redes sociales.
 */
add_action('wp_head', function () {
    if (is_admin()) return;

    $site_name = get_bloginfo('name');
    $site_desc = get_bloginfo('description');

    $title = wp_get_document_title();
    $desc  = $site_desc;

    // URL actual (para og:url)
    $scheme = is_ssl() ? 'https://' : 'http://';
    $current_url = $scheme . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? '');
    $current_url = esc_url($current_url);

    // Detectar qué ID usar para traer "imagen destacada"
    $post_id = 0;

    if (is_front_page()) {
        // Página asignada como portada
        $post_id = (int) get_option('page_on_front');
    } elseif (is_home()) {
        // Página asignada como "Página de entradas" (blog)
        $post_id = (int) get_option('page_for_posts');
    } elseif (is_singular()) {
        // Cualquier página/post/CPT
        $post_id = (int) get_queried_object_id();
    }

    // Descripción para singular (si quieres que sea más específica)
    if ($post_id && is_singular()) {
        if (has_excerpt($post_id)) {
            $desc = get_the_excerpt($post_id);
        } else {
            $content = get_post_field('post_content', $post_id);
            $content = wp_strip_all_tags(strip_shortcodes($content));
            $desc = mb_substr(trim($content), 0, 160);
            if ($desc === '') $desc = $site_desc;
        }
    }

    // SOLO imagen destacada (si no hay, no imprime og:image)
    $img = '';
    if ($post_id && has_post_thumbnail($post_id)) {
        $img = get_the_post_thumbnail_url($post_id, 'full');
    }

    echo "\n<meta property=\"og:site_name\" content=\"" . esc_attr($site_name) . "\" />\n";
    echo "<meta property=\"og:title\" content=\"" . esc_attr($title) . "\" />\n";
    echo "<meta property=\"og:description\" content=\"" . esc_attr(wp_strip_all_tags($desc)) . "\" />\n";
    echo "<meta property=\"og:url\" content=\"" . esc_url($current_url) . "\" />\n";
    echo "<meta property=\"og:type\" content=\"" . (is_singular() ? "article" : "website") . "\" />\n";

    if (!empty($img)) {
        echo "<meta property=\"og:image\" content=\"" . esc_url($img) . "\" />\n";
        echo "<meta name=\"twitter:card\" content=\"summary_large_image\" />\n";
    }
}, 5);

// PASS SITE URL TO JS
function site_url_js() {
    $site_url = home_url();
    $is_front = is_front_page() ? 'true' : 'false';
    ?>
    <script type="text/javascript">
        var site_url = "<?php echo esc_url($site_url); ?>";
        var is_home = <?php echo $is_front; ?>;
    </script>
    <?php
}
add_action('wp_head', 'site_url_js');   

/* START CODING FROM HERE */




