<?php
/**
 * Plugin Name: Munresa Plan
 * Plugin URI: https://munresa.com
 * Description: Funciones personalizadas para Munresa: redirecciones de formularios CF7 a páginas de gracias, enlaces rápidos a WhatsApp, redirecciones internas y personalización del admin.
 * Version: 1.0.0
 * Author: Munresa
 * Text Domain: munresa-plan
 */

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

/* =========================================================
 * CARGAR ARCHIVOS DEL PLUGIN
 * ========================================================= */

$munresa_admin_file = plugin_dir_path(__FILE__) . 'munresa-admin.php';

if (file_exists($munresa_admin_file)) {
    require_once $munresa_admin_file;
}

/* =========================================================
 * CONFIGURACIÓN GENERAL
 * ========================================================= */

function munresa_get_whatsapp_number() {
    return '50685434040';
}

function munresa_get_whatsapp_messages() {
    return array(
        'repuestos'       => 'Hola Munresa, quiero cotizar un repuesto para mi vehículo europeo.',
        'compensadores'   => 'Hola Munresa, quiero cotizar compensadores para mi vehículo.',
        'contacto'        => 'Hola Munresa, vengo desde la web y quiero recibir ayuda para cotizar un repuesto.',
        'pedido' 		  => 'Hola Munresa, quiero cotizar un repuesto para mi vehículo europeo. Marca: [MARCA] | Modelo: [MODELO] | Año: [AÑO] | Repuesto: [DESCRIPCIÓN]',
    );
}

function munresa_get_custom_redirects() {
    return array(
        'historia' => '/nosotros/',
        'wa'       => '/wa/repuestos/',
    );
}

/* =========================================================
 * REDIRECCIÓN THANK YOU PAGE PARA CONTACT FORM 7
 * ========================================================= */

add_action('wp_footer', 'munresa_cf7_thank_you_redirect_script');

function munresa_cf7_thank_you_redirect_script() {
    if (is_admin()) {
        return;
    }

    $home_url = esc_url(home_url('/'));
    ?>
    <script>
    document.addEventListener('wpcf7mailsent', function() {
        const currentUrl = window.location.href.toLowerCase();
        const homeUrl = "<?php echo $home_url; ?>";

        let redirectPath = "gracias-repuestos/";

        const redirectRules = {
            "compensadores": "gracias-compensadores/",
            "repuestos": "gracias-repuestos/",
            "cotiza": "gracias-repuestos/",
            "productos": "gracias-repuestos/"
        };

        for (const key in redirectRules) {
            if (currentUrl.includes(key)) {
                redirectPath = redirectRules[key];
                break;
            }
        }

        setTimeout(function() {
            window.location.href = homeUrl + redirectPath;
        }, 1200);
    }, false);
    </script>
    <?php
}

/* =========================================================
 * ENLACES DINÁMICOS WHATSAPP
 * Ejemplo:
 * munresa.com/wa/repuestos
 * munresa.com/wa/compensadores
 * munresa.com/wa/contacto
 * ========================================================= */

add_action('init', 'munresa_add_whatsapp_rewrite_rule');

function munresa_add_whatsapp_rewrite_rule() {
    add_rewrite_rule(
        '^wa/([^/]*)/?$',
        'index.php?munresa_wa_service=$matches[1]',
        'top'
    );
}

add_filter('query_vars', 'munresa_register_query_vars');

function munresa_register_query_vars($vars) {
    $vars[] = 'munresa_wa_service';
    return $vars;
}

add_action('template_redirect', 'munresa_handle_whatsapp_redirect');

function munresa_handle_whatsapp_redirect() {
    if (is_admin()) {
        return;
    }

    $service = get_query_var('munresa_wa_service');

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

    $service  = sanitize_key($service);
    $messages = munresa_get_whatsapp_messages();

    if (!isset($messages[$service])) {
        $service = 'repuestos';
    }

    $phone        = munresa_get_whatsapp_number();
    $message      = rawurlencode($messages[$service]);
    $whatsapp_url = 'https://wa.me/' . $phone . '?text=' . $message;

    wp_redirect($whatsapp_url, 302);
    exit;
}

/* =========================================================
 * REDIRECCIONES INTERNAS PERSONALIZADAS
 * Ejemplo:
 * munresa.com/historia -> munresa.com/nosotros/
 * ========================================================= */

add_action('template_redirect', 'munresa_handle_custom_redirects', 1);

function munresa_handle_custom_redirects() {
    if (is_admin()) {
        return;
    }

    $redirects = munresa_get_custom_redirects();

    $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
    $current_path = trim(parse_url($request_uri, PHP_URL_PATH), '/');

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

    if (isset($redirects[$current_path])) {
        $target = home_url($redirects[$current_path]);

        wp_safe_redirect($target, 301);
        exit;
    }
}

/* =========================================================
 * PERSONALIZAR ADMIN WP - COLORES Y LOGO MUNRESA
 * Azul: #046BD2
 * Rojo: #E43337
 * ========================================================= */

add_action('admin_head', 'mdo_admin_branding_styles');
add_action('admin_bar_menu', 'mdo_replace_wp_logo', 999);

