<?php
/**
 * Munresa Admin
 *
 * Funciones administrativas personalizadas:
 * - Rol Promo Manager
 * - Acceso limitado al admin
 * - Menús independientes: Leads, Novedades y Promociones
 * - URLs limpias visuales: /admin, /admin/novedades, /admin/promociones
 */

if (!defined('ABSPATH')) {
    exit;
}

require_once __DIR__ . '/munresa-novedades.php';
require_once __DIR__ . '/munresa-promociones.php';

/* =========================================================
 * CREAR / ACTUALIZAR ROLE: PROMO MANAGER
 * ========================================================= */

function munresa_admin_create_roles() {

    $capabilities = array(
        'read'       => true,
        'edit_posts' => true,
        'edit_users' => true,
        'flamingo_edit_contacts'             => true,
        'flamingo_edit_contact'              => true,
        'flamingo_edit_inbound_messages'     => true,
        'flamingo_edit_inbound_message'      => true,
        'flamingo_delete_inbound_messages'   => true,
        'flamingo_delete_inbound_message'    => true,
        'flamingo_spam_inbound_messages'     => true,
        'flamingo_unspam_inbound_messages'   => true,

        /*
         * Capacidad personalizada general.
         */
        'manage_munresa_promos' => true,

        /*
         * Capacidades para Novedades.
         */
        'edit_munresa_novedad'               => true,
        'read_munresa_novedad'               => true,
        'delete_munresa_novedad'             => true,
        'edit_munresa_novedades'             => true,
        'edit_others_munresa_novedades'      => true,
        'publish_munresa_novedades'          => true,
        'read_private_munresa_novedades'     => true,
        'delete_munresa_novedades'           => true,
        'delete_private_munresa_novedades'   => true,
        'delete_published_munresa_novedades' => true,
        'delete_others_munresa_novedades'    => true,
        'edit_private_munresa_novedades'     => true,
        'edit_published_munresa_novedades'   => true,

        /*
         * Capacidades para Promociones.
         */
        'edit_munresa_promocion'                 => true,
        'read_munresa_promocion'                 => true,
        'delete_munresa_promocion'               => true,
        'edit_munresa_promociones'               => true,
        'edit_others_munresa_promociones'        => true,
        'publish_munresa_promociones'            => true,
        'read_private_munresa_promociones'       => true,
        'delete_munresa_promociones'             => true,
        'delete_private_munresa_promociones'     => true,
        'delete_published_munresa_promociones'   => true,
        'delete_others_munresa_promociones'      => true,
        'edit_private_munresa_promociones'       => true,
        'edit_published_munresa_promociones'     => true,

        /*
         * Para imágenes destacadas y medios.
         */
        'upload_files' => true,
    );

    $promo_role = get_role('promo_manager');

    if (!$promo_role) {
        add_role(
            'promo_manager',
            'Promo Manager',
            array('read' => true)
        );

        $promo_role = get_role('promo_manager');
    }

    if ($promo_role) {
        foreach ($capabilities as $cap => $grant) {
            $promo_role->add_cap($cap, $grant);
        }
    }

    $admin_role = get_role('administrator');

    if ($admin_role) {
        foreach ($capabilities as $cap => $grant) {
            $admin_role->add_cap($cap, $grant);
        }
    }
}

add_action('init', 'munresa_admin_create_roles', 20);

/* =========================================================
 * CPT: NOVEDADES
 * ========================================================= */

add_action('init', 'munresa_register_novedades_cpt');

