<?php
/**
 * MenuX Free — Footer Renderer
 * Renders the footer via shortcode [menux_footer] (also reused by the Gutenberg block).
 * @package MenuX
 */

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

add_shortcode( 'menux_footer', 'menux_render_footer_shortcode' );

function menux_render_footer_shortcode( $atts = array() ) {
    $footer = wp_parse_args( get_option( 'menux_footer', array() ), menux_footer_defaults() );

    if ( ( $footer['enabled'] ?? '0' ) !== '1' || empty( $footer['columns'] ) ) {
        return '';
    }

    wp_enqueue_script( 'menux-frontend' );

    $networks = menux_footer_social_networks();
    $layout_raw = $footer['layout'] ?? 'wide-first';
    $layout     = in_array( $layout_raw, array( 'equal', 'wide-first', 'centered' ), true ) ? $layout_raw : 'wide-first';
    $cols      = array_slice( (array) $footer['columns'], 0, 6 );
    $ncols     = max( 1, count( $cols ) );
    $style_opt = wp_parse_args( get_option( 'menux_footer_style', array() ), menux_footer_style_defaults() );

    ob_start();
    ?>
    <footer class="menux-footer" role="contentinfo">
        <div class="menux-footer-inner">
            <div class="menux-footer-cols menux-flayout-<?php echo esc_attr( $layout ); ?>" style="--menux-fcols:<?php echo (int) $ncols; ?>;">
                <?php foreach ( $cols as $ci => $col ) :
                    $hide_class = ( ( $col['hide_mobile'] ?? '0' ) === '1' ) ? ' menux-fcol-hidden-mobile' : '';
                ?>
                <div class="menux-footer-col menux-fcol-<?php echo esc_attr( $col['type'] ?? 'links' ); echo esc_attr( $hide_class ); ?>">
                    <?php
                    if ( ! empty( $col['title'] ) ) {
                        echo '<h4 class="menux-footer-heading">' . esc_html( menux_footer_translate( $col['title'], 'footer-col-' . $ci . '-title' ) ) . '</h4>';
                    }
                    menux_footer_render_column( $col, $networks, $ci );
                    ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php menux_footer_render_bottom( $footer, $networks ); ?>
    </footer>
    <?php
    // Skip the scroll-to-top button+script in REST/block-editor contexts — it would attach
    // scroll listeners to the ServerSideRender iframe window, not the real page window.
    // Static flag prevents a second button when the shortcode runs more than once per page.
    static $scroll_top_rendered = false;
    if ( ( $style_opt['scroll_top'] ?? '0' ) === '1' && ! $scroll_top_rendered && ! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
        $scroll_top_rendered = true;
        echo '<button class="menux-scroll-top" aria-label="' . esc_attr__( 'Back to top', 'giuliomax-menu-builder' ) . '"><i class="fa-solid fa-chevron-up" aria-hidden="true"></i></button>';
        echo '<script>(function(){var b=document.querySelector(".menux-scroll-top");if(!b)return;window.addEventListener("scroll",function(){b.classList.toggle("is-visible",window.scrollY>300);},{passive:true});b.addEventListener("click",function(){window.scrollTo({top:0,behavior:"smooth"});});})();</script>';
    }
    // Record that a real footer was emitted on this request so the wp_footer
    // auto-injector can skip itself and avoid rendering a second copy.
    menux_footer_render_state( true );
    return ob_get_clean();
}

/**
 * Tracks whether the footer has already been output on the current request.
 * Set by the shortcode/block renderer; read by the auto-injector to prevent
 * a duplicate footer when the user has also placed the shortcode or block.
 */
function menux_footer_render_state( $mark = false ) {
    static $rendered = false;
    if ( $mark ) {
        $rendered = true;
    }
    return $rendered;
}

/**
 * Registers the wp_footer auto-injection when placement is set to "auto".
 * Reads the configured hook priority so power users can order the footer
 * relative to other plugins printing at wp_footer.
 */
add_action( 'template_redirect', 'menux_footer_maybe_auto_inject' );
function menux_footer_maybe_auto_inject() {
    if ( is_admin() ) {
        return;
    }
    $footer = wp_parse_args( get_option( 'menux_footer', array() ), menux_footer_defaults() );
    if ( ( $footer['enabled'] ?? '0' ) !== '1'
        || ( $footer['placement'] ?? 'manual' ) !== 'auto'
        || empty( $footer['columns'] ) ) {
        return;
    }
    $priority = (int) ( $footer['auto_priority'] ?? 100 );
    add_action( 'wp_footer', 'menux_footer_auto_render', $priority );
}

/**
 * Echoes the footer at wp_footer, unless it was already placed manually
 * (shortcode or block) earlier on the same page.
 */