function mdo_get_admin_logo_url() {
    return 'https://newsite.munresa.com/wp-content/uploads/2026/06/cropped-Iso-Munresa.jpg';
}

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

    /*
     * No eliminamos el nodo wp-logo.
     * Solo cambiamos su contenido para que conserve la posición original.
     */
    $wp_admin_bar->add_node(array(
        'id'    => 'wp-logo',
        'title' => '<span class="mdo-admin-logo"></span>',
        'href'  => admin_url(),
        'meta'  => array(
            'title' => 'Munresa'
        )
    ));
}

function mdo_admin_branding_styles() {
    $logo_url = esc_url(mdo_get_admin_logo_url());
    ?>
    <style>
        :root {
            --munresa-blue: #046BD2;
            --munresa-blue-dark: #0354a5;
            --munresa-red: #E43337;
            --munresa-white: #ffffff;
        }

        /* Barra superior */
        #wpadminbar {
            background: var(--munresa-blue) !important;
        }

        #wpadminbar .ab-item,
        #wpadminbar a.ab-item,
        #wpadminbar .ab-icon:before,
        #wpadminbar .ab-item:before {
            color: var(--munresa-white) !important;
        }

        #wpadminbar:not(.mobile) .ab-top-menu > li:hover > .ab-item,
        #wpadminbar .ab-top-menu > li.hover > .ab-item {
            background: var(--munresa-blue-dark) !important;
            color: var(--munresa-white) !important;
        }

        /* Logo Munresa en lugar del logo/casita de WP */
        #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;
        }

        #wpadminbar #wp-admin-bar-wp-logo .ab-icon,
        #wpadminbar #wp-admin-bar-wp-logo .ab-icon:before {
            display: none !important;
            content: none !important;
        }

        #wpadminbar #wp-admin-bar-wp-logo .mdo-admin-logo {
            display: block !important;
            width: 24px !important;
            height: 24px !important;
            background-image: url('<?php echo $logo_url; ?>') !important;
            background-size: contain !important;
            background-position: center !important;
            background-repeat: no-repeat !important;
            border-radius: 50%;
        }

        /* Menú lateral */
        #adminmenuback,
        #adminmenuwrap,
        #adminmenu {
            background: var(--munresa-blue) !important;
        }

        #adminmenu a {
            color: var(--munresa-white) !important;
        }

        #adminmenu div.wp-menu-image:before {
            color: rgba(255,255,255,0.95) !important;
        }

        #adminmenu li.menu-top:hover,
        #adminmenu li.opensub > a.menu-top,
        #adminmenu li > a.menu-top:focus {
            background: var(--munresa-blue-dark) !important;
            color: var(--munresa-white) !important;
        }

        /* Menú activo */
        #adminmenu li.wp-has-current-submenu a.wp-has-current-submenu,
        #adminmenu li.current a.menu-top,
        #adminmenu .wp-menu-arrow {
            background: var(--munresa-red) !important;
            color: var(--munresa-white) !important;
        }

        /* Submenú en azul, no negro */
        #adminmenu .wp-submenu,
        #adminmenu .wp-has-current-submenu .wp-submenu,
        #adminmenu .wp-has-current-submenu.opensub .wp-submenu,
        #adminmenu a.wp-has-current-submenu:focus + .wp-submenu,
        .folded #adminmenu .wp-has-current-submenu .wp-submenu {
            background: var(--munresa-blue-dark) !important;
        }

        #adminmenu .wp-submenu a {
            color: rgba(255,255,255,0.92) !important;
        }

        #adminmenu .wp-submenu a:hover,
        #adminmenu .wp-submenu a:focus,
        #adminmenu .wp-submenu li.current a {
            background: rgba(228, 51, 55, 0.25) !important;
            color: var(--munresa-white) !important;
        }

        #adminmenu .awaiting-mod,
        #adminmenu .update-plugins {
            background: var(--munresa-red) !important;
            color: var(--munresa-white) !important;
        }

        #collapse-button,
        #collapse-button .collapse-button-icon:after {
            color: var(--munresa-white) !important;
        }

        #collapse-button:hover {
            background: var(--munresa-blue-dark) !important;
            color: var(--munresa-white) !important;
        }

        .wp-core-ui .button-primary {
            background: var(--munresa-red) !important;
            border-color: var(--munresa-red) !important;
            color: var(--munresa-white) !important;
        }

        .wp-core-ui .button-primary:hover,
        .wp-core-ui .button-primary:focus {
            background: #c9252b !important;
            border-color: #c9252b !important;
            color: var(--munresa-white) !important;
        }

        .wrap a,
        .wp-list-table a,
        .subsubsub a {
            color: var(--munresa-blue);
        }

        .wrap a:hover,
        .wp-list-table a:hover,
        .subsubsub a:hover {
            color: var(--munresa-red);
        }
    </style>
    <?php
}

/* =========================================================
 * ACTIVACIÓN Y DESACTIVACIÓN
 * ========================================================= */

register_activation_hook(__FILE__, 'munresa_plan_activate');

function munresa_plan_activate() {
    munresa_add_whatsapp_rewrite_rule();

    if (function_exists('munresa_admin_add_admin_rewrite')) {
        munresa_admin_add_admin_rewrite();
    }

    if (function_exists('munresa_admin_create_roles')) {
        munresa_admin_create_roles();
    }

    flush_rewrite_rules();
}

register_deactivation_hook(__FILE__, 'munresa_plan_deactivate');

function munresa_plan_deactivate() {
    flush_rewrite_rules();
}