<?php

namespace Retheme;

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

class Post_View {

    public function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'add_scripts'], 99);
        add_action('rest_api_init', [$this, 'rest_api']);
        add_action('wp_after_insert_post', [$this, 'update_postmeta']);
    }

    /**
     * Enqueue scripts for Ajax post view
     *
     */
    public function add_scripts() {
        if (is_single()) {
            wp_enqueue_script('retheme-post-view', RETHEME_POST_VIEW_ASSETS . 'assets/js/post-view.min.js', false,  '3.0.0', true);
            wp_localize_script(
                'retheme-post-view',
                'retheme_post_view',
                [
                    'apiurl' => rest_url('retheme/v1/post-view'),
                ]
            );
        }
    }


    /**
     * Register Rest API
     *
     * @return void
     */
    public function rest_api() {
        register_rest_route('retheme/v1', 'post-view', [
            'methods'  => 'GET',
            'callback' => [$this, 'result'],
            'permission_callback' => '__return_true',
        ]);
    }

    /**
     * Get rest API result
     * get post view
     *
     * @param [type] $result
     * @return void
     */
    public function result($request) {

        $post_id = intval($request->get_param('id'));

        if (!empty($post_id)) {

            $count = get_post_meta($post_id, 'wp_post_views_count', true);

            if ($count === '') {
                update_post_meta($post_id, 'wp_post_views_count', 1);
            } else {
                $count = (int) $count + 1;
                update_post_meta($post_id, 'wp_post_views_count', $count);
            }

            $post_count = number_format($count, 0, "", ".");
        } else {
            $post_count = 1;
        }

        wp_send_json(['count' => $post_count]);
    }

    /**
     * Set post meta count for first time
     * Post meta needed for show on front popular posts
     * @hook wp_after_insert_post update after updated/saved post
     * @hook wp_head update when single page open
     */
    public function update_postmeta($post_id) {

        if (!get_post_meta($post_id, 'wp_post_views_count', true)) {
            update_post_meta($post_id, 'wp_post_views_count', 1);
        }
    }
}

new Post_View;
