<?php
namespace Wpupgrader\Libraries\WordPress\Plugins\Core\Settings\Page\Callback;

use Wpupgrader\Libraries\WordPress\Plugins\Core\Settings\Page\Callback;

class Consent extends Callback
{
    public function callbackAction()
    {
        $r = [
            'post_type'        => 'gdprc_consent',
            'post_status'      => 'publish',
            'posts_per_page'   => -1,
            'select_name'      => $this->getNameString(),
            'id'               => $this->getIdString(),
            'value_field'      => 'ID',
            'order'            => 'ASC',
            'orderby'          => 'post_title',
            'show'             => 'post_title',
            'pagination'       => false,
            'suppress_filters' => false,
            'selected'         => $this->getValue() //this will have to be the id of the stored page.
        ];
        $posts = \get_posts($r);

        $show = $r['show'];
        $output = '';
        if (!empty($posts)) {
            $name = \esc_attr($r['select_name']);
            $id = $r['id'] ? " id='".\esc_attr($r['id'])."'" : " id='$name'";
            $output = "<select name='{$name}'{$id} class='gdprc-consent-dropdown'>\n";
            $output .= "\t<option value=''>".\__("- Disabled -", 'gdprc_consent')."</option>\n";

            if ($r['show_option_none']) {
                $_selected = \selected($r['show_option_none'], $r['selected'], false);
                $output .= "\t<option value='".\esc_attr($r['option_none_value'])."'$_selected>{$r['show_option_none']}</option>\n";
            }

            foreach ((array)$posts as $post) {
                $value = !isset($r['value_field']) || !isset($post->{$r['value_field']}) ? $post->ID : $post->{$r['value_field']};
                $_selected = \selected($value, $r['selected'], false);
                $display = !empty($post->$show) ? $post->$show : \sprintf(\__('#%d (no title)'), $post->ID);
                $output .= "\t<option value='{$value}'{$_selected}>".\esc_html($display)."</option>\n";
            }
            $output .= "</select>";
        }
        echo $output;
        echo $this->getDescription();
    }
}