<?php

/**
 * Plugin Name: WP private counter
 * Plugin URI: https://google.com/
 * Description: Personlize your code here.
 * Version: 0.1
 * Author: wp-private-counter
 * Author URI: https://google.com/
 **/

//  ini_set('display_errors', 1);
//  ini_set('display_startup_errors', 1);
//  error_reporting(E_ALL);

function register_page_visit_counts()
{

    /**
     * Post Type: Page visit counts.
     */

    $labels = [
        "name" => esc_html__("Seitenbesucherzähler", "__theme__"),
        "singular_name" => esc_html__("Seitenbesucherzähler", "__theme__"),
        "add_new_item" => esc_html__("Add new link", "__theme__"),
        "edit_item" => esc_html__("Edit link", "__theme__"),
        "new_item" => esc_html__("New link", "__theme__"),
        "view_item" => esc_html__("View link", "__theme__"),
        "search_items" => esc_html__("Search link", "__theme__"),
        "not_found" => esc_html__("Link not found", "__theme__"),
        "not_found_in_trash" => esc_html__("Link not found in trash", "__theme__"),
    ];

    $args = [
        "label" => esc_html__("Seitenbesucherzähler", "__theme__"),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => true,
        "rest_base" => "",
        "rest_controller_class" => "WP_REST_Posts_Controller",
        "rest_namespace" => "wp/v2",
        "has_archive" => false,
        "show_in_menu" => true,
        "show_in_nav_menus" => true,
        "delete_with_user" => false,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "can_export" => false,
        "rewrite" => ["slug" => "page-visit-counts", "with_front" => true],
        "query_var" => true,
        "supports" => ["title", "custom-fields", "author", "page-attributes"],
        "show_in_graphql" => false,
    ];

    register_post_type("page-visit-counts", $args);
}

add_action('init', 'register_page_visit_counts');

function wpb_change_title_text($title)
{
    $screen = get_current_screen();

    if ('page-visit-counts' == $screen->post_type) {
        $title = 'Add link (etc. https://yoursite.com/page-xyz)';
    }
    return $title;
}

add_filter('enter_title_here', 'wpb_change_title_text');


add_action('init', 'plugin_init');

function plugin_init()
{
    // https://wordpress.org/support/article/roles-and-capabilities
    add_role('wp_private_counter_role', 'Private counter role', array(
        'read'  => true,  // true allows this capability 
        'edit_others_posts'  => false,
        'read_private_posts' => false,
        // 'publish_posts' => true,
        // 'edit_posts' => true
    ));
    
    if (str_contains($_SERVER['REQUEST_URI'], 'page-visit-counts')) {

        // No robots for this slug
        add_filter('wp_robots', 'wp_robots_no_robots');
    }

    if (
        array_key_exists('REQUEST_METHOD', $_SERVER) && !empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'GET'
        && array_key_exists('d', $_GET) && !empty($_GET['d'])
    ) {

        $args = array(
            'name'        => esc_sql($_GET['d']),
            'post_type'   => 'page-visit-counts',
            'post_status' => 'publish',
            'numberposts' => 1
        );
        $my_posts = get_posts($args);

        if (!empty($my_posts) && !empty($my_posts[0]) && $_GET['d'] === $my_posts[0]->post_name) {
            $cnt = (int)get_post_meta($my_posts[0]->ID, 'visit_number', true);
            $cnt += 1;
            update_post_meta($my_posts[0]->ID, 'visit_number', $cnt);
        }


        header('Content-Type: image/png');
        echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=');

        die();
    }
}

// this function makes all posts in the default category private
function save_post_callback($post_id, $post, $update)
{

    if ($post->post_type != 'page-visit-counts') {
        return;
    }

    // if (!current_user_can("edit_post", $postID)) {
    //     return $postID;
    // }

    if (defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
        return $postID;
    }

    update_post_meta($post_id, 'embed', '<img src="' . site_url() . '/?d=' . $post->post_name . '" alt="">');
    remove_action('save_post', 'save_post_callback');
    $type = get_post_type();

    switch ($type) {
        case "page-visit-counts":
            $url =  admin_url() . 'edit.php?post_type=page-visit-counts';
            wp_redirect($url);
            exit;
            break;
            
            break;
    }
}
add_action('save_post', 'save_post_callback', 20, 3);


add_filter('manage_page-visit-counts_posts_columns', 'custom_columns');
function custom_columns($columns)
{
    $columns = array(
        'cb' => $columns['cb'],
        'title' => __('Title'),
        'visit_number' => __('Count'),
        'embed' => __('Embed'),
        'date' => __('Date', 'smashing'),
        'author' => __('Author', 'smashing'),
    );
    return $columns;
}


add_action('manage_page-visit-counts_posts_custom_column', 'custom_columns_column', 10, 2);
function custom_columns_column($column, $post_id)
{
    // Image column
    if ($column == 'visit_number') {
        echo get_post_meta($post_id, 'visit_number', true);
    }

    if ($column == 'embed') {
        echo '<code>' . htmlentities(get_post_meta($post_id, 'embed', true)) . '</code>';
    }
}

