<?php
/**
 * #8037 Two-level "Sort by" picker.
 *
 * A family dropdown (Recent / Top / Hot …) plus a variant dropdown whose options are the leaves
 * of the currently-selected family. The persisted value stays a single leaf key in
 * #peepso_stream_filter_sort_by (backend + user-meta persistence unchanged); the family in
 * #peepso_stream_filter_sort_group is UI state, derived from the leaf's 'group'. Shared by the
 * full, simple and pages filter templates so Top/Hot only have to be registered once.
 */

$user_stream_filters = PeepSoUser::get_stream_filters();
$sort_posts    = apply_filters('peepso_stream_sort_list', array());
$sort_families = apply_filters('peepso_stream_sort_families', array());

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

// Resolve the current leaf: persisted user pref, else admin default, else first leaf.
$sort_by = PeepSo::get_option_new('stream_sort_default');
if (isset($user_stream_filters['sort_by']) && array_key_exists($user_stream_filters['sort_by'], $sort_posts)) {
    $sort_by = $user_stream_filters['sort_by'];
}
if (!array_key_exists($sort_by, $sort_posts)) {
    reset($sort_posts);
    $sort_by = key($sort_posts);
}

// Group leaves into families. A leaf with no 'group' forms its own single-variant family
// (e.g. pinned_only), so nothing needs special-casing here.
$groups = array();
foreach ($sort_posts as $key => $leaf) {
    $g = (isset($leaf['group']) && strlen($leaf['group'])) ? $leaf['group'] : $key;
    if (!isset($groups[$g])) {
        if (isset($sort_families[$g])) {
            $meta = $sort_families[$g];
        } else {
            $meta = array(
                'order'     => 9999,
                'label'     => $leaf['label'],
                'desc'      => isset($leaf['desc']) ? $leaf['desc'] : '',
                'icon'      => $leaf['icon'],
            );
        }
        $groups[$g] = array('meta' => $meta, 'variants' => array());
    }
    $groups[$g]['variants'][$key] = $leaf;
}

// Order families by their meta 'order'.
uasort($groups, function ($a, $b) {
    $oa = isset($a['meta']['order']) ? $a['meta']['order'] : 9999;
    $ob = isset($b['meta']['order']) ? $b['meta']['order'] : 9999;
    return $oa - $ob;
});

// Current family = the group owning the current leaf.
$current_family = (isset($sort_posts[$sort_by]['group']) && strlen($sort_posts[$sort_by]['group']))
    ? $sort_posts[$sort_by]['group'] : $sort_by;
if (!isset($groups[$current_family])) {
    reset($groups);
    $current_family = key($groups);
}

$family_meta      = $groups[$current_family]['meta'];
$variant_leaf     = $sort_posts[$sort_by];
$current_variants = $groups[$current_family]['variants'];

// #8117 One family => the family picker has nothing to pick. Hide it with display:none, NEVER by
// omitting the markup: activitystream.js gates the ENTIRE #8003 localStorage sort restore on
// $family.length, and sources the variant header text from this pill's options.
$solo_family = (count($groups) <= 1);

// _posts-filters.scss keys the flush-left padding off :first-of-type, which IGNORES display:none,
// so the surviving variant pill would render indented. Hand it that padding inline.
$family_style  = $solo_family ? ' style="display:none"' : '';
$variant_style = '';
if (count($current_variants) <= 1) {
    $variant_style = ' style="display:none"';
} else if ($solo_family) {
    $variant_style = ' style="padding-inline-start:0"';
}
?>
<input type="hidden" id="peepso_stream_filter_sort_group" value="<?php echo esc_attr($current_family); ?>" />
<input type="hidden" id="peepso_stream_filter_sort_by" value="<?php echo esc_attr($sort_by); ?>" />

<!-- Sort family (main picker) -->
<div class="pso-posts__filter pso-posts__filter--sort pso-posts__filter--sort-family ps-js-dropdown ps-js-activitystream-filter" data-id="peepso_stream_filter_sort_group"<?php echo $family_style; ?>>
    <a href="javascript:" class="pso-posts-filter__toggle ps-js-dropdown-toggle" aria-haspopup="true">
        <i class="<?php echo esc_attr($family_meta['icon']); ?>"></i>
        <span><?php echo $family_meta['label']; ?></span>
    </a>
    <div class="pso-posts-filter__box ps-js-dropdown-menu" role="menu">
        <div class="pso-posts-filter__title">
            <span><?php echo esc_attr__('Sort by', 'peepso-core'); ?></span>
            <a href="javascript:" class="pso-posts-filter__close ps-js-cancel" role="button" aria-label="<?php echo esc_attr__('Close', 'peepso-core'); ?>"><i class="pso-i-cross-small"></i></a>
        </div>
        <div class="pso-posts-filter__options">
            <?php foreach ($groups as $fkey => $group) { $meta = $group['meta']; ?>
                <a class="pso-posts-filter__option" data-option-value="<?php echo esc_attr($fkey); ?>" role="menuitem">
                    <div class="pso-posts-filter-option__control">
                        <input type="radio" name="peepso_stream_filter_sort_group" id="peepso_stream_filter_sort_group_opt_<?php echo esc_attr($fkey); ?>"
                               value="<?php echo esc_attr($fkey); ?>" <?php if ($fkey == $current_family) echo 'checked'; ?> />
                    </div>
                    <label class="pso-posts-filter-option__content" for="peepso_stream_filter_sort_group_opt_<?php echo esc_attr($fkey); ?>">
                        <span class="pso-posts-filter-option__name"><?php echo $meta['label']; ?></span>
                        <?php if (isset($meta['desc']) && strlen($meta['desc'])) { ?><div class="pso-posts-filter-option__desc"><?php echo $meta['desc']; ?></div><?php } ?>
                    </label>
                    <div class="pso-posts-filter-option__icon">
                        <i class="<?php echo esc_attr($meta['icon']); ?>"></i>
                    </div>
                </a>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Sort variant (sub picker) -->
<div class="pso-posts__filter pso-posts__filter--sort pso-posts__filter--sort-variant ps-js-dropdown ps-js-activitystream-filter" data-id="peepso_stream_filter_sort_by"<?php if ($solo_family) echo ' data-solo="1"'; ?><?php echo $variant_style; ?>>
    <a href="javascript:" class="pso-posts-filter__toggle ps-js-dropdown-toggle" aria-haspopup="true">
        <i class="<?php echo esc_attr($variant_leaf['icon']); ?>"></i>
        <span><?php echo $variant_leaf['label']; ?></span>
    </a>
    <div class="pso-posts-filter__box ps-js-dropdown-menu" role="menu">
        <div class="pso-posts-filter__title">
            <!-- #8037 Header mirrors the selected family (Recent/Top/Hot); kept in sync client-side by applySortFamily().
                 #8117 ...except in single-family mode, where the family pill is hidden and this dropdown stands
                 alone - then it reverts to the pre-ranking "Sort by" header. -->
            <span><?php echo $solo_family ? esc_html__('Sort by', 'peepso-core') : $family_meta['label']; ?></span>
            <a href="javascript:" class="pso-posts-filter__close ps-js-cancel" role="button" aria-label="<?php echo esc_attr__('Close', 'peepso-core'); ?>"><i class="pso-i-cross-small"></i></a>
        </div>
        <div class="pso-posts-filter__options">
            <?php foreach ($groups as $fkey => $group) {
                foreach ($group['variants'] as $key => $value) { ?>
                    <a class="pso-posts-filter__option" data-option-value="<?php echo esc_attr($key); ?>" data-group="<?php echo esc_attr($fkey); ?>" role="menuitem"<?php if ($fkey != $current_family) echo ' style="display:none"'; ?>>
                        <div class="pso-posts-filter-option__control">
                            <input type="radio" name="peepso_stream_filter_sort_by" id="peepso_stream_filter_sort_by_opt_<?php echo esc_attr($key); ?>"
                                   value="<?php echo esc_attr($key); ?>" <?php if ($key == $sort_by) echo 'checked'; ?> />
                        </div>
                        <label class="pso-posts-filter-option__content" for="peepso_stream_filter_sort_by_opt_<?php echo esc_attr($key); ?>">
                            <span class="pso-posts-filter-option__name"><?php echo $value['label']; ?></span>
                        </label>
                        <div class="pso-posts-filter-option__icon">
                            <i class="<?php echo esc_attr($value['icon']); ?>"></i>
                        </div>
                    </a>
                <?php }
            } ?>
        </div>
    </div>
</div>