function menux_footer_auto_render() {
    if ( menux_footer_render_state() ) {
        return;
    }
    echo menux_render_footer_shortcode( array() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- renderer escapes all output internally
}

/**
 * Makes a footer string translatable.
 *
 * Registers the string with — and pulls its translation from — the WPML/Polylang
 * compatible String Translation API. Both plugins honor these hooks; when neither
 * is active they are no-ops and the original value is returned unchanged.
 * TranslatePress translates the rendered output directly and needs no registration.
 *
 * @param string $value The source string entered in the builder.
 * @param string $name  A stable, unique name shown in the String Translation UI.
 * @return string The translated string, or the original when no plugin is active.
 */
function menux_footer_translate( $value, $name ) {
    if ( ! is_string( $value ) || $value === '' ) {
        return $value;
    }
    do_action( 'wpml_register_single_string', 'MenuX Footer', $name, $value );
    return (string) apply_filters( 'wpml_translate_single_string', $value, 'MenuX Footer', $name );
}

/**
 * Renders the body of a single footer column based on its type.
 *
 * @param array $col      Column data.
 * @param array $networks Social network map.
 * @param int   $ci       Column index, used to build stable translation string names.
 */
function menux_footer_render_column( $col, $networks, $ci = 0 ) {
    switch ( $col['type'] ?? 'links' ) {

        case 'about':
            if ( ! empty( $col['img_url'] ) ) {
                $width = ! empty( $col['img_width'] ) ? ' style="max-width:' . esc_attr( $col['img_width'] ) . ';height:auto;"' : ' style="max-width:160px;height:auto;"';
                echo '<img src="' . esc_url( $col['img_url'] ) . '" alt=""' . $width . ' loading="lazy" class="menux-footer-logo">';
            }
            if ( ! empty( $col['text'] ) ) {
                echo '<p>' . nl2br( esc_html( menux_footer_translate( $col['text'], 'footer-col-' . $ci . '-text' ) ) ) . '</p>';
            }
            break;

        case 'links':
            if ( ! empty( $col['items'] ) && is_array( $col['items'] ) ) {
                $items_html = '';
                foreach ( $col['items'] as $ii => $item ) {
                    if ( empty( $item['label'] ) ) continue;
                    $url    = ! empty( $item['url'] ) ? $item['url'] : '#';
                    $target = ( $item['target'] ?? '' ) === '_blank' ? ' target="_blank" rel="noopener"' : '';
                    $label  = menux_footer_translate( $item['label'], 'footer-col-' . $ci . '-link-' . $ii );
                    $items_html .= '<li><a href="' . esc_url( $url ) . '"' . $target . '>' . esc_html( $label ) . '</a></li>';
                }
                if ( $items_html !== '' ) {
                    echo '<ul class="menux-footer-list">' . $items_html . '</ul>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped per-item above
                }
            }
            break;

        case 'contact':
            $contact_html = '';
            if ( ! empty( $col['address'] ) ) {
                $addr = menux_footer_translate( $col['address'], 'footer-col-' . $ci . '-address' );
                $contact_html .= '<li><i class="fa-solid fa-location-dot" aria-hidden="true"></i><span>' . nl2br( esc_html( $addr ) ) . '</span></li>';
            }
            if ( ! empty( $col['phone'] ) ) {
                $tel          = preg_replace( '/[^0-9+]/', '', $col['phone'] );
                $phone_inner  = $tel !== ''
                    ? '<a href="tel:' . esc_attr( $tel ) . '">' . esc_html( $col['phone'] ) . '</a>'
                    : '<span>' . esc_html( $col['phone'] ) . '</span>';
                $contact_html .= '<li><i class="fa-solid fa-phone" aria-hidden="true"></i>' . $phone_inner . '</li>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above
            }
            if ( ! empty( $col['email'] ) && is_email( $col['email'] ) ) {
                $contact_html .= '<li><i class="fa-solid fa-envelope" aria-hidden="true"></i><a href="mailto:' . esc_attr( $col['email'] ) . '">' . esc_html( $col['email'] ) . '</a></li>';
            }
            if ( $contact_html !== '' ) {
                echo '<ul class="menux-footer-contact">' . $contact_html . '</ul>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped per-item above
            }
            break;

        case 'social':
            menux_footer_render_social( $col['networks'] ?? array(), $networks );
            break;

        case 'hours':
            if ( ! empty( $col['lines'] ) && is_array( $col['lines'] ) ) {
                $hours_html = '';
                foreach ( $col['lines'] as $li => $line ) {
                    if ( $line === '' ) continue;
                    $hours_html .= '<li>' . esc_html( menux_footer_translate( $line, 'footer-col-' . $ci . '-hour-' . $li ) ) . '</li>';
                }
                if ( $hours_html !== '' ) {
                    echo '<ul class="menux-footer-list">' . $hours_html . '</ul>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped per-item above
                }
            }
            break;

        case 'html':
            if ( ! empty( $col['html'] ) ) {
                echo wp_kses_post( $col['html'] );
            }
            break;

        case 'newsletter':
            if ( empty( $col['form_action'] ) ) {
                break; // Don't render a form with no action URL — would POST to the current page
            }
            echo '<div class="menux-footer-newsletter">';
            if ( ! empty( $col['subtitle'] ) ) {
                echo '<p>' . nl2br( esc_html( menux_footer_translate( $col['subtitle'], 'footer-col-' . $ci . '-subtitle' ) ) ) . '</p>';
            }
            $placeholder = ! empty( $col['placeholder'] )
                ? menux_footer_translate( $col['placeholder'], 'footer-col-' . $ci . '-placeholder' )
                : __( 'Your email address', 'giuliomax-menu-builder' );
            $btn_text    = ! empty( $col['button_text'] )
                ? menux_footer_translate( $col['button_text'], 'footer-col-' . $ci . '-button' )
                : __( 'Subscribe', 'giuliomax-menu-builder' );
            echo '<form class="menux-newsletter-form" action="' . esc_url( $col['form_action'] ) . '" method="post">';
            echo '<div class="menux-newsletter-row">';
            echo '<input type="email" name="EMAIL" placeholder="' . esc_attr( $placeholder ) . '" required>';
            echo '<button type="submit">' . esc_html( $btn_text ) . '</button>';
            echo '</div>';
            if ( ! empty( $col['gdpr_text'] ) ) {
                $gdpr = menux_footer_translate( $col['gdpr_text'], 'footer-col-' . $ci . '-gdpr' );
                echo '<label class="menux-newsletter-gdpr"><input type="checkbox" required> ' . esc_html( $gdpr ) . '</label>';
            }
            echo '</form>';
            echo '</div>'; // .menux-footer-newsletter
            break;
    }
}

/**
 * Renders the social icon row.
 */
function menux_footer_render_social( $items, $networks ) {
    $out = '';
    foreach ( (array) $items as $soc ) {
        $key = $soc['network'] ?? '';
        if ( empty( $networks[ $key ] ) || empty( $soc['url'] ) ) continue;
        $out .= '<a href="' . esc_url( $soc['url'] ) . '" target="_blank" rel="noopener" aria-label="' . esc_attr( $networks[ $key ]['label'] ) . '">'
              . '<i class="' . esc_attr( $networks[ $key ]['icon'] ) . '" aria-hidden="true"></i></a>';
    }
    if ( $out !== '' ) {
        echo '<div class="menux-footer-social">' . $out . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above
    }
}

/**
 * Renders the bottom bar: copyright, legal links and optional social icons.
 */
function menux_footer_render_bottom( $footer, $networks ) {
    $bottom = $footer['bottom'] ?? array();
    $copy   = $bottom['copyright'] ?? '';
    $links  = is_array( $bottom['links'] ?? null ) ? $bottom['links'] : array();

    // Pre-build legal links so the early-return guard can check real rendered content,
    // not just whether the array is non-empty (it may contain all-blank labels).
    $legal_html = '';
    foreach ( $links as $li => $l ) {
        if ( empty( $l['label'] ) ) continue;
        $label      = menux_footer_translate( $l['label'], 'footer-bottom-link-' . $li );
        $legal_html .= '<li><a href="' . esc_url( ! empty( $l['url'] ) ? $l['url'] : '#' ) . '">' . esc_html( $label ) . '</a></li>';
    }

    if ( $copy === '' && $legal_html === '' && ( $bottom['show_social'] ?? '0' ) !== '1' ) {
        return;
    }

    echo '<div class="menux-footer-bottom"><div class="menux-footer-bottom-inner">';

    if ( $copy !== '' ) {
        $copy_t = menux_footer_translate( $copy, 'footer-bottom-copyright' );
        echo '<span class="menux-footer-copy">' . esc_html( str_replace( '{year}', gmdate( 'Y' ), $copy_t ) ) . '</span>';
    }

    if ( $legal_html !== '' ) {
        echo '<ul class="menux-footer-legal">' . $legal_html . '</ul>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped per-item above
    }

    if ( ( $bottom['show_social'] ?? '0' ) === '1' ) {
        // Prefer the first social column's networks; fall back to bottom.networks.
        $socials = $bottom['networks'] ?? array();
        foreach ( (array) ( $footer['columns'] ?? array() ) as $col ) {
            if ( ( $col['type'] ?? '' ) === 'social' && ! empty( $col['networks'] ) ) {
                $socials = $col['networks'];
                break;
            }
        }
        menux_footer_render_social( $socials, $networks );
    }

    echo '</div></div>';
}
