<?php

/**
 * bsTheme shortcodes
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package bsTheme
 * 
 * Syntax: add_shortcode('nameofshortcode', 'getNameofshortcode');
 */

// Address ---------------------------------------------
add_shortcode('address', 'getAddress');

function getAddress($attr)
{
    $defaults = array(
        'content' => '',
        'class' => '',
    );

    $atts = shortcode_atts($defaults, $attr);

    $classItem = esc_attr($atts['class']);
    $content = $atts['content'];

    switch ($content) {
        case 'full':
            $name = esc_html(get_field('name', 'option'));
            $street = esc_html(get_field('street', 'option'));
            $zip = esc_html(get_field('zip', 'option'));
            $city = esc_html(get_field('city', 'option'));
            return "<div class='addressFull {$classItem}'>
                        <div class='addressName'>{$name}</div>
                        <div class='addressStreet'>{$street}</div>
                        <div class='addressCity'>{$zip} {$city}</div>
                    </div>";

        case 'tel':
            $tel = get_field('tel', 'option');
            $telHref = toTel($tel);
            return "<a class='addressTel {$classItem}' title='" . esc_attr($tel) . " anrufen.' href='tel:" . esc_attr($telHref) . "'>" . esc_html($tel) . "</a>";

        case 'telRaw':
            $tel = get_field('tel', 'option');
            return esc_html($tel);

        case 'mobile':
            $mobile = get_field('mobile', 'option');
            $mobileHref = toTel($mobile);
            return "<a class='addressTel {$classItem}' title='" . esc_attr($mobile) . " anrufen.' href='tel:" . esc_attr($mobileHref) . "'>" . esc_html($mobile) . "</a>";

        case 'mobileRaw':
            $mobile = get_field('mobile', 'option');
            return esc_html($mobile);

        case 'mail':
            $mail = get_field('mail', 'option');
            return "<a class='addressMail {$classItem}' title='Mail an " . esc_attr($mail) . "' href='mailto:" . esc_attr($mail) . "'>" . esc_html($mail) . "</a>";

        case 'mailRaw':
            $mail = get_field('mail', 'option');
            return esc_html($mail);

        case 'name':
        case 'street':
        case 'zip':
        case 'city':
        case 'country':
            $value = esc_html(get_field($content, 'option'));
            $className = 'address' . ucfirst($content);
            return "<div class='{$className} {$classItem}'>{$value}</div>";

        default:
            return ''; // optionally: return some error or default
    }
}

// Copyright + Credits (default true) ---------------------------------------------
add_shortcode('copyright', 'getCopyright');

function getCopyright($attr)
{
    $year = date('Y');

    $defaults = array(
        'name' => 'Hello World',
        'credits' => 'true',
        'class' => '',
    );

    $atts = shortcode_atts($defaults, $attr);

    // Sanitize input
    $name = esc_html($atts['name']); // Sanitize name attribute
    $class = esc_attr($atts['class']); // Sanitize class attribute
    $credits = filter_var($atts['credits'], FILTER_VALIDATE_BOOLEAN); // Convert to boolean

    // * HEREDOC syntax for better readability
    if (!$credits) {
        return <<<HTML
            <div class="copyright {$class}">&copy; {$year} {$name}</div>
        HTML;
    }

    return <<<HTML
    <div class="copyright d-flex flex-wrap flex-column flex-md-row {$class}">
        <span>&copy; {$year} {$name}</span>
        <span class="d-none d-md-inline mx-1">|</span>
        <span class="copyright__credits mt-2 mt-md-0">Design by <a href="https://brotsalz.de" target="_blank" rel="noopener">brot & salz</a></span>
    </div>
    HTML;
}

// Get company logos (default prime) ---------------------------------------------
function getCompLogo($atts)
{
    $attributes = shortcode_atts([
        'id' => '',
        'class' => '',
        'type' => 'prime',       // prime | alt | both
        'link' => '',
        'inlinesvg' => 'false'   // true | false
    ], $atts);

    $logoPrime = get_field('logo_prime', 'option'); // Must be image array
    $logoAlt = get_field('logo_alt', 'option');
    $useInlineSvg = filter_var($attributes['inlinesvg'], FILTER_VALIDATE_BOOLEAN);
    $type = $attributes['type'];
    $link = esc_url($attributes['link']);
    $class = esc_attr($attributes['class']);

    $res = '<div class="logo_wrapper ' . $class . '">';
    if (!empty($link)) {
        $res .= '<a class="d-flex" href="' . $link . '">';
    }

    // Helper function to render either inline SVG or fallback <img>
    $renderLogo = function ($logo, $className) use ($useInlineSvg) {
        if (!is_array($logo) || empty($logo['url'])) return '';

        $isSvg = strtolower(pathinfo($logo['url'], PATHINFO_EXTENSION)) === 'svg';

        if ($useInlineSvg && $isSvg) {
            return inlinesvg($logo, $className);
        }

        return '<img class="' . esc_attr($className) . '" src="' . esc_url($logo['url']) . '" alt="Logo">';
    };

    // Decide which logos to render
    if ($type === 'both') {
        $res .= $renderLogo($logoPrime, 'logoPrime');
        $res .= $renderLogo($logoAlt, 'logoAlt');
    } elseif ($type === 'prime') {
        $res .= $renderLogo($logoPrime, 'logoPrime');
    } elseif ($type === 'alt') {
        $res .= $renderLogo($logoAlt, 'logoAlt');
    } else {
        $res .= esc_html(get_bloginfo('name'));
    }

    if (!empty($link)) {
        $res .= '</a>';
    }

    $res .= '</div>';
    return $res;
}

