<?php

namespace FleekDash\Controllers\Analytics;

use FleekDash\Services\AnalyticsCacheService;

/**
 * Engagement Tracker
 *
 * Handles user engagement tracking and analysis
 *
 * @package FleekDash\Controllers\Analytics
 */
class EngagementTracker
{
    private $cacheService;

    public function __construct()
    {
        $this->cacheService = new AnalyticsCacheService();
    }

    /**
     * Get top engaging content
     *
     * @param \DateTime $date Date to analyze
     * @param string|null $engagement_type Type of engagement
     * @param string|null $source Engagement source
     * @return array Top engaging content
     */
    public function getTopEngagingContent($date, $engagement_type = null, $source = null)
    {
        global $wpdb;

        $top_content = [];

        // Get posts with most comments
        $posts_with_comments = $wpdb->get_results($wpdb->prepare("
            SELECT
                p.ID,
                p.post_title,
                p.post_type,
                COUNT(c.comment_ID) as comment_count
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
                AND DATE(c.comment_date) = %s
            WHERE p.post_status = 'publish'
            AND p.post_type IN ('post', 'page')
            GROUP BY p.ID
            HAVING comment_count > 0
            ORDER BY comment_count DESC
            LIMIT 5
        ", $date->format('Y-m-d')));

        foreach ($posts_with_comments as $post) {
            $top_content[] = [
                'id' => $post->ID,
                'title' => $post->post_title,
                'type' => $post->post_type,
                'engagement_count' => $post->comment_count,
                'engagement_type' => 'comments',
                'url' => get_permalink($post->ID)
            ];
        }

        return $top_content;
    }

    /**
     * Get available engagement types
     *
     * @return array Engagement types
     */
    public function getAvailableEngagementTypes()
    {
        return [
            'comments' => [
                'name' => 'Comments',
                'description' => 'User comments on posts and pages',
                'icon' => 'message-circle'
            ],
            'likes' => [
                'name' => 'Likes',
                'description' => 'Post and content likes',
                'icon' => 'heart'
            ],
            'shares' => [
                'name' => 'Shares',
                'description' => 'Social media shares',
                'icon' => 'share-2'
            ],
            'registrations' => [
                'name' => 'User Registrations',
                'description' => 'New user account registrations',
                'icon' => 'user-plus'
            ],
            'post_interactions' => [
                'name' => 'Post Interactions',
                'description' => 'Views, time on page, scroll depth',
                'icon' => 'eye'
            ],
            'social_media' => [
                'name' => 'Social Media',
                'description' => 'Engagement on social platforms',
                'icon' => 'instagram'
            ]
        ];
    }

    /**
     * Get available engagement sources
     *
     * @return array Engagement sources
     */
    public function getAvailableEngagementSources()
    {
        $sources = [
            'wordpress' => [
                'name' => 'WordPress Native',
                'description' => 'Built-in WordPress engagement data',
                'types' => ['comments', 'registrations', 'post_interactions']
            ],
            'social_media' => [
                'name' => 'Social Media',
                'description' => 'Social media platform engagement',
                'types' => ['likes', 'shares', 'comments']
            ]
        ];

        $custom_sources = \apply_filters('fleekdash_engagement_sources', []);
        $sources = array_merge($sources, $custom_sources);

        return $sources;
    }

    /**
     * Store engagement event in database
     *
     * @param array $event_data Event data
     * @return array Event data with ID
     */
    public function storeEngagementEvent($event_data)
    {
        global $wpdb;

        $table = $wpdb->prefix . 'fleekdash_engagement_events';

        // Create table if it doesn't exist
        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") != $table) {
            $this->createEngagementEventsTable();
        }

        $wpdb->insert($table, [
            'user_id' => $event_data['user_id'],
            'event_type' => $event_data['event_type'],
            'content_id' => $event_data['content_id'],
            'content_type' => $event_data['content_type'],
            'source' => $event_data['source'],
            'metadata' => json_encode($event_data['metadata']),
            'created_at' => $event_data['timestamp']
        ]);

        $event_data['id'] = $wpdb->insert_id;
        return $event_data;
    }

    /**
     * Create engagement events table
     *
     * @return void
     */
    private function createEngagementEventsTable()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'fleekdash_engagement_events';

        $sql = "CREATE TABLE $table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) DEFAULT NULL,
            event_type varchar(100) NOT NULL,
            content_id bigint(20) DEFAULT NULL,
            content_type varchar(50) DEFAULT NULL,
            source varchar(50) DEFAULT 'wordpress',
            metadata longtext DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_user_id (user_id),
            KEY idx_event_type (event_type),
            KEY idx_content_id (content_id),
            KEY idx_created_at (created_at),
            KEY idx_source (source)
        ) " . $wpdb->get_charset_collate();

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

    /**
     * Calculate engagement score (weighted average)
     *
     * @param array $engagement_data Engagement data
     * @return float Engagement score
     */
    public function calculateEngagementScore($engagement_data)
    {
        $weights = [
            'comments' => 0.3,
            'likes' => 0.2,
            'shares' => 0.25,
            'registrations' => 0.15,
            'post_interactions' => 0.1
        ];

        $total_score = 0;
        $total_weight = 0;

        foreach ($engagement_data as $type => $count) {
            if (isset($weights[$type])) {
                $total_score += $count * $weights[$type];
                $total_weight += $weights[$type];
            }
        }

        return $total_weight > 0 ? $total_score / $total_weight : 0;
    }
}
