<?php
/**
 * Name: Post Views Counter
 * Description: Track and display post view counts for analytics and content popularity metrics with database storage to identify trending content and most viewed posts
 * Category: Content
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Track Popularity",
 *     "description": "See which posts and pages are most viewed to understand what content resonates with your audience."
 *   },
 *   {
 *     "title": "Content Strategy",
 *     "description": "Use view counts to identify trending topics and create more of the content your visitors want."
 *   }
 * ]
 * Added: 2025-09-10
 * Tags: views, counter, analytics, statistics, popular
 * WhereToFind: {
 *   "location": "Posts List & Frontend",
 *   "url": "edit.php",
 *   "instructions": "View count column in posts list, use [post_views] shortcode on frontend",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardPostViewsCounter {

    public function __construct() {
        add_action('wp', [$this, 'track_post_views']);
        add_shortcode('post_views', [$this, 'display_views_shortcode']);
        add_filter('manage_posts_columns', [$this, 'add_views_column']);
        add_action('manage_posts_custom_column', [$this, 'display_views_column'], 10, 2);
        add_filter('manage_edit-post_sortable_columns', [$this, 'make_views_sortable']);
    }

    public function track_post_views() {
        if (!is_single()) {
            return;
        }
        
        global $post;

        if (!$post || !is_object($post) || !isset($post->ID)) {
            return;
        }

        // Don't count logged-in users (optional - remove this if you want to count all visits)
        if (is_user_logged_in()) {
            return;
        }

        $post_id = $post->ID;
        $count_key = 'post_views_count';
        $count = get_post_meta($post_id, $count_key, true);
        
        if ($count === '') {
            $count = 1;
            add_post_meta($post_id, $count_key, '1');
        } else {
            $count = intval($count) + 1;
            update_post_meta($post_id, $count_key, $count);
        }
    }
    
    public function get_post_views($post_id) {
        $count = get_post_meta($post_id, 'post_views_count', true);
        return $count ? $count : 0;
    }
    
    public function display_views_shortcode($atts) {
        global $post;

        if (!$post) {
            return '';
        }

        $views = $this->get_post_views($post->ID);
        /* translators: %s: number of views */
        return sprintf(esc_html__('%s views', 'wpswitchboard'), number_format($views));
    }

    public function add_views_column($columns) {
        $columns['post_views'] = esc_html__('Views', 'wpswitchboard');
        return $columns;
    }
    
    public function display_views_column($column_name, $post_id) {
        if ($column_name === 'post_views') {
            echo number_format($this->get_post_views($post_id));
        }
    }
    
    public function make_views_sortable($columns) {
        $columns['post_views'] = 'post_views';
        return $columns;
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [
                'post_views_count',
            ],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardPostViewsCounter();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
