<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package ChaletMontagne
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Adds custom classes to the array of body classes
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function chaletmontagne_body_classes($classes) {
    // Adds a class of hfeed to non-singular pages
    if (!is_singular()) {
        $classes[] = 'hfeed';
    }

    // Adds a class of no-sidebar when there is no sidebar present
    if (!is_active_sidebar('sidebar-1')) {
        $classes[] = 'no-sidebar';
    }

    // Add theme preset class
    $luxury_preset = get_theme_mod('chaletmontagne_luxury_preset', 'marron-sobre');
    $classes[] = 'theme-preset-' . sanitize_html_class($luxury_preset);

    // Add dark theme class for dark themes
    $colors = chaletmontagne_get_luxury_colors($luxury_preset);
    if (isset($colors['is_dark']) && $colors['is_dark']) {
        $classes[] = 'theme-dark';
    }

    // Add effect class
    if (isset($colors['effect']) && !empty($colors['effect'])) {
        $classes[] = 'theme-effect-' . sanitize_html_class($colors['effect']);
    }

    return $classes;
}
add_filter('body_class', 'chaletmontagne_body_classes');

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments
 */
function chaletmontagne_pingback_header() {
    if (is_singular() && pings_open()) {
        printf('<link rel="pingback" href="%s">', esc_url(get_bloginfo('pingback_url')));
    }
}
add_action('wp_head', 'chaletmontagne_pingback_header');

/**
 * Display social media links
 */
function chaletmontagne_social_links() {
    // SVG icons inline — no external dependency, RGPD compliant
    $social_networks = array(
        'facebook'       => array(
            'label' => 'Facebook',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>',
        ),
        'instagram'      => array(
            'label' => 'Instagram',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg>',
        ),
        'twitter'        => array(
            'label' => 'X (Twitter)',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>',
        ),
        'youtube'        => array(
            'label' => 'YouTube',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>',
        ),
        'chalet-montagne' => array(
            'label' => 'Chalet-Montagne.com',
            'svg'   => 'file:chalet-montagne.svg',
        ),
        'airbnb'         => array(
            'label' => 'Airbnb',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12.001 18.275c-1.353-1.697-2.148-3.184-2.413-4.457-.263-1.027-.16-1.848.291-2.465.346-.476.849-.74 1.425-.793.63-.053 1.262.159 1.69.581a2.14 2.14 0 01.635 1.476c.029.737-.238 1.58-.794 2.502a14.91 14.91 0 01-.834 1.156zm.854-13.153c.397.682.744 1.34 1.057 1.982.157.319.306.647.446.972a8.39 8.39 0 011.338-.762c1.27-.556 2.636-.792 3.94-.657 1.903.198 3.304 1.261 3.87 2.932.72 2.134-.057 4.793-2.147 7.39-1.32 1.64-2.985 3.103-4.768 4.193-1.3.793-2.484 1.204-3.524 1.244h-.084c-1.04-.04-2.224-.45-3.524-1.244-1.783-1.09-3.449-2.553-4.768-4.194-2.09-2.596-2.867-5.255-2.147-7.389.566-1.671 1.967-2.734 3.87-2.932 1.304-.135 2.67.1 3.94.657.432.19.87.42 1.303.685.14-.32.29-.64.443-.952.313-.64.66-1.299 1.057-1.981C13.037 2.529 12.547 1.247 12 0c-.548 1.247-1.037 2.53-1.554 4.122z"/></svg>',
        ),
        'booking'        => array(
            'label' => 'Booking.com',
            'svg'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M2.273 0C1.018 0 0 1.018 0 2.273v19.454C0 22.982 1.018 24 2.273 24h19.454C22.982 24 24 22.982 24 21.727V2.273C24 1.018 22.982 0 21.727 0zm3.975 5.401h4.389c2.628 0 4.265 1.304 4.265 3.392 0 1.36-.779 2.425-2.166 2.942v.072c1.752.312 2.764 1.47 2.764 3.17 0 2.371-1.823 3.82-4.787 3.82H6.248zm2.804 2.186v3.12h1.375c1.432 0 2.175-.575 2.175-1.593 0-.952-.671-1.527-1.818-1.527zm0 5.16v3.373h1.643c1.467 0 2.238-.623 2.238-1.71 0-1.064-.796-1.663-2.238-1.663z"/></svg>',
        ),
    );

    $has_links = false;
    foreach ($social_networks as $network => $data) {
        if (get_theme_mod("chaletmontagne_social_{$network}")) {
            $has_links = true;
            break;
        }
    }

    if (!$has_links) {
        return;
    }

    // Allowed HTML for inline SVG icons (hardcoded above, but kses-filtered for safety/review).
    $allowed_svg = array(
        'svg'  => array(
            'viewbox' => true,
            'fill'    => true,
            'class'   => true,
            'width'   => true,
            'height'  => true,
            'xmlns'   => true,
        ),
        'path' => array(
            'd'    => true,
            'fill' => true,
        ),
        'span' => array(
            'class' => true,
        ),
        'img'  => array(
            'src'    => true,
            'alt'    => true,
            'class'  => true,
            'width'  => true,
            'height' => true,
        ),
    );

    echo '<div class="social-links">';
    foreach ($social_networks as $network => $data) {
        $url = get_theme_mod("chaletmontagne_social_{$network}");
        if ($url) {
            // Generate icon HTML
            if (strpos($data['svg'], 'file:') === 0) {
                $icon_file = str_replace('file:', '', $data['svg']);
                $icon_path = get_template_directory_uri() . '/assets/images/social/' . $icon_file;
                $icon_html = sprintf(
                    '<img src="%s" alt="%s" class="social-icon social-icon-svg" width="20" height="20">',
                    esc_url($icon_path),
                    esc_attr($data['label'])
                );
            } else {
                $icon_html = '<span class="social-icon">' . $data['svg'] . '</span>';
            }

            printf(
                '<a href="%s" class="social-link social-link-%s" target="_blank" rel="noopener noreferrer" aria-label="%s">%s</a>',
                esc_url($url),
                esc_attr($network),
                esc_attr($data['label']),
                wp_kses($icon_html, $allowed_svg)
            );
        }
    }
    echo '</div>';
}

/**
 * Custom excerpt length
 *
 * @param int $length Excerpt length.
 * @return int
 */
function chaletmontagne_excerpt_length($length) {
    if (is_admin()) {
        return $length;
    }

    return 30;
}
add_filter('excerpt_length', 'chaletmontagne_excerpt_length');

/**
 * Custom excerpt more string
 *
 * @param string $more "Read more" string.
 * @return string
 */
function chaletmontagne_excerpt_more($more) {
    if (is_admin()) {
        return $more;
    }

    return '&hellip;';
}
add_filter('excerpt_more', 'chaletmontagne_excerpt_more');

/**
 * Get location ID from page meta
 *
 * @param int $post_id Post ID.
 * @return int|false Location ID or false if not found.
 */
function chaletmontagne_get_location_id($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    $location_id = get_post_meta($post_id, 'cm2_location_id', true);

    return $location_id ? intval($location_id) : false;
}

/**
 * Check if current page is a location page (generated by plugin)
 *
 * @return bool
 */
function chaletmontagne_is_location_page() {
    return (bool) chaletmontagne_get_location_id();
}

/**
 * Prints HTML with meta information for the current post-date/time
 */
function chaletmontagne_posted_on() {
    $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
    if (get_the_time('U') !== get_the_modified_time('U')) {
        $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
    }

    $time_string = sprintf(
        $time_string,
        esc_attr(get_the_date(DATE_W3C)),
        esc_html(get_the_date()),
        esc_attr(get_the_modified_date(DATE_W3C)),
        esc_html(get_the_modified_date())
    );

    $posted_on = sprintf(
        /* translators: %s: post date. */
        esc_html_x('Publié le %s', 'post date', 'chalet-montagne'),
        '<a href="' . esc_url(get_permalink()) . '" rel="bookmark">' . $time_string . '</a>'
    );

    echo '<span class="posted-on">' . $posted_on . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * Prints HTML with meta information for the current author
 */
function chaletmontagne_posted_by() {
    $byline = sprintf(
        /* translators: %s: post author. */
        esc_html_x('par %s', 'post author', 'chalet-montagne'),
        '<span class="author vcard"><a class="url fn n" href="' . esc_url(get_author_posts_url(get_the_author_meta('ID'))) . '">' . esc_html(get_the_author()) . '</a></span>'
    );

    echo '<span class="byline"> ' . $byline . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * Prints HTML with meta information for the categories, tags and comments
 */
function chaletmontagne_entry_footer() {
    // Hide category and tag text for pages.
    if ('post' === get_post_type()) {
        /* translators: used between list items, there is a space after the comma */
        $categories_list = get_the_category_list(esc_html__(', ', 'chalet-montagne'));
        if ($categories_list) {
            /* translators: 1: list of categories. */
            printf('<span class="cat-links">' . esc_html__('Publié dans %1$s', 'chalet-montagne') . '</span>', $categories_list); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        /* translators: used between list items, there is a space after the comma */
        $tags_list = get_the_tag_list('', esc_html_x(', ', 'list item separator', 'chalet-montagne'));
        if ($tags_list) {
            /* translators: 1: list of tags. */
            printf('<span class="tags-links">' . esc_html__('Tagué %1$s', 'chalet-montagne') . '</span>', $tags_list); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
    }

    if (!is_single() && !post_password_required() && (comments_open() || get_comments_number())) {
        echo '<span class="comments-link">';
        comments_popup_link(
            sprintf(
                wp_kses(
                    /* translators: %s: post title */
                    __('Laisser un commentaire<span class="screen-reader-text"> sur %s</span>', 'chalet-montagne'),
                    array(
                        'span' => array(
                            'class' => array(),
                        ),
                    )
                ),
                wp_kses_post(get_the_title())
            )
        );
        echo '</span>';
    }

    edit_post_link(
        sprintf(
            wp_kses(
                /* translators: %s: Name of current post. Only visible to screen readers */
                __('Modifier <span class="screen-reader-text">%s</span>', 'chalet-montagne'),
                array(
                    'span' => array(
                        'class' => array(),
                    ),
                )
            ),
            wp_kses_post(get_the_title())
        ),
        '<span class="edit-link">',
        '</span>'
    );
}

/**
 * Display breadcrumbs
 */
function chaletmontagne_breadcrumbs() {
    if (is_front_page()) {
        return;
    }

    $separator = ' <span class="breadcrumb-separator">&raquo;</span> ';
    $home_title = __('Accueil', 'chalet-montagne');

    echo '<nav class="breadcrumbs" aria-label="' . esc_attr__('Fil d\'Ariane', 'chalet-montagne') . '">';
    echo '<a href="' . esc_url(home_url('/')) . '">' . esc_html($home_title) . '</a>';

    if (is_singular()) {
        $post_type = get_post_type();

        // Custom Post Types (location, etc.)
        if ($post_type !== 'post' && $post_type !== 'page') {
            $post_type_obj = get_post_type_object($post_type);

            // Default label for all custom post types is "Nos locations"
            $default_label = __('Nos locations', 'chalet-montagne');

            // Get archive title (use default for rental/location types)
            $archive_title = $default_label;

            // Link to post type archive if available, otherwise just text
            if ($post_type_obj && $post_type_obj->has_archive) {
                $archive_link = get_post_type_archive_link($post_type);
                echo $separator . '<a href="' . esc_url($archive_link) . '">' . esc_html($archive_title) . '</a>';
            } else {
                echo $separator . '<span>' . esc_html($archive_title) . '</span>';
            }

            // Current post title
            echo $separator . '<span class="breadcrumb-current">' . esc_html(get_the_title()) . '</span>';

        // Regular posts (blog)
        } elseif ($post_type === 'post') {
            // Categories
            $categories = get_the_category();
            if ($categories) {
                $category = $categories[0];
                echo $separator . '<a href="' . esc_url(get_category_link($category->term_id)) . '">' . esc_html($category->name) . '</a>';
            }
            // Post title
            echo $separator . '<span class="breadcrumb-current">' . esc_html(get_the_title()) . '</span>';

        // Pages
        } elseif ($post_type === 'page') {
            // Parent pages
            if (wp_get_post_parent_id(get_the_ID())) {
                $parent_id = wp_get_post_parent_id(get_the_ID());
                $breadcrumbs = array();
                while ($parent_id) {
                    $page = get_post($parent_id);
                    $breadcrumbs[] = '<a href="' . esc_url(get_permalink($page->ID)) . '">' . esc_html(get_the_title($page->ID)) . '</a>';
                    $parent_id = $page->post_parent;
                }
                $breadcrumbs = array_reverse($breadcrumbs);
                foreach ($breadcrumbs as $crumb) {
                    echo $separator . $crumb;
                }
            }
            echo $separator . '<span class="breadcrumb-current">' . esc_html(get_the_title()) . '</span>';
        }

    } elseif (is_page()) {
        // Fallback for pages (should not reach here normally)
        // Parent pages
        if (wp_get_post_parent_id(get_the_ID())) {
            $parent_id = wp_get_post_parent_id(get_the_ID());
            $breadcrumbs = array();
            while ($parent_id) {
                $page = get_post($parent_id);
                $breadcrumbs[] = '<a href="' . esc_url(get_permalink($page->ID)) . '">' . esc_html(get_the_title($page->ID)) . '</a>';
                $parent_id = $page->post_parent;
            }
            $breadcrumbs = array_reverse($breadcrumbs);
            foreach ($breadcrumbs as $crumb) {
                echo $separator . $crumb;
            }
        }
        echo $separator . '<span class="breadcrumb-current">' . esc_html(get_the_title()) . '</span>';

    } elseif (is_category()) {
        $category = get_queried_object();
        if ($category->parent) {
            $parent = get_category($category->parent);
            echo $separator . '<a href="' . esc_url(get_category_link($parent->term_id)) . '">' . esc_html($parent->name) . '</a>';
        }
        echo $separator . '<span class="breadcrumb-current">' . esc_html($category->name) . '</span>';

    } elseif (is_tag()) {
        echo $separator . '<span class="breadcrumb-current">' . esc_html(single_tag_title('', false)) . '</span>';

    } elseif (is_post_type_archive()) {
        $post_type_obj = get_queried_object();
        echo $separator . '<span class="breadcrumb-current">' . esc_html($post_type_obj->labels->name) . '</span>';

    } elseif (is_tax()) {
        $term = get_queried_object();
        $taxonomy = get_taxonomy($term->taxonomy);
        $post_type = $taxonomy->object_type[0] ?? '';

        // Link to post type archive
        if ($post_type) {
            $post_type_obj = get_post_type_object($post_type);
            if ($post_type_obj && $post_type_obj->has_archive) {
                echo $separator . '<a href="' . esc_url(get_post_type_archive_link($post_type)) . '">' . esc_html($post_type_obj->labels->name) . '</a>';
            }
        }
        echo $separator . '<span class="breadcrumb-current">' . esc_html($term->name) . '</span>';

    } elseif (is_search()) {
        echo $separator . '<span class="breadcrumb-current">' . esc_html__('Résultats de recherche pour', 'chalet-montagne') . ' "' . esc_html(get_search_query()) . '"</span>';

    } elseif (is_404()) {
        echo $separator . '<span class="breadcrumb-current">' . esc_html__('Erreur 404', 'chalet-montagne') . '</span>';

    } elseif (is_archive()) {
        echo $separator . '<span class="breadcrumb-current">' . esc_html(get_the_archive_title()) . '</span>';
    }

    echo '</nav>';
}