function munresa_register_novedades_cpt() {

    $labels = array(
        'name'               => 'Novedades',
        'singular_name'      => 'Novedad',
        'menu_name'          => 'Novedades',
        'add_new'            => 'Agregar nueva',
        'add_new_item'       => 'Agregar novedad',
        'edit_item'          => 'Editar novedad',
        'new_item'           => 'Nueva novedad',
        'view_item'          => 'Ver novedad',
        'search_items'       => 'Buscar novedades',
        'not_found'          => 'No se encontraron novedades',
        'not_found_in_trash' => 'No hay novedades en la papelera',
    );

    register_post_type('munresa_novedad', array(
        'labels'          => $labels,
        'public'          => true,
        'show_ui'         => true,
        'show_in_menu'    => true,
        'show_in_rest'    => true,
        'menu_position'   => 26,
        'menu_icon'       => 'dashicons-megaphone',
        'has_archive'     => false,
        'rewrite'         => array('slug' => 'novedades'),
        'supports'        => array('title', 'editor', 'thumbnail', 'excerpt'),
        'capability_type' => array('munresa_novedad', 'munresa_novedades'),
        'map_meta_cap'    => true,
    ));
}

/* =========================================================
 * CPT: PROMOCIONES
 * ========================================================= */

add_action('init', 'munresa_register_promociones_cpt');

function munresa_register_promociones_cpt() {

    $labels = array(
        'name'               => 'Promociones',
        'singular_name'      => 'Promoción',
        'menu_name'          => 'Promociones',
        'add_new'            => 'Agregar nueva',
        'add_new_item'       => 'Agregar promoción',
        'edit_item'          => 'Editar promoción',
        'new_item'           => 'Nueva promoción',
        'view_item'          => 'Ver promoción',
        'search_items'       => 'Buscar promociones',
        'not_found'          => 'No se encontraron promociones',
        'not_found_in_trash' => 'No hay promociones en la papelera',
    );

    register_post_type('munresa_promocion', array(
        'labels'          => $labels,
        'public'          => true,
        'show_ui'         => true,
        'show_in_menu'    => true,
        'show_in_rest'    => true,
        'menu_position'   => 27,
        'menu_icon'       => 'dashicons-tag',
        'has_archive'     => false,
        'rewrite'         => array('slug' => 'promociones'),
        'supports'        => array('title', 'editor', 'thumbnail', 'excerpt'),
        'capability_type' => array('munresa_promocion', 'munresa_promociones'),
        'map_meta_cap'    => true,
    ));
}

/* =========================================================
 * RENOMBRAR MENÚS
 * Flamingo -> Leads
 * Contacto / CF7 -> Forms
 * ========================================================= */

add_action('admin_menu', 'munresa_rename_admin_menus', 99999);

function munresa_rename_admin_menus() {
    global $menu, $submenu;

    if (!empty($menu) && is_array($menu)) {
        foreach ($menu as $key => $item) {
            $slug  = isset($item[2]) ? $item[2] : '';
            $title = isset($item[0]) ? wp_strip_all_tags($item[0]) : '';

            if ($slug === 'flamingo' || $slug === 'flamingo_inbound' || stripos($title, 'Flamingo') !== false) {
                $menu[$key][0] = 'Leads';
            }

            if ($slug === 'wpcf7' || stripos($title, 'Contacto') !== false || stripos($title, 'Contact') !== false) {
                $menu[$key][0] = 'Forms';
            }
        }
    }

    if (!empty($submenu['flamingo']) && is_array($submenu['flamingo'])) {
        foreach ($submenu['flamingo'] as $key => $item) {
            $slug  = isset($item[2]) ? $item[2] : '';
            $title = isset($item[0]) ? wp_strip_all_tags($item[0]) : '';

            if ($slug === 'flamingo_inbound' || stripos($title, 'Inbound') !== false || stripos($title, 'Messages') !== false || stripos($title, 'Mensajes') !== false) {
                $submenu['flamingo'][$key][0] = 'Leads recibidos';
            }

            if ($slug === 'flamingo' || stripos($title, 'Address Book') !== false || stripos($title, 'Libreta') !== false) {
                $submenu['flamingo'][$key][0] = 'Contactos';
            }
        }
    }
}

