<?php
/**
 * Shois Chat Button — Analytics Tracker (Server-side)
 *
 * Stores click/impression data in options (lightweight).
 * Provides aggregation methods for the analytics dashboard.
 *
 * @package ShoisChatButton
 */

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

/**
 * Class SHCB_Analytics
 *
 * Handles analytics data storage and retrieval.
 */
class SHCB_Analytics {

	/** Option key for analytics data. */
	const OPTION_KEY = 'shcb_analytics_data';

	/**
	 * Record an event.
	 *
	 * @param string $event_type Event type (impression, click, platform_click).
	 * @param array  $meta       Additional meta data.
	 * @return bool True on success.
	 */
	public static function record_event( $event_type, $meta = array() ) {
		$data = get_option( self::OPTION_KEY, array() );

		$today = gmdate( 'Y-m-d' );

		if ( ! isset( $data[ $today ] ) ) {
			$data[ $today ] = array(
				'impressions'     => 0,
				'clicks'          => 0,
				'platform_clicks' => array(),
				'devices'         => array( 'mobile' => 0, 'desktop' => 0 ),
			);
		}

		$event_type = sanitize_key( $event_type );

		switch ( $event_type ) {
			case 'impression':
				$data[ $today ]['impressions']++;
				break;

			case 'click':
				$data[ $today ]['clicks']++;
				$device = ! empty( $meta['device'] ) ? sanitize_key( $meta['device'] ) : 'desktop';
				if ( isset( $data[ $today ]['devices'][ $device ] ) ) {
					$data[ $today ]['devices'][ $device ]++;
				}
				break;

			case 'platform_click':
				$platform = ! empty( $meta['platform'] ) ? sanitize_key( $meta['platform'] ) : 'unknown';
				if ( ! isset( $data[ $today ]['platform_clicks'][ $platform ] ) ) {
					$data[ $today ]['platform_clicks'][ $platform ] = 0;
				}
				$data[ $today ]['platform_clicks'][ $platform ]++;
				break;
		}

		// Prune data older than 90 days.
		$cutoff = gmdate( 'Y-m-d', strtotime( '-90 days' ) );
		foreach ( array_keys( $data ) as $date ) {
			if ( $date < $cutoff ) {
				unset( $data[ $date ] );
			}
		}

		update_option( self::OPTION_KEY, $data, false );
		return true;
	}

	/**
	 * Get analytics data for a date range.
	 *
	 * @param string $start Start date (Y-m-d).
	 * @param string $end   End date (Y-m-d).
	 * @return array Analytics data.
	 */
	public static function get_range( $start, $end ) {
		$data   = get_option( self::OPTION_KEY, array() );
		$result = array();

		$current = $start;
		while ( $current <= $end ) {
			$result[ $current ] = isset( $data[ $current ] ) ? $data[ $current ] : array(
				'impressions'     => 0,
				'clicks'          => 0,
				'platform_clicks' => array(),
				'devices'         => array( 'mobile' => 0, 'desktop' => 0 ),
			);
			$current = gmdate( 'Y-m-d', strtotime( $current . ' +1 day' ) );
		}

		return $result;
	}

	/**
	 * Get summary stats for the dashboard.
	 *
	 * @param int $days Number of days to aggregate.
	 * @return array Summary with totals and top platforms.
	 */
	public static function get_summary( $days = 30 ) {
		$end   = gmdate( 'Y-m-d' );
		$start = gmdate( 'Y-m-d', strtotime( "-{$days} days" ) );
		$range = self::get_range( $start, $end );

		$totals = array(
			'impressions'     => 0,
			'clicks'          => 0,
			'ctr'             => 0,
			'platform_clicks' => array(),
			'devices'         => array( 'mobile' => 0, 'desktop' => 0 ),
			'daily'           => array(),
		);

		foreach ( $range as $date => $day_data ) {
			$totals['impressions'] += $day_data['impressions'];
			$totals['clicks']      += $day_data['clicks'];

			// Aggregate platform clicks.
			foreach ( $day_data['platform_clicks'] as $platform => $count ) {
				if ( ! isset( $totals['platform_clicks'][ $platform ] ) ) {
					$totals['platform_clicks'][ $platform ] = 0;
				}
				$totals['platform_clicks'][ $platform ] += $count;
			}

			// Aggregate devices.
			foreach ( $day_data['devices'] as $device => $count ) {
				if ( isset( $totals['devices'][ $device ] ) ) {
					$totals['devices'][ $device ] += $count;
				}
			}

			// Daily data for chart.
			$totals['daily'][] = array(
				'date'        => $date,
				'impressions' => $day_data['impressions'],
				'clicks'      => $day_data['clicks'],
			);
		}

		// Calculate CTR.
		if ( $totals['impressions'] > 0 ) {
			$totals['ctr'] = round( ( $totals['clicks'] / $totals['impressions'] ) * 100, 2 );
		}

		// Sort platforms by clicks.
		arsort( $totals['platform_clicks'] );

		return $totals;
	}

	/**
	 * Clear all analytics data.
	 *
	 * @return bool True on success.
	 */
	public static function clear_data() {
		return delete_option( self::OPTION_KEY );
	}
}
