/*
 Theme Name:   Organium Child
 Description:  Organium Child Theme
 Theme URI:	   https://organium.artureanec.com
 Author:       Artureanec
 Author URI:   https://demo.artureanec.com
 Template:     organium
 Version:      1.1.0
 License: GNU  General Public License version 3.0
 License URI:  http://www.gnu.org/licenses/gpl-3.0.html
 Text Domain:  organium-child
*/

/* =Theme customization starts here
------------------------------------------------------- */



<?php
/**
 * Casa Alonso — functions.php para tienda.casa-alonso.es
 *
 * INSTRUCCIONES:
 * 1. En WordPress ve a Apariencia → Editor de temas
 * 2. Selecciona "Tema hijo" (child theme) → functions.php
 * 3. Pega este código AL FINAL del archivo existente
 *
 * Si no tienes child theme, crea uno antes de editar functions.php
 * para que las actualizaciones del tema no borren tus cambios.
 */


// ═══════════════════════════════════════════════════════
//  1. REDIRIGIR LOGO AL DOMINIO PRINCIPAL
// ═══════════════════════════════════════════════════════
add_filter('get_custom_logo', function($html) {
    return str_replace(
        ['href="' . home_url('/') . '"', "href='" . home_url('/') . "'"],
        ['href="https://pensive-spence.5-250-188-44.plesk.page"',  "href='https://pensive-spence.5-250-188-44.plesk.page'"],
        $html
    );
});

// Por si el tema usa site_url en lugar de custom_logo
add_filter('home_url', function($url, $path, $scheme) {
    // Solo redirigir el home root — no afectar URLs internas de WC
    if ($path === '' || $path === '/') {
        return 'https://pensive-spence.5-250-188-44.plesk.page';
    }
    return $url;
}, 10, 3);


// ═══════════════════════════════════════════════════════
//  2. BLOQUEAR NAVEGACIÓN FUERA DE LA TIENDA
//     Solo permite: shop, producto, categoría, carrito,
//     checkout, mi cuenta y confirmación de pedido
// ═══════════════════════════════════════════════════════
add_action('template_redirect', function() {

    // Excluir peticiones de admin, AJAX, REST y cron
    if (is_admin() || wp_doing_ajax() || (defined('REST_REQUEST') && REST_REQUEST)) return;

    $allowed =
        is_shop() ||
        is_product() ||
        is_product_category() ||
        is_product_tag() ||
        is_cart() ||
        is_checkout() ||
        is_account_page() ||
        is_order_received_page() ||
        is_wc_endpoint_url();       // includes order-pay, add-payment-method, etc.

    if (!$allowed) {
        wp_redirect('https://pensive-spence.5-250-188-44.plesk.page', 302);
        exit;
    }
});


// ═══════════════════════════════════════════════════════
//  3. ELIMINAR HEADER Y FOOTER FUERA DE LO NECESARIO
//     (Agrega esto en Apariencia → Personalizar → CSS adicional
//      si prefieres no tocar PHP)
// ═══════════════════════════════════════════════════════
add_action('wp_head', function() {
    echo '<style>
        /* ── Ocultar elementos no-tienda ── */
        .site-header .site-navigation,
        .main-navigation,
        nav.navbar,
        #site-navigation,
        .header-search,
        .site-footer .footer-widgets,
        .footer-bottom-bar,
        #secondary,
        .widget-area,
        .breadcrumb:not(.woocommerce-breadcrumb),
        .page-header:not(.woocommerce) { display: none !important; }

        /* ── Logo apunta a landing ── */
        .custom-logo-link { cursor: pointer; }

        /* ── Branding mínimo en header ── */
        .site-branding { padding: 12px 0; }

        /* ── Quitar menú hamburguesa móvil ── */
        .menu-toggle { display: none !important; }
    </style>';
});


// ═══════════════════════════════════════════════════════
//  4. CORS PARA LA STORE API (WC 8.x)
//     Permite que www.casa-alonso.es llame a la Store API
// ═══════════════════════════════════════════════════════
add_action('rest_api_init', function() {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function($value) {
        $allowed_origins = [
            'https://www.pensive-spence.5-250-188-44.plesk.page',
            'https://pensive-spence.5-250-188-44.plesk.page',
        ];
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        if (in_array($origin, $allowed_origins, true)) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS');
            header('Access-Control-Allow-Headers: Content-Type, X-WC-Store-API-Nonce, Nonce, Cart-Token');
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Expose-Headers: X-WC-Store-API-Nonce, Nonce, Cart-Token');
        }
        return $value;
    });
}, 15);


// ═══════════════════════════════════════════════════════
//  5. QUITAR XMLRPC Y FEEDS (seguridad mínima)
// ═══════════════════════════════════════════════════════
add_filter('xmlrpc_enabled', '__return_false');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'wp_generator');  // Ocultar versión WP


// ═══════════════════════════════════════════════════════
//  6. PERSONALIZAR TEXTOS DE LA TIENDA (opcional)
// ═══════════════════════════════════════════════════════
add_filter('gettext', function($translated, $original, $domain) {
    if ($domain !== 'woocommerce') return $translated;
    $replacements = [
        'Cart'              => 'Cesta',
        'Proceed to checkout' => 'Finalizar pedido',
        'Return to shop'    => '← Volver a la tienda',
    ];
    return $replacements[$original] ?? $translated;
}, 10, 3);


// ═══════════════════════════════════════════════════════
//  7. AÑADIR ENLACE "VOLVER A CASA ALONSO" EN CHECKOUT
// ═══════════════════════════════════════════════════════
add_action('woocommerce_before_checkout_form', function() {
    echo '<p style="text-align:center; margin-bottom:20px;">
        <a href="https://pensive-spence.5-250-188-44.plesk.page" style="color:#6B8E23; font-size:0.9rem;">
            ← Volver a Casa Alonso
        </a>
    </p>';
});