<?php
/**
 * Includes: Metaboxes

 */
if (! defined('ABSPATH')) {
    die('Sorry, you cannot access this page.');
}
function chama_tier_level_meta_box()
{
    $args = [
        'public' => true,

    ];
    $excluded_post_types = ['chama_tier', 'chama_commission', 'chama_campaign', 'attachment', 'slide'];
    $post_types          = get_post_types($args);
    $filtered_post_types = array_diff($post_types, $excluded_post_types);

    foreach ($filtered_post_types as $post_type) {
        add_meta_box(
            'tier_level',
            __('Tier Level', 'chama'),
            'chama_tier_level_display_metabox',
            $post_type,
            'side',
            'core'
        );
    }

}

add_action('add_meta_boxes', 'chama_tier_level_meta_box');
function chama_tier_level_display_metabox($post)
{

    // Add a nonce field so we can check for it later.
    wp_nonce_field('chama_metabox_nonce', 'chama_tier_level_nonce');

    $current_tier = get_post_meta($post->ID, 'chama_tier_level', true);
    $tier_list    = chama_get_tier_levels();
    echo '<p>Choose the tier level you would like this content protected.</p>';
    echo '<p><em>Note that this will override any level you may have set from the "Settings > Protection" page or on the category/taxonomy/tag.</em></p>';
    echo '<select id="chama_tier_level" name="chama_tier_level">';

    foreach ($tier_list as $value => $label):
        echo '<option value="' . esc_attr($value) . '"' . selected($value, $current_tier) . '>' . esc_html($label) . '</option>';
    endforeach;
    echo '</select>';

}

function chama_tier_level_save_postdata($post_id)
{

    // Check if our nonce is set.
    if (! isset($_POST['chama_tier_level_nonce'])) {
        return;
    }

    // Verify that the nonce is valid.
    // check
    if (! wp_verify_nonce(sanitize_key($_POST['chama_tier_level_nonce']), 'chama_metabox_nonce')) {
        return;
    }

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // Check the user's permissions.
    if (isset($_POST['post_type']) && 'page' == $_POST['post_type']) {

        if (! current_user_can('edit_page', $post_id)) {
            return;
        }

    } else {

        if (! current_user_can('edit_post', $post_id)) {
            return;
        }
    }

    /* OK, it's safe for us to save the data now. */

    // Make sure that it is set.
    if (! isset($_POST['chama_tier_level'])) {
        return;
    }

    // Sanitize user input.
    $tier_level = sanitize_text_field(wp_unslash($_POST['chama_tier_level']));

    // Update the meta field in the database.
    update_post_meta($post_id, 'chama_tier_level', $tier_level);
}

add_action('save_post', 'chama_tier_level_save_postdata');

add_filter('manage_posts_columns', 'chama_add_tier_level_column');
add_filter('manage_pages_columns', 'chama_add_tier_level_column');
add_filter('manage_chama_newsletter_columns', 'chama_add_tier_level_column');
function chama_add_tier_level_column($columns)
{
    foreach ($columns as $key => $column) {
        $new_columns[$key] = $columns[$key];
        $new_columns       = [];

        foreach ($columns as $key => $column) {
            $new_columns[$key] = $columns[$key];
            if ($key === 'author') {
                $new_columns['tier_level'] = __('Tier Level', 'chama');
            }

        }

        return $new_columns;

    }

    return $new_columns;
}
add_action('manage_posts_custom_column', 'chama_populate_tier_level_column', 10, 2);
add_action('manage_pages_custom_column', 'chama_populate_tier_level_column', 10, 2);
function chama_populate_tier_level_column($column_name, $id)
{
    $post_type     = 'post';
    $get_post_type = filter_input(INPUT_GET, 'post_type', FILTER_SANITIZE_STRING);

    if ($get_post_type) {
        $post_type = sanitize_text_field(wp_unslash($get_post_type));
    }
    if ($column_name === 'tier_level') {
        $tier_level   = get_post_meta($id, 'chama_tier_level', true);
        $filter_level = $tier_level === '' ? 'no-tier' : $tier_level;
        $filter_url   = admin_url('/edit.php?post_type=' . $post_type);

        $filter_url = esc_url(add_query_arg(
            [
                'tier_level' => $filter_level,
            ],
            $filter_url
        ));
        echo '<a href="' . esc_attr($filter_url) . '">' . esc_html(chama_get_tier_level_from_amount($tier_level)) . '</a>';
    }

}
function chama_filter_tier_levels( $query ) {
    global $pagenow;

    // Check if we're in admin and on the post list screen
    if ( ! is_admin() || $pagenow !== 'edit.php' ) {
        return;
    }

    // Get and sanitize the tier_level query var
    $tier_level = filter_input( INPUT_GET, 'tier_level', FILTER_SANITIZE_STRING );

    // Exit if it's not present
    if ( empty( $tier_level ) ) {
        return;
    }

    // Apply appropriate meta query
    if ( $tier_level === 'no-tier' ) {
        $query->set( 'meta_query', [
            'relation' => 'OR',
            [
                'key'     => 'chama_tier_level',
                'compare' => 'NOT EXISTS',
            ],
            [
                'key'   => 'chama_tier_level',
                'value' => '',
            ],
        ] );
    } else {
        $query->set( 'meta_key', 'chama_tier_level' );
        $query->set( 'meta_value', sanitize_text_field( wp_unslash( $tier_level ) ) );
    }
}

add_filter('parse_query', 'chama_filter_tier_levels');