/* =========================================================
 * LIMITAR MENÚS PARA PROMO MANAGER
 * Solo debe ver:
 * - Leads / Flamingo real
 * - Novedades
 * - Promociones
 * ========================================================= */

add_action('admin_menu', 'munresa_admin_limit_promo_manager_menu', 999999);

function munresa_admin_limit_promo_manager_menu() {

    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    global $menu, $submenu;

    /*
     * Mantener solo los menús reales permitidos.
     * Flamingo debe quedarse como menú real.
     */
    $allowed_top_menus = array(
		'flamingo',
		'flamingo_inbound',
		'munresa-novedades',
		'munresa-promociones',
	);

    if (!empty($menu) && is_array($menu)) {
        foreach ($menu as $item) {
            $slug = isset($item[2]) ? $item[2] : '';

            if (!in_array($slug, $allowed_top_menus, true)) {
                remove_menu_page($slug);
            }
        }
    }

    /*
     * Flamingo real:
     * mantener Contactos y Leads recibidos.
     */
    $flamingo_parents = array('flamingo', 'flamingo_inbound');

    foreach ($flamingo_parents as $parent_slug) {
        if (!empty($submenu[$parent_slug]) && is_array($submenu[$parent_slug])) {
            foreach ($submenu[$parent_slug] as $key => $item) {
                $slug = isset($item[2]) ? $item[2] : '';

                if (!in_array($slug, array('flamingo', 'flamingo_inbound'), true)) {
                    unset($submenu[$parent_slug][$key]);
                }
            }
        }
    }

    /*
     * Quitar submenús Agregar nueva de Novedades y Promociones.
     */
    remove_submenu_page(
        'edit.php?post_type=munresa_promocion',
        'post-new.php?post_type=munresa_promocion'
    );
}

/* =========================================================
 * BLOQUEAR ACCESO A PANTALLAS NO PERMITIDAS
 * ========================================================= */

add_action('admin_init', 'munresa_admin_restrict_promo_manager_pages');

function munresa_admin_restrict_promo_manager_pages() {

    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    global $pagenow;

    $post_type = isset($_GET['post_type']) ? sanitize_key($_GET['post_type']) : '';
    $page      = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';

    /*
     * Permitir Ajax, medios y perfil.
     */
    if ((defined('DOING_AJAX') && DOING_AJAX) || $pagenow === 'async-upload.php' || $pagenow === 'media-upload.php') {
        return;
    }

    if ($pagenow === 'profile.php') {
        return;
    }

    /*
     * Dashboard WP: enviar al dashboard limpio.
     */
    if ($pagenow === 'index.php') {
        wp_safe_redirect(home_url('/admin/'));
        exit;
    }

    $allowed = false;

    /*
     * Menús propios.
     */
    if ($pagenow === 'admin.php' && in_array($page, array(
		'munresa-leads',
		'munresa-contactos',
		'munresa-novedades',
		'munresa-promociones',
	), true)) {
		$allowed = true;
	}

    /*
     * Pantallas reales de Flamingo.
     */
    if ($pagenow === 'admin.php' && in_array($page, array('flamingo', 'flamingo_inbound'), true)) {
        $allowed = true;
    }

    /*
     * Novedades y Promociones.
     */
    if ($pagenow === 'edit.php' && in_array($post_type, array('munresa_novedad', 'munresa_promocion'), true)) {
        $allowed = true;
    }

    if ($pagenow === 'post-new.php' && in_array($post_type, array('munresa_novedad', 'munresa_promocion'), true)) {
        $allowed = true;
    }

    if ($pagenow === 'post.php' && isset($_GET['post'])) {
        $post_id = absint($_GET['post']);

        if ($post_id) {
            $current_post_type = get_post_type($post_id);

            if (in_array($current_post_type, array('munresa_novedad', 'munresa_promocion'), true)) {
                $allowed = true;
            }
        }
    }

    if ($pagenow === 'post.php' && isset($_POST['post_type'])) {
        $posted_post_type = sanitize_key(wp_unslash($_POST['post_type']));

        if (in_array($posted_post_type, array('munresa_novedad', 'munresa_promocion'), true)) {
            $allowed = true;
        }
    }

    if (!$allowed) {
        wp_safe_redirect(home_url('/admin/'));
        exit;
    }
}