add_shortcode('compLogo', 'getCompLogo');

// Turn Images into inline SVG ---------------------------------------------
function inlinesvg($svg, $class)
{
    if (!isset($svg['url']) || strpos($svg['url'], get_site_url()) !== 0) {
        return ''; // reject non-local files
    }

    $svg_content = file_get_contents($svg['url']);
    if (!$svg_content) return '';

    $aria_title = esc_html($svg['title']);
    $aria_description = esc_html($svg['description']);
    $uid = uniqid('svg_');

    $svg_content = str_replace(
        '<svg',
        '<svg class="' . esc_attr($class) . '" aria-labelledby="' . $uid . '_title ' . $uid . '_desc"',
        $svg_content
    );

    $svg_content = str_replace(
        '</svg>',
        '<title id="' . $uid . '_title">' . $aria_title . '</title><desc id="' . $uid . '_desc">' . $aria_description . '</desc></svg>',
        $svg_content
    );

    return $svg_content;
}

// Social Media ---------------------------------------------
add_shortcode('social', 'getSocial');

function getSocial($attr)
{
    $atts = shortcode_atts([
        'label' => 'false',
        'class' => '',
        'content' => 'all'
    ], $attr);

    $showLabel = filter_var($atts['label'], FILTER_VALIDATE_BOOLEAN);
    $classItem = esc_attr($atts['class']);
    $result = '<div class="social_media__wrapper d-flex flex-wrap ' . $classItem . '">';

    $sources = ['social_media', 'socmed'];

    foreach ($sources as $fieldName) {
        $rows = get_field($fieldName, 'option');
        if (!$rows) continue;

        foreach ($rows as $row) {
            if ($atts['content'] !== 'all' && (!isset($row['value']) || $row['value'] !== $atts['content'])) continue;
            if (empty($row['isactive'])) continue;

            $label = esc_attr($row['label'] ?? '');
            $link = esc_url($row['link'] ?? '#');

            $icon = $row['icon'] ?? '';
            $displayText = $showLabel ? esc_html($label) : $icon; // NOTE: raw icon is trusted

            $result .= '<div class="social_media__item me-2">';
            $result .= '<a href="' . $link . '" title="' . $label . '" target="_blank" rel="noopener">' . $displayText . '</a>';
            $result .= '</div>';
        }
    }

    $result .= '</div>';
    return $result;
}

// Default Nav Burger ---------------------------------------------
function nav_burger_shortcode($atts)
{
    $atts = shortcode_atts([
        'side_text' => 'Menu',
        'class' => '',
        'text_position' => '',
        'label' => 'Open Main Navigation',
    ], $atts);

    ob_start();
?>
    <div class="menu_burger__wrapper d-flex align-items-center">
        <?php if ($atts['text_position'] == 'left') {  ?>
            <div class="menu_burger__text me-3"><?php echo esc_html($atts['side_text']); ?></div>
        <?php }  ?>
        <button id="menu_burger"
            class="menu_burger__button"
            aria-label="<?php echo esc_attr($atts['label']); ?>"
            aria-expanded="false"
            aria-controls="navigation_overlay">
            <div class="menu_burger__button_wrapper">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </button>
        <?php if ($atts['text_position'] == 'right') {  ?>
            <div class="menu_burger__text ms-3"><?php echo esc_html($atts['side_text']); ?></div>
        <?php } ?>
    </div>
<?php
    return ob_get_clean();
}

add_shortcode('navBurger', 'nav_burger_shortcode');

//  ---------------------------------------------
add_shortcode('menu', 'getMenu');

function getMenu($atts)
{
    $atts = shortcode_atts([
        'menu' => '',
        'theme_location' => '',
        'container' => 'div',
        'container_class' => 'menu-container',
        'menu_class' => '',
    ], $atts);

    $args = [
        'container' => sanitize_html_class($atts['container']),
        'container_class' => sanitize_html_class($atts['container_class']),
        'menu_class' => 'menu ' . sanitize_html_class($atts['menu_class']),
        'echo' => false,
    ];

    if (!empty($atts['theme_location'])) {
        $args['theme_location'] = sanitize_key($atts['theme_location']);
    } elseif (!empty($atts['menu'])) {
        $args['menu'] = absint($atts['menu']);
    }

    return wp_nav_menu($args);
}

// Sanitize phone number ---------------------------------------------
function toTel($tel)
{
    // Keep leading +, strip all other non-numeric characters
    $tel = trim($tel);
    $tel = preg_replace('/[^+\d]/', '', $tel);

    return $tel;
}

// Add favicon ---------------------------------------------
function bs_custom_favicon()
{

    $fav = get_field('favicon', 'options'); // Replace with the correct path to your favicon file
    if ($fav) {
        echo '<link rel="shortcut icon" href="' . $fav['url'] . '" >';
    }
}
add_action('wp_head', 'bs_custom_favicon');