function my_login_redirect($redirect_to, $request, $user)
{
    //is there a user to check?
    global $user;
    if (isset($user->roles) && is_array($user->roles)) {

        if (in_array('wp_private_counter_role', $user->roles)) {
            // redirect them to the default place
            return admin_url('edit.php?post_type=page-visit-counts');
        } else {
            return home_url();
        }
    } else {
        return $redirect_to;
    }
}
add_filter('login_redirect', 'my_login_redirect', 10, 3);






// Show only posts and media related to logged in author
add_action('pre_get_posts', 'query_set_only_author' );
function query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can('edit_others_posts') ) {
        $wp_query->set( 'author', $current_user->ID );
        add_filter('views_edit-post', 'fix_post_counts');
        add_filter('views_upload', 'fix_media_counts');
    }
}

// Fix post counts
function fix_post_counts($views) {
    global $current_user, $wp_query;
    unset($views['mine']);
    $types = array(
        array( 'status' =>  NULL ),
        array( 'status' => 'publish' ),
        array( 'status' => 'draft' ),
        array( 'status' => 'pending' ),
        array( 'status' => 'trash' )
    );
    foreach( $types as $type ) {
        $query = array(
            'author'      => $current_user->ID,
            'post_type'   => 'post',
            'post_status' => $type['status']
        );
        $result = new WP_Query($query);
        if( $type['status'] == NULL ):
            $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
            $views['all'] = sprintf(__('<a href="%s"'. $class .'>All <span class="count">(%d)</span></a>', 'all'),
                admin_url('edit.php?post_type=page-visit-counts'),
                $result->found_posts);
        elseif( $type['status'] == 'publish' ):
            $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
            $views['publish'] = sprintf(__('<a href="%s"'. $class .'>Published <span class="count">(%d)</span></a>', 'publish'),
                admin_url('edit.php?post_status=publish&post_type=page-visit-counts'),
                $result->found_posts);
        elseif( $type['status'] == 'draft' ):
            $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
            $views['draft'] = sprintf(__('<a href="%s"'. $class .'>Draft'. ((sizeof($result->posts) > 1) ? "s" : "") .' <span class="count">(%d)</span></a>', 'draft'),
                admin_url('edit.php?post_status=draft&post_type=page-visit-counts'),
                $result->found_posts);
        elseif( $type['status'] == 'pending' ):
            $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
            $views['pending'] = sprintf(__('<a href="%s"'. $class .'>Pending <span class="count">(%d)</span></a>', 'pending'),
                admin_url('edit.php?post_status=pending&post_type=page-visit-counts'),
                $result->found_posts);
        elseif( $type['status'] == 'trash' ):
            $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
            $views['trash'] = sprintf(__('<a href="%s"'. $class .'>Trash <span class="count">(%d)</span></a>', 'trash'),
                admin_url('edit.php?post_status=trash&post_type=page-visit-counts'),
                $result->found_posts);
        endif;
    }
    return $views;
}

// Fix media counts
function fix_media_counts($views) {
    global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
    $views = array();
    $count = $wpdb->get_results( "
        SELECT post_mime_type, COUNT( * ) AS num_posts 
        FROM $wpdb->posts 
        WHERE post_type = 'attachment' 
        AND post_author = $current_user->ID 
        AND post_status != 'trash' 
        GROUP BY post_mime_type
    ", ARRAY_A );
    foreach( $count as $row )
        $_num_posts[$row['post_mime_type']] = $row['num_posts'];
    $_total_posts = array_sum($_num_posts);
    $detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] );
    if ( !isset( $total_orphans ) )
        $total_orphans = $wpdb->get_var("
            SELECT COUNT( * ) 
            FROM $wpdb->posts 
            WHERE post_type = 'attachment' 
            AND post_author = $current_user->ID 
            AND post_status != 'trash' 
            AND post_parent < 1
        ");
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ( $matches as $type => $reals )
        foreach ( $reals as $real )
            $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
    $class = ( empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ) ? ' class="current"' : '';
    $views['all'] = "<a href='upload.php'$class>" . sprintf( __('All <span class="count">(%s)</span>', 'uploaded files' ), number_format_i18n( $_total_posts )) . '</a>';
    foreach ( $post_mime_types as $mime_type => $label ) {
        $class = '';
        if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
            continue;
        if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
            $class = ' class="current"';
        if ( !empty( $num_posts[$mime_type] ) )
            $views[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . '</a>';
    }
    $views['detached'] = '<a href="upload.php?detached=1"' . ( $detached ? ' class="current"' : '' ) . '>' . sprintf( __( 'Unattached <span class="count">(%s)</span>', 'detached files' ), $total_orphans ) . '</a>';
    return $views;
}