/* =========================================================
 * URLS LIMPIAS
 * /admin
 * /admin/leads
 * /admin/novedades
 * /admin/promociones
 * ========================================================= */

add_action('init', 'munresa_admin_add_admin_rewrite');

function munresa_admin_add_admin_rewrite() {
    add_rewrite_rule(
        '^admin/?$',
        'index.php?munresa_admin_view=dashboard',
        'top'
    );

    add_rewrite_rule(
        '^admin/leads/?$',
        'index.php?munresa_admin_view=leads',
        'top'
    );

    add_rewrite_rule(
        '^admin/contactos/?$',
        'index.php?munresa_admin_view=contactos',
        'top'
    );

    add_rewrite_rule(
        '^admin/novedades/?$',
        'index.php?munresa_admin_view=novedades',
        'top'
    );

    add_rewrite_rule(
        '^admin/promociones/?$',
        'index.php?munresa_admin_view=promociones',
        'top'
    );
}

add_filter('query_vars', 'munresa_admin_query_vars');

function munresa_admin_query_vars($vars) {
    $vars[] = 'munresa_admin_view';
    return $vars;
}

add_action('template_redirect', 'munresa_admin_handle_clean_urls');

function munresa_admin_handle_clean_urls() {
    $view = get_query_var('munresa_admin_view');

    if (empty($view)) {
        return;
    }

    if (!is_user_logged_in()) {
        wp_safe_redirect(wp_login_url(home_url('/admin/')));
        exit;
    }

    if ($view === 'dashboard') {
        munresa_admin_render_dashboard();
        exit;
    }

    if ($view === 'leads') {
        wp_safe_redirect(admin_url('admin.php?page=flamingo_inbound'));
        exit;
    }

    if ($view === 'contactos') {
        wp_safe_redirect(admin_url('admin.php?page=flamingo'));
        exit;
    }

    if ($view === 'novedades') {
        wp_safe_redirect(admin_url('admin.php?page=munresa-novedades'));
        exit;

        wp_die('El módulo de Novedades no está disponible.');
    }

    if ($view === 'promociones') {
		wp_safe_redirect(admin_url('admin.php?page=munresa-promociones'));
		exit;
	}
}

/* =========================================================
 * DASHBOARD LIMPIO PARA /admin
 * ========================================================= */

function munresa_admin_render_dashboard() {
    $logo_url = 'https://newsite.munresa.com/wp-content/uploads/2026/06/cropped-Iso-Munresa.jpg';

    $user = wp_get_current_user();
    $name = !empty($user->first_name) ? $user->first_name : 'Fernando';

    ?>
    <!DOCTYPE html>
    <html <?php language_attributes(); ?>>
    <head>
        <meta charset="<?php bloginfo('charset'); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Admin Munresa</title>
        <?php wp_head(); ?>
        <style>
            body {
                margin: 0;
                min-height: 100vh;
                background: #f4f7fb;
                font-family: Arial, Helvetica, sans-serif;
                color: #1f2933;
            }

            .munresa-dashboard {
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 30px;
                box-sizing: border-box;
            }

            .munresa-dashboard-card {
                width: 100%;
                max-width: 620px;
                background: #ffffff;
                border-radius: 18px;
                padding: 38px 34px;
                text-align: center;
                box-shadow: 0 18px 50px rgba(0, 0, 0, 0.10);
                border-top: 6px solid #046BD2;
            }

            .munresa-dashboard-logo {
                width: 90px;
                height: 90px;
                object-fit: contain;
                margin-bottom: 18px;
            }

            .munresa-dashboard h1 {
                margin: 0 0 8px;
                color: #046BD2;
                font-size: 32px;
                line-height: 1.1;
            }

            .munresa-dashboard p {
                margin: 0 0 26px;
                color: #555;
                font-size: 16px;
            }

            .munresa-dashboard-actions {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
            }

            .munresa-dashboard-actions a {
                display: block;
                padding: 15px 12px;
                background: #046BD2;
                color: #ffffff;
                text-decoration: none;
                border-radius: 10px;
                font-weight: 700;
                transition: all 0.2s ease;
            }

            .munresa-dashboard-actions a:hover {
                background: #E43337;
                color: #ffffff;
                transform: translateY(-1px);
            }

            .munresa-dashboard-logout {
                display: inline-block;
                margin-top: 24px;
                color: #E43337;
                text-decoration: none;
                font-weight: 700;
            }

            @media (max-width: 640px) {
                .munresa-dashboard-actions {
                    grid-template-columns: 1fr;
                }

                .munresa-dashboard-card {
                    padding: 30px 22px;
                }

                .munresa-dashboard h1 {
                    font-size: 27px;
                }
            }
        </style>
    </head>
    <body>
        <main class="munresa-dashboard">
            <section class="munresa-dashboard-card">
                <img class="munresa-dashboard-logo" src="<?php echo esc_url($logo_url); ?>" alt="Munresa">

                <h1>Bienvenido <?php echo esc_html($name); ?></h1>
                <p>Panel de administración Munresa</p>

                <div class="munresa-dashboard-actions">
                    <a href="<?php echo esc_url(home_url('/admin/leads/')); ?>">Leads</a>
                    <a href="<?php echo esc_url(home_url('/admin/novedades/')); ?>">Novedades</a>
                    <a href="<?php echo esc_url(home_url('/admin/promociones/')); ?>">Promociones</a>
                </div>

                <a class="munresa-dashboard-logout" href="<?php echo esc_url(wp_logout_url(home_url('/admin/'))); ?>">
                    Cerrar sesión
                </a>
            </section>
        </main>
        <?php wp_footer(); ?>
    </body>
    </html>
    <?php
}

/* =========================================================
 * URL LIMPIA VISUAL + LINKS DEL MENÚ
 * ========================================================= */

add_action('admin_footer', 'munresa_admin_clean_url_script', 999);

function munresa_admin_clean_url_script() {
    global $pagenow;

    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    $post_type = isset($_GET['post_type']) ? sanitize_key($_GET['post_type']) : '';
    $page      = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';

    $clean_url = '';

    if ($pagenow === 'admin.php' && in_array($page, array('flamingo_inbound'), true)) {
        $clean_url = home_url('/admin/leads/');
    }

    if ($pagenow === 'admin.php' && in_array($page, array('flamingo'), true)) {
        $clean_url = home_url('/admin/contactos/');
    }

    if ($pagenow === 'admin.php' && $page === 'munresa-novedades') {
        $clean_url = home_url('/admin/novedades/');
    }

    if ($pagenow === 'admin.php' && $page === 'munresa-promociones') {
		$clean_url = home_url('/admin/promociones/');
	}
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const cleanLinks = {
    '<?php echo esc_js(admin_url('admin.php?page=flamingo_inbound')); ?>': '<?php echo esc_js(home_url('/admin/leads/')); ?>',
    '<?php echo esc_js(admin_url('admin.php?page=flamingo')); ?>': '<?php echo esc_js(home_url('/admin/contactos/')); ?>',
    '<?php echo esc_js(admin_url('admin.php?page=munresa-novedades')); ?>': '<?php echo esc_js(home_url('/admin/novedades/')); ?>',
    '<?php echo esc_js(admin_url('admin.php?page=munresa-promociones')); ?>': '<?php echo esc_js(home_url('/admin/promociones/')); ?>'
};

        document.querySelectorAll('#adminmenu a').forEach(function(link) {
            Object.keys(cleanLinks).forEach(function(realUrl) {
                if (link.href === realUrl) {
                    link.href = cleanLinks[realUrl];
                }
            });
        });

        <?php if (!empty($clean_url)) : ?>
        if (window.history && window.history.replaceState) {
            window.history.replaceState(null, document.title, '<?php echo esc_js($clean_url); ?>');
        }
        <?php endif; ?>
    });
    </script>
    <?php
}

/* =========================================================
 * ADMIN BAR PARA PROMO MANAGER
 * Se mantiene visible en wp-admin, pero limpio.
 * Se oculta solo en el frontend.
 * ========================================================= */

add_action('after_setup_theme', 'munresa_admin_bar_for_promo_manager');

function munresa_admin_bar_for_promo_manager() {
    if (munresa_admin_is_promo_manager() && !is_admin()) {
        show_admin_bar(false);
    }
}

/* =========================================================
 * LIMPIAR ADMIN BAR Y PANTALLA PARA PROMO MANAGER
 * ========================================================= */

add_action('wp_before_admin_bar_render', 'munresa_clean_promo_manager_admin_bar', 999);

function munresa_clean_promo_manager_admin_bar() {
    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    global $wp_admin_bar;

    if (!is_object($wp_admin_bar)) {
        return;
    }

    /*
     * Eliminar elementos extra de la barra superior.
     */
    $nodes_to_remove = array(
        'about',
        'wporg',
        'documentation',
        'support-forums',
        'feedback',
        'updates',
        'comments',
        'new-content',
        'new-post',
        'new-media',
        'new-page',
        'new-user',
        'search',
        'customize',
        'edit',
        'view',
        'view-site',
        'wpseo-menu',
        'yoast-seo',
        'autoptimize',
        'query-monitor',
        'wp-mail-smtp-menu',
    );

    foreach ($nodes_to_remove as $node) {
        $wp_admin_bar->remove_node($node);
    }

    /*
     * Logo Munresa.
     */
    $wp_admin_bar->add_node(array(
        'id'    => 'wp-logo',
        'title' => '<span class="mdo-admin-logo"></span>',
        'href'  => home_url('/admin/'),
        'meta'  => array(
            'title' => 'Munresa'
        )
    ));

    /*
     * Link principal a la web.
     */
    $wp_admin_bar->add_node(array(
        'id'    => 'site-name',
        'title' => 'newsite.munresa.com',
        'href'  => home_url('/'),
        'meta'  => array(
            'title' => 'Ir al sitio web'
        )
    ));

    /*
     * Mantener usuario / perfil.
     * El usuario puede editar su propio perfil.
     */
    $wp_admin_bar->add_node(array(
        'id'    => 'edit-profile',
        'title' => 'Editar perfil',
        'href'  => admin_url('profile.php'),
        'parent'=> 'user-actions'
    ));
}

/* =========================================================
 * OCULTAR OPCIONES DE PANTALLA Y AYUDA
 * ========================================================= */

add_filter('screen_options_show_screen', 'munresa_hide_screen_options_for_promo_manager');

function munresa_hide_screen_options_for_promo_manager($show_screen) {
    if (munresa_admin_is_promo_manager()) {
        return false;
    }

    return $show_screen;
}

add_action('admin_head', 'munresa_hide_help_tab_for_promo_manager');

function munresa_hide_help_tab_for_promo_manager() {
    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    $screen = get_current_screen();

    if ($screen) {
        $screen->remove_help_tabs();
        $screen->set_help_sidebar('');
    }

    ?>
    <style>
        #screen-meta-links,
        #contextual-help-link-wrap,
        #screen-options-link-wrap,
        #wp-admin-bar-search,
        #wp-admin-bar-comments,
        #wp-admin-bar-new-content,
        #wp-admin-bar-wpseo-menu,
        #wp-admin-bar-updates {
            display: none !important;
        }

        body.wp-admin #wpadminbar #wp-admin-bar-wp-logo > .ab-item {
            width: 34px !important;
            padding: 0 !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        body.wp-admin #wpadminbar #wp-admin-bar-site-name > .ab-item {
            font-weight: 700 !important;
        }

        body.wp-admin #wpadminbar #wp-admin-bar-my-account > .ab-item {
            padding-right: 12px !important;
        }
    </style>
    <?php
}

/* =========================================================
 * LIMPIAR DASHBOARD WIDGETS PARA PROMO MANAGER
 * ========================================================= */

add_action('wp_dashboard_setup', 'munresa_remove_dashboard_widgets_for_promo_manager', 999);

function munresa_remove_dashboard_widgets_for_promo_manager() {
    if (!munresa_admin_is_promo_manager()) {
        return;
    }

    global $wp_meta_boxes;

    $wp_meta_boxes['dashboard'] = array();
}

/* =========================================================
 * PERMISOS REFORZADOS FLAMINGO PARA PROMO MANAGER
 * Permite acceder a Contactos y Leads recibidos de Flamingo
 * sin convertir al usuario en administrador.
 * ========================================================= */

add_filter('user_has_cap', 'munresa_grant_flamingo_caps_to_promo_manager', 20, 4);

function munresa_grant_flamingo_caps_to_promo_manager($allcaps, $caps, $args, $user) {
    if (empty($user) || empty($user->roles)) {
        return $allcaps;
    }

    if (!in_array('promo_manager', (array) $user->roles, true)) {
        return $allcaps;
    }

    /*
     * Permisos necesarios para que Flamingo funcione correctamente.
     * edit_users es requerido por Flamingo en algunas instalaciones.
     * El acceso a Usuarios, Plugins, Ajustes, etc. sigue bloqueado
     * por munresa_admin_restrict_promo_manager_pages().
     */
    $caps_to_grant = array(
        'read',
        'edit_posts',
        'edit_users',
        'upload_files',

        'flamingo_edit_contacts',
        'flamingo_edit_contact',
        'flamingo_delete_contacts',
        'flamingo_delete_contact',

        'flamingo_edit_inbound_messages',
        'flamingo_edit_inbound_message',
        'flamingo_delete_inbound_messages',
        'flamingo_delete_inbound_message',
        'flamingo_spam_inbound_messages',
        'flamingo_spam_inbound_message',
        'flamingo_unspam_inbound_messages',
        'flamingo_unspam_inbound_message',
    );

    foreach ($caps_to_grant as $cap) {
        $allcaps[$cap] = true;
    }

    return $allcaps;
}

/* =========================================================
 * LIMPIAR FOOTER DEL ADMIN WORDPRESS
 * Elimina:
 * - Gracias por crear con WordPress
 * - Versión de WordPress
 * ========================================================= */

add_filter('admin_footer_text', 'munresa_clean_admin_footer_text', 999);

function munresa_clean_admin_footer_text($text) {
    return '';
}

add_filter('update_footer', 'munresa_clean_admin_update_footer', 999);

function munresa_clean_admin_update_footer($text) {
    return '';
}

/* =========================================================
 * HELPER: VALIDAR ROLE PROMO MANAGER
 * IMPORTANTE:
 * Si el usuario es administrador, nunca se limita el acceso.
 * ========================================================= */

function munresa_admin_is_promo_manager() {
    if (!is_user_logged_in()) {
        return false;
    }

    $user = wp_get_current_user();

    /*
     * Si es administrador real, nunca se limita.
     * No usamos current_user_can('manage_options') porque ese permiso
     * se puede dar temporalmente para que Flamingo funcione.
     */
    if (in_array('administrator', (array) $user->roles, true)) {
        return false;
    }

    if (is_multisite() && is_super_admin($user->ID)) {
        return false;
    }

    return in_array('promo_manager', (array) $user->roles, true);
}