<?php
namespace PageVICO\Admin\Views;

defined( 'ABSPATH' ) || exit;

use PageVICO\Cache\CacheManager;

class TopDevices {
	public static function render() {
		global $wpdb;

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed for GET parameters
		$date_from    = isset( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : date( 'Y-m-d', current_time('timestamp') - (7 * 86400) );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed for GET parameters
		$date_to      = isset( $_GET['to'] ) ? sanitize_text_field( wp_unslash( $_GET['to'] ) ) : date( 'Y-m-d', current_time('timestamp') );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized	 -- Nonce verification is not needed for GET parameters
		$paged        = max( 1, (int) ( wp_unslash( $_GET['paged'] ?? 1 ) ) );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed for GET parameters
		$limit        = get_option( 'posts_per_page', 25 );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed for GET parameters
		$offset       = ( $paged - 1 ) * $limit;

		$cache_key = CacheManager::generateDateKey( 'PageVICO_top_devices', $date_from, $date_to, $paged );
		$total_key = CacheManager::generateDateKey( 'PageVICO_top_devices_total', $date_from, $date_to );

		$results = CacheManager::get( $cache_key );
		$total   = CacheManager::get( $total_key );

		if ( $results === false || $total === false ) {
			// First, let's check if we have any data in the tables
			$check_data = $wpdb->get_results(
				$wpdb->prepare(
					"
					SELECT 
						'pagevico_sessions' as table_name,
						COUNT(*) as total_records,
						COUNT(CASE WHEN device_type IS NOT NULL AND device_type != '' THEN 1 END) as valid_devices,
						COUNT(CASE WHEN browser IS NOT NULL AND browser != '' THEN 1 END) as valid_browsers,
						COUNT(CASE WHEN os IS NOT NULL AND os != '' THEN 1 END) as valid_os,
						MIN(first_seen) as earliest_date,
						MAX(first_seen) as latest_date
					FROM {$wpdb->prefix}pagevico_sessions
					WHERE first_seen BETWEEN %s AND %s
					UNION ALL
					SELECT 
						'pagevico_pageviews' as table_name,
						COUNT(*) as total_records,
						COUNT(CASE WHEN session_id IS NOT NULL THEN 1 END) as valid_sessions,
						COUNT(CASE WHEN session_id IS NOT NULL THEN 1 END) as valid_sessions,
						COUNT(CASE WHEN session_id IS NOT NULL THEN 1 END) as valid_sessions,
						MIN(created_at) as earliest_date,
						MAX(created_at) as latest_date
					FROM {$wpdb->prefix}pagevico_pageviews
					WHERE created_at BETWEEN %s AND %s
					",
					$date_from . ' 00:00:00',
					$date_to . ' 23:59:59',
					$date_from . ' 00:00:00',
					$date_to . ' 23:59:59'
				),
				ARRAY_A
			);


			// Modified main query with more inclusive conditions
			$results = $wpdb->get_results(
				$wpdb->prepare(
					"
					SELECT 
						COALESCE(s.device_type, 'unknown') as device_type,
						COALESCE(s.browser, 'unknown') as browser,
						COALESCE(s.os, 'unknown') as os,
						COUNT(DISTINCT s.session_id) as sessions,
						COUNT(pv.id) as pageviews,
						ROUND(COUNT(pv.id) / NULLIF(COUNT(DISTINCT s.session_id), 0), 2) as pages_per_session,
						ROUND(AVG(NULLIF(s.screen_width, 0))) as avg_screen_width,
						ROUND(AVG(NULLIF(s.screen_height, 0))) as avg_screen_height
					FROM {$wpdb->prefix}pagevico_sessions s
					LEFT JOIN {$wpdb->prefix}pagevico_pageviews pv ON s.session_id = pv.session_id
					WHERE (s.first_seen BETWEEN %s AND %s OR pv.created_at BETWEEN %s AND %s)
					GROUP BY 
						COALESCE(s.device_type, 'unknown'), 
						COALESCE(s.browser, 'unknown'), 
						COALESCE(s.os, 'unknown')
					HAVING sessions > 0
					ORDER BY sessions DESC
					LIMIT %d OFFSET %d
					",
					$date_from . ' 00:00:00',
					$date_to . ' 23:59:59',
					$date_from . ' 00:00:00',
					$date_to . ' 23:59:59',
					$limit,
					$offset
				),
				ARRAY_A
			);

			if (empty($results)) {
				// Try a simpler query to see if we can get any data
				$simple_check = $wpdb->get_results(
					$wpdb->prepare(
						"
						SELECT 
							device_type,
							browser,
							os,
							COUNT(*) as count
						FROM {$wpdb->prefix}pagevico_sessions
						WHERE first_seen BETWEEN %s AND %s
						GROUP BY device_type, browser, os
						LIMIT 5
						",
						$date_from . ' 00:00:00',
						$date_to . ' 23:59:59'
					),
					ARRAY_A
				);
			}

			// Get total count with the same conditions
			$total = $wpdb->get_var(
				$wpdb->prepare(
					"
					SELECT COUNT(DISTINCT CONCAT(
						COALESCE(device_type, 'unknown'),
						COALESCE(browser, 'unknown'),
						COALESCE(os, 'unknown')
					))
					FROM {$wpdb->prefix}pagevico_sessions
					WHERE first_seen BETWEEN %s AND %s
					",
					$date_from . ' 00:00:00',
					$date_to . ' 23:59:59'
				)
			);

			if ($wpdb->last_error || $total === null) {
				$total = 0;
			}

			CacheManager::set($cache_key, $results);
			CacheManager::set($total_key, $total);
		}

		include PageVICO_PLUGIN_DIR . 'templates/pages/top-devices.php';
	}

	private static function getDeviceIcon( $device_type ) {
		$icons = array(
			'desktop' => 'dashicons-desktop',
			'mobile'  => 'dashicons-smartphone',
			'tablet'  => 'dashicons-tablet',
			'unknown' => 'dashicons-welcome-view-site',
		);

		return $icons[ strtolower( $device_type ) ] ?? $icons['unknown'];
	}

	private static function getBrowserIcon( $browser ) {
		$icons = array(
			'chrome'  => 'chrome',
			'firefox' => 'firefox',
			'safari'  => 'safari',
			'edge'    => 'edge',
			'opera'   => 'opera',
			'ie'      => 'ie',
		);

		$browser_key = strtolower( $browser );
		$icon_name   = $icons[ $browser_key ] ?? 'globe';

		return "browser-{$icon_name}";
	}
}
