<?php

namespace PageVICO\Admin;

defined( 'ABSPATH' ) || exit;
use PageVICO\Cache\CacheManager;
class AdminPage {
    public static function init() {
        add_action( 'admin_menu', array(__CLASS__, 'addMenuPage') );
        add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueueAssets') );
    }

    public static function addMenuPage() {
        add_menu_page(
            // translators: %s: Plugin name
            __( 'Analytics', 'page-visit-counter-analytics' ),
            // translators: %s: Menu name
            __( 'Analytics', 'page-visit-counter-analytics' ),
            'manage_options',
            'pagevico-dashboard',
            array(__CLASS__, 'renderDashboard'),
            'dashicons-chart-area',
            30
        );
    }

    public static function enqueueAssets( $hook ) {
        if ( strpos( $hook, 'pagevico' ) === false ) {
            return;
        }
        // Enqueue admin styles
        wp_register_style(
            'pagevico-admin-styles',
            PageVICO_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            PageVICO_VERSION
        );
        // Register Tailwind CDN script to load utilities
        wp_register_script(
            'pagevico-tailwind',
            'https://cdn.tailwindcss.com/?v=3.4.2',
            array(),
            '3.4.2',
            false
        );
        // Enqueue jVectorMap CSS
        wp_register_style(
            'pagevico-jvectormap',
            'https://cdn.jsdelivr.net/npm/jsvectormap@1.5.3/dist/css/jsvectormap.min.css',
            array(),
            '1.5.3'
        );
        wp_enqueue_style( 'pagevico-admin-styles' );
        wp_enqueue_script( 'pagevico-tailwind' );
        // Only load jVectorMap on the world map page
        if ( isset( $_GET['page'] ) && $_GET['page'] === 'pagevico-world-map' ) {
            wp_enqueue_style( 'pagevico-jvectormap' );
        }
        // Register and enqueue Bootstrap JS Bundle
        // Register and enqueue Chart.js
        wp_register_script(
            'pagevico-chartjs',
            PageVICO_PLUGIN_URL . 'assets/js/chart.js',
            array(),
            PageVICO_VERSION,
            true
        );
        wp_enqueue_script( 'pagevico-chartjs' );
        // Register and enqueue dashboard scripts
        wp_register_script(
            'pagevico-dashboard',
            PageVICO_PLUGIN_URL . 'assets/js/dashboard.js',
            array('pagevico-chartjs', 'jquery'),
            PageVICO_VERSION,
            true
        );
        wp_enqueue_script( 'pagevico-dashboard' );
        wp_register_script(
            'pagevico-chart-admin',
            PageVICO_PLUGIN_URL . 'assets/js/chart-admin.js',
            array('pagevico-chartjs', 'jquery'),
            PageVICO_VERSION,
            true
        );
        wp_enqueue_script( 'pagevico-chart-admin' );
        // Prepare data for localization
        $pageviewsData = self::getPageviewsLast7Days();
        $sessionsData = self::getSessionsLast7Days();
        // Localize script with data
        wp_localize_script( 'pagevico-dashboard', 'pagevicoTracker', array(
            'realtime_url'   => rest_url( 'pagevico/v1/realtime' ),
            'nonce'          => wp_create_nonce( 'wp_rest' ),
            'chart_labels'   => $pageviewsData['labels'],
            'chart_values'   => $pageviewsData['values'],
            'session_values' => $sessionsData['values'],
        ) );
    }

    public static function getCountriesCount() {
        global $wpdb;
        $cache_key = 'PageVICO_countries_count_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (int) $wpdb->get_var( "SELECT COUNT(DISTINCT country) FROM {$wpdb->prefix}pagevico_sessions" );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getTodayPageviews() {
        global $wpdb;
        $cache_key = 'PageVICO_today_pageviews_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            $today = current_time( 'Y-m-d' );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_pageviews WHERE DATE(created_at) = %s", $today ) );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getTodaySessions() {
        global $wpdb;
        $cache_key = 'PageVICO_today_sessions_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            $today = current_time( 'Y-m-d' );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_sessions WHERE DATE(first_seen) = %s", $today ) );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    /**
     * Get total pageviews for all time
     *
     * @return int Total pageviews
     */
    public static function getAllTimePageviews() {
        global $wpdb;
        $cache_key = 'PageVICO_all_time_pageviews';
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_pageviews" );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    /**
     * Get total sessions for all time
     *
     * @return int Total sessions
     */
    public static function getAllTimeSessions() {
        global $wpdb;
        $cache_key = 'PageVICO_all_time_sessions';
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_sessions WHERE is_bot = 0" );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getBounceRate() {
        global $wpdb;
        $cache_key = 'PageVICO_today_bounce_rate_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            $today = current_time( 'Y-m-d' );
            // Total sessions for today (exclude bots if needed)
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_sessions \n\t\t\t\t\tWHERE DATE(first_seen) = %s AND is_bot = 0", $today ) );
            // Sessions with only 1 pageview for today
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $bounces = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM (\n\t\t\t\t\t\tSELECT session_id\n\t\t\t\t\t\tFROM {$wpdb->prefix}pagevico_pageviews\n\t\t\t\t\t\tWHERE DATE(created_at) = %s\n\t\t\t\t\t\tGROUP BY session_id\n\t\t\t\t\t\tHAVING COUNT(*) = 1\n\t\t\t\t\t) AS bounce_sessions", $today ) );
            $result = ( $total === 0 ? 0 : round( $bounces / $total * 100, 1 ) );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getPageviewsLast7Days() {
        global $wpdb;
        $cache_key = 'PageVICO_pageviews_7days_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $results = $wpdb->get_results( $wpdb->prepare( "\n                SELECT DATE(created_at) as date, COUNT(*) as views\n                FROM {$wpdb->prefix}pagevico_pageviews\n                WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL %d DAY)\n                GROUP BY DATE(created_at)\n                ORDER BY DATE(created_at) ASC\n            ", 6 ), ARRAY_A );
            $data = array();
            $labels = array();
            for ($i = 6; $i >= 0; $i--) {
                $day = date( 'Y-m-d', current_time( 'timestamp' ) - $i * 86400 );
                $labels[] = date( 'M j', current_time( 'timestamp' ) - $i * 86400 );
                $data[$day] = 0;
            }
            foreach ( $results as $row ) {
                if ( isset( $data[$row['date']] ) ) {
                    $data[$row['date']] = (int) $row['views'];
                }
            }
            $result = array(
                'labels' => array_values( $labels ),
                'values' => array_values( $data ),
            );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function renderDashboard() {
        include PageVICO_PLUGIN_DIR . 'templates/dashboard.php';
    }

    public static function cleanURL( $url ) {
        $parsed = wp_parse_url( $url );
        // Handle URLs with query parameters and different language paths
        if ( isset( $parsed['path'] ) ) {
            $path = $parsed['path'];
            // Remove trailing slashes for consistency
            $path = rtrim( $path, '/' );
            // If there's a query string, add it back in a readable format
            if ( isset( $parsed['query'] ) ) {
                $path .= '?' . $parsed['query'];
            }
            // Handle URLs with fragments (anchors)
            if ( isset( $parsed['fragment'] ) ) {
                $path .= '#' . $parsed['fragment'];
            }
            return $path;
        }
        return $url;
    }

    public static function getAvgSessionDuration() {
        global $wpdb;
        $cache_key = 'PageVICO_avg_session_duration';
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (float) $wpdb->get_var( "SELECT AVG(TIMESTAMPDIFF(SECOND, first_seen, last_seen)) FROM {$wpdb->prefix}pagevico_sessions" );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    /**
     * Get average session duration for today's sessions
     *
     * @return float Average session duration in seconds
     */
    public static function getAverageSessionDuration() {
        global $wpdb;
        $cache_key = 'PageVICO_today_avg_session_duration_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            $today = current_time( 'Y-m-d' );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = (float) $wpdb->get_var( $wpdb->prepare( "SELECT AVG(TIMESTAMPDIFF(SECOND, first_seen, last_seen)) \n\t\t\t\t\tFROM {$wpdb->prefix}pagevico_sessions \n\t\t\t\t\tWHERE DATE(first_seen) = %s", $today ) );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function formatDuration( $seconds ) {
        $seconds = (int) $seconds;
        if ( $seconds <= 0 ) {
            return '0s';
        }
        $hours = floor( $seconds / 3600 );
        $minutes = floor( $seconds % 3600 / 60 );
        $remainingSeconds = $seconds % 60;
        $parts = array();
        if ( $hours > 0 ) {
            $parts[] = "{$hours}h";
        }
        if ( $minutes > 0 ) {
            $parts[] = "{$minutes}m";
        }
        if ( $hours === 0 && $remainingSeconds > 0 ) {
            $parts[] = "{$remainingSeconds}s";
        }
        return implode( ' ', $parts );
    }

    public static function getPagesPerSession() {
        global $wpdb;
        $cache_key = CacheManager::generateTimeKey( 'PageVICO_pages_per_session' );
        $result = CacheManager::get( $cache_key );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $views = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_pageviews" );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $sessions = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pagevico_sessions" );
            $result = ( $sessions === 0 ? 0 : round( $views / $sessions, 2 ) );
            CacheManager::set( $cache_key, $result );
        }
        return $result;
    }

    public static function getTopCountries( $limit = 10 ) {
        global $wpdb;
        $cache_key = CacheManager::generateTimeKey( 'PageVICO_top_countries_' . $limit );
        $result = CacheManager::get( $cache_key );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = $wpdb->get_results( $wpdb->prepare( "\n                SELECT country, COUNT(*) as total\n                FROM {$wpdb->prefix}pagevico_sessions\n                WHERE country IS NOT NULL AND country != ''\n                GROUP BY country\n                ORDER BY total DESC\n                LIMIT %d\n            ", intval( $limit ) ), ARRAY_A );
            CacheManager::set( $cache_key, $result );
        }
        return $result;
    }

    public static function getTopDevices( $limit = 3 ) {
        global $wpdb;
        $cache_key = CacheManager::generateTimeKey( 'PageVICO_top_devices_' . $limit );
        $result = CacheManager::get( $cache_key );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = $wpdb->get_results( $wpdb->prepare( "\n                SELECT device_type, COUNT(*) as total\n                FROM {$wpdb->prefix}pagevico_sessions\n                GROUP BY device_type\n                ORDER BY total DESC\n                LIMIT %d\n            ", intval( $limit ) ), ARRAY_A );
            CacheManager::set( $cache_key, $result );
        }
        return $result;
    }

    public static function getTopBrowsers( $limit = 5 ) {
        global $wpdb;
        $cache_key = CacheManager::generateTimeKey( 'PageVICO_top_browsers_' . $limit );
        $result = CacheManager::get( $cache_key );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = $wpdb->get_results( $wpdb->prepare( "\n                SELECT browser, COUNT(*) as total\n                FROM {$wpdb->prefix}pagevico_sessions\n                WHERE browser IS NOT NULL AND browser != ''\n                GROUP BY browser\n                ORDER BY total DESC\n                LIMIT %d\n            ", intval( $limit ) ), ARRAY_A );
            CacheManager::set( $cache_key, $result );
        }
        return $result;
    }

    public static function getSessionsLast7Days() {
        global $wpdb;
        $cache_key = 'PageVICO_sessions_7days_' . current_time( 'Y-m-d' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $results = $wpdb->get_results( $wpdb->prepare( "\n                SELECT DATE(first_seen) as date, COUNT(*) as sessions\n                FROM {$wpdb->prefix}pagevico_sessions\n                WHERE first_seen >= DATE_SUB(CURDATE(), INTERVAL %d DAY)\n                GROUP BY DATE(first_seen)\n                ORDER BY DATE(first_seen) ASC\n            ", 6 ), ARRAY_A );
            $data = array();
            $labels = array();
            for ($i = 6; $i >= 0; $i--) {
                $day = date( 'Y-m-d', current_time( 'timestamp' ) - $i * 86400 );
                $labels[] = $day;
                $data[$day] = 0;
            }
            foreach ( $results as $row ) {
                $data[$row['date']] = (int) $row['sessions'];
            }
            $result = array(
                'labels' => array_values( $labels ),
                'values' => array_values( $data ),
            );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getTopPosts( $limit = 10 ) {
        global $wpdb;
        $cache_key = 'PageVICO_top_posts_' . $limit . '_' . current_time( 'Y-m-d_H' );
        $result = wp_cache_get( $cache_key, 'pagevico' );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $result = $wpdb->get_results( $wpdb->prepare( "\n                SELECT pv.page_url, COUNT(*) as total_views, p.post_title\n                FROM {$wpdb->prefix}pagevico_pageviews pv\n                LEFT JOIN {$wpdb->posts} p ON p.ID = pv.post_id\n                WHERE pv.post_type = 'post'\n                AND (p.post_status = 'publish' OR p.post_status IS NULL)\n                GROUP BY pv.page_url, p.post_title\n                ORDER BY total_views DESC\n                LIMIT %d\n            ", intval( $limit ) ), ARRAY_A );
            wp_cache_set(
                $cache_key,
                $result,
                'pagevico',
                15 * MINUTE_IN_SECONDS
            );
        }
        return $result;
    }

    public static function getSessionsByDay( $days = 7 ) {
        global $wpdb;
        $cache_key = CacheManager::generateTimeKey( 'PageVICO_sessions_by_day_' . $days );
        $result = CacheManager::get( $cache_key );
        if ( $result === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe query, no caching needed for reads
            $results = $wpdb->get_results( $wpdb->prepare( "\n                SELECT DATE(first_seen) as date, COUNT(*) as sessions\n                FROM {$wpdb->prefix}pagevico_sessions\n                WHERE first_seen >= DATE_SUB(CURDATE(), INTERVAL %d DAY)\n                GROUP BY DATE(first_seen)\n                ORDER BY date ASC\n            ", intval( $days ) ), ARRAY_A );
            $data = array();
            $labels = array();
            for ($i = 6; $i >= 0; $i--) {
                $day = date( 'Y-m-d', current_time( 'timestamp' ) - $i * 86400 );
                $labels[] = $day;
                $data[$day] = 0;
            }
            foreach ( $results as $row ) {
                $data[$row['date']] = (int) $row['sessions'];
            }
            $result = array(
                'labels' => array_values( $labels ),
                'values' => array_values( $data ),
            );
            CacheManager::set( $cache_key, $result );
        }
        return $result;
    }

}
