<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'BOOSTIFY_BLOG_AI_POST_VIEW_TRACKER' ) ) : 
    class BOOSTIFY_BLOG_AI_POST_VIEW_TRACKER {

        private $table_name;

        /**
         * Constructor.
         */
        public function __construct() {
            global $wpdb;
            $this->table_name = $wpdb->prefix . 'boostify_blog_ai_post_views';
            
            add_action( 'wp_head', [ $this, 'track_post_view' ] );
            add_action( 'wp_ajax_boostify_blog_ai_get_post_views', [ $this, 'get_post_views_ajax' ] );
            add_action( 'wp_ajax_nopriv_boostify_blog_ai_get_post_views', [ $this, 'get_post_views_ajax' ] );
            
            // Frontend functionality
            add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_frontend_assets' ] );
            add_shortcode( 'boostify_blog_ai_post_views', [ $this, 'post_views_shortcode' ] );
            add_filter( 'the_content', [ $this, 'auto_append_post_views' ], 20 );
            
            // Admin functionality
            // add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );
        }

        /**
         * Create the post views tracking table.
         */
        public function create_table() {
            global $wpdb;

            $charset_collate = $wpdb->get_charset_collate();

            $sql = "CREATE TABLE {$this->table_name} (
                id int(11) NOT NULL AUTO_INCREMENT,
                post_id bigint(20) NOT NULL,
                ip_address varchar(45) NOT NULL,
                location varchar(255) DEFAULT '',
                count int(11) DEFAULT 1,
                created_at datetime DEFAULT CURRENT_TIMESTAMP,
                updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY post_id (post_id),
                KEY ip_address (ip_address),
                UNIQUE KEY unique_post_ip (post_id, ip_address)
            ) $charset_collate;";

            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $sql );
        }

        /**
         * Track post view when a single post is accessed.
         */
        public function track_post_view() {
            if ( is_single() && 'post' == get_post_type() ) {
                global $post, $wpdb;

                $post_id = $post->ID;
                $ip_address = $this->get_user_ip();
                $location = $this->get_user_location( $ip_address );

                // Check if this IP has already viewed this post
                $existing_view = $wpdb->get_row( $wpdb->prepare(
                    "SELECT * FROM {$this->table_name} WHERE post_id = %d AND ip_address = %s",
                    $post_id,
                    $ip_address
                ) );

                if ( $existing_view ) {
                    // Update existing record
                    $wpdb->update(
                        $this->table_name,
                        [
                            'count' => $existing_view->count + 1,
                            'location' => $location,
                            'updated_at' => current_time( 'mysql' )
                        ],
                        [
                            'post_id' => $post_id,
                            'ip_address' => $ip_address
                        ],
                        [ '%d', '%s', '%s' ],
                        [ '%d', '%s' ]
                    );
                } else {
                    // Insert new record
                    $wpdb->insert(
                        $this->table_name,
                        [
                            'post_id' => $post_id,
                            'ip_address' => $ip_address,
                            'location' => $location,
                            'count' => 1,
                            'created_at' => current_time( 'mysql' )
                        ],
                        [ '%d', '%s', '%s', '%d', '%s' ]
                    );
                }
            }
        }

        /**
         * Get user's IP address.
         */
        private function get_user_ip() {
            if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
                return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
            } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
                return sanitize_text_field( $_SERVER['HTTP_X_FORWARDED_FOR'] );
            } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
                return sanitize_text_field( $_SERVER['REMOTE_ADDR'] );
            }
            return '0.0.0.0';
        }

        /**
         * Get user's location based on IP address.
         * This is a basic implementation - you can enhance it with a geolocation service.
         */
        private function get_user_location( $ip_address ) {
            // Basic location detection - you can integrate with services like ipapi.co, geojs.io, etc.
            if ( $ip_address === '127.0.0.1' || $ip_address === '::1' || $ip_address === '0.0.0.0' ) {
                return 'Local/Unknown';
            }

            // Simple geolocation using a free service (optional)
            $location = 'Unknown';
            
            // You can uncomment and modify this to use a geolocation service
            /*
            $response = wp_remote_get( "http://ip-api.com/json/{$ip_address}" );
            if ( ! is_wp_error( $response ) ) {
                $body = wp_remote_retrieve_body( $response );
                $data = json_decode( $body, true );
                if ( $data && $data['status'] === 'success' ) {
                    $location = $data['city'] . ', ' . $data['country'];
                }
            }
            */

            return $location;
        }

        /**
         * Get post views count for a specific post.
         */
        public function get_post_views( $post_id ) {
            global $wpdb;

            $total_views = $wpdb->get_var( $wpdb->prepare(
                "SELECT SUM(count) FROM {$this->table_name} WHERE post_id = %d",
                $post_id
            ) );

            return $total_views ? intval( $total_views ) : 0;
        }

        /**
         * Get unique visitors count for a specific post.
         */
        public function get_unique_visitors( $post_id ) {
            global $wpdb;

            $unique_visitors = $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(DISTINCT ip_address) FROM {$this->table_name} WHERE post_id = %d",
                $post_id
            ) );

            return $unique_visitors ? intval( $unique_visitors ) : 0;
        }

        /**
         * Ajax handler to get post views.
         */
        public function get_post_views_ajax() {
            // Verify nonce for security
            if ( ! isset( $_POST['nonce'] ) ||  ! wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'boostify_blog_ai_post_views_nonce' ) ) {
                wp_die( 'Security check failed' );
            }

            if ( ! isset( $_POST['post_id'] ) ) {
                wp_die( 'Post ID is required' );
            }

            $post_id = intval( sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) );
            $total_views = $this->get_post_views( $post_id );
            $unique_visitors = $this->get_unique_visitors( $post_id );

            wp_send_json_success( [
                'total_views' => $total_views,
                'unique_visitors' => $unique_visitors
            ] );
        }

        /**
         * Enqueue frontend assets.
         */
        public function enqueue_frontend_assets() {
            // Only load on single posts and pages, or if shortcode is present
            if ( ! is_single() && ! is_page() && ! $this->has_post_views_shortcode() ) {
                return;
            }

            wp_enqueue_script( 
                'bbai-post-views', 
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'js/post-views.js', 
                array( 'jquery' ), 
                '1.0.0', 
                true 
            );

            wp_enqueue_style( 
                'bbai-post-views', 
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'css/post-views.css', 
                array(), 
                '1.0.0' 
            );

            // Localize script with AJAX URL and nonce
            wp_localize_script( 'bbai-post-views', 'boostify_blog_ai_post_views', [
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'boostify_blog_ai_post_views_nonce' ),
                'refresh_interval' => get_option( 'boostify_blog_ai_views_refresh_interval', 0 ),
            ] );
        }

        /**
         * Check if current content has post views shortcode.
         */
        private function has_post_views_shortcode() {
            global $post;
            if ( $post && has_shortcode( $post->post_content, 'boostify_blog_ai_post_views' ) ) {
                return true;
            }
            return false;
        }

        /**
         * Post views shortcode handler.
         */
        public function post_views_shortcode( $atts ) {
            $atts = shortcode_atts( [
                'post_id' => get_the_ID(),
                'display' => 'both', // 'both', 'views-only', 'unique-only'
                'format' => 'default', // 'default', 'icon', 'label', 'short'
                'style' => 'default', // 'default', 'minimal', 'badge'
                'refresh' => 'false', // 'true', 'false'
                'class' => ''
            ], $atts, 'boostify_blog_ai_post_views' );

            if ( ! $atts['post_id'] ) {
                return '';
            }

            $classes = [ 'bbai-post-views-shortcode' ];
            if ( $atts['style'] !== 'default' ) {
                $classes[] = 'style-' . $atts['style'];
            }
            if ( $atts['class'] ) {
                $classes[] = $atts['class'];
            }

            $refresh_button = '';
            if ( $atts['refresh'] === 'true' ) {
                $refresh_button = '<button class="bbai-refresh-views" type="button">↻</button>';
            }

            $output = sprintf(
                '<div class="%s">
                    <div class="bbai-post-views-counter" 
                         data-post-id="%d" 
                         data-display-type="%s" 
                         data-format="%s">
                        Loading...
                    </div>
                    %s
                </div>',
                esc_attr( implode( ' ', $classes ) ),
                intval( $atts['post_id'] ),
                esc_attr( $atts['display'] ),
                esc_attr( $atts['format'] ),
                $refresh_button
            );

            return $output;
        }

        /**
         * Automatically append post views to content.
         */
        public function auto_append_post_views( $content ) {
            // Only on single posts
            if ( ! is_single() || get_post_type() !== 'post' ) {
                return $content;
            }

            // Check if auto-append is enabled
            $auto_append = get_option( 'boostify_blog_ai_views_auto_append', 'disabled' );
            if ( $auto_append === 'disabled' ) {
                return $content;
            }

            // Don't append if shortcode is already present
            if ( has_shortcode( $content, 'boostify_blog_ai_post_views' ) ) {
                return $content;
            }

            $post_id = get_the_ID();
            $display_format = get_option( 'boostify_blog_ai_views_auto_format', 'default' );
            $display_type = get_option( 'boostify_blog_ai_views_auto_display', 'both' );

            $views_html = sprintf(
                '<div class="bbai-post-views-auto">
                    <div class="bbai-post-views-counter" 
                         data-post-id="%d" 
                         data-display-type="%s" 
                         data-format="%s">
                        Loading views...
                    </div>
                </div>',
                $post_id,
                esc_attr( $display_type ),
                esc_attr( $display_format )
            );

            // Append or prepend based on settings
            if ( $auto_append === 'prepend' ) {
                return $views_html . $content;
            } else {
                return $content . $views_html;
            }
        }

        /**
         * Add admin menu for post views settings.
         */
        public function add_admin_menu() {
            add_options_page(
                'Post Views Settings',
                'Post Views',
                'manage_options',
                'bbai-post-views',
                [ $this, 'admin_page' ]
            );
        }

        /**
         * Admin settings page.
         */
        public function admin_page() {
            if ( isset( $_POST['submit'] ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'boostify_blog_ai_views_settings' ) ) {
                update_option( 'boostify_blog_ai_views_auto_append', sanitize_text_field( wp_unslash( $_POST['auto_append'] ) ) );
                update_option( 'boostify_blog_ai_views_auto_display', sanitize_text_field( wp_unslash( $_POST['auto_display'] ) ) );
                update_option( 'boostify_blog_ai_views_auto_format', sanitize_text_field( wp_unslash( $_POST['auto_format'] ) ) );
                update_option( 'boostify_blog_ai_views_refresh_interval', intval( sanitize_text_field( wp_unslash( $_POST['refresh_interval'] ) ) ) );
                echo '<div class="notice notice-success"><p>Settings saved!</p></div>';
            }

            $auto_append = get_option( 'boostify_blog_ai_views_auto_append', 'disabled' );
            $auto_display = get_option( 'boostify_blog_ai_views_auto_display', 'both' );
            $auto_format = get_option( 'boostify_blog_ai_views_auto_format', 'default' );
            $refresh_interval = get_option( 'boostify_blog_ai_views_refresh_interval', 0 );
            ?>
            <div class="wrap">
                <h1>Post Views Settings</h1>
                
                <form method="post" action="">
                    <?php wp_nonce_field( 'boostify_blog_ai_views_settings' ); ?>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row">Auto Append to Posts</th>
                            <td>
                                <select name="auto_append">
                                    <option value="disabled" <?php selected( $auto_append, 'disabled' ); ?>>Disabled</option>
                                    <option value="append" <?php selected( $auto_append, 'append' ); ?>>Append to end</option>
                                    <option value="prepend" <?php selected( $auto_append, 'prepend' ); ?>>Prepend to beginning</option>
                                </select>
                                <p class="description">Automatically display post views on all single posts.</p>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">Display Type</th>
                            <td>
                                <select name="auto_display">
                                    <option value="both" <?php selected( $auto_display, 'both' ); ?>>Views and Unique Visitors</option>
                                    <option value="views-only" <?php selected( $auto_display, 'views-only' ); ?>>Views Only</option>
                                    <option value="unique-only" <?php selected( $auto_display, 'unique-only' ); ?>>Unique Visitors Only</option>
                                </select>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">Display Format</th>
                            <td>
                                <select name="auto_format">
                                    <option value="default" <?php selected( $auto_format, 'default' ); ?>>Default Text</option>
                                    <option value="icon" <?php selected( $auto_format, 'icon' ); ?>>With Icons</option>
                                    <option value="label" <?php selected( $auto_format, 'label' ); ?>>With Labels</option>
                                    <option value="short" <?php selected( $auto_format, 'short' ); ?>>Numbers Only</option>
                                </select>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">Auto Refresh Interval</th>
                            <td>
                                <input type="number" name="refresh_interval" value="<?php echo esc_attr( $refresh_interval ); ?>" min="0" step="1" />
                                <p class="description">Seconds (0 = disabled). How often to automatically refresh view counts.</p>
                            </td>
                        </tr>
                    </table>
                    
                    <?php submit_button(); ?>
                </form>
                
                <h2>Usage</h2>
                <h3>Shortcode Examples:</h3>
                <code>[boostify_blog_ai_post_views]</code> - Basic usage<br>
                <code>[boostify_blog_ai_post_views display="views-only" format="icon"]</code> - Views only with icons<br>
                <code>[boostify_blog_ai_post_views style="badge" refresh="true"]</code> - Badge style with refresh button<br>
                
                <h3>PHP Functions:</h3>
                <code>echo boostify_blog_ai_get_post_views();</code> - Get views count<br>
                <code>echo boostify_blog_ai_display_post_views();</code> - Display formatted views<br>
            </div>
            <?php
        }

        /**
         * Get post views statistics for admin display.
         */
        public function get_post_views_stats( $post_id ) {
            global $wpdb;

            $stats = $wpdb->get_results( $wpdb->prepare(
                "SELECT ip_address, location, count, created_at, updated_at 
                FROM {$this->table_name} 
                WHERE post_id = %d 
                ORDER BY updated_at DESC",
                $post_id
            ) );

            return $stats;
        }

        /**
         * Drop the table on plugin uninstall (optional method).
         */
        public function drop_table() {
            global $wpdb;
            $wpdb->query( "DROP TABLE IF EXISTS {$this->table_name}" );
        }
    }
endif; 