<?php

namespace FleekDash\Services;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Engagement Plugin Example
 *
 * This plugin demonstrates how to integrate custom engagement data
 * into the FleekDash V2 analytics system. It shows how to:
 *
 * 1. Register custom engagement types
 * 2. Register custom engagement sources
 * 3. Provide custom engagement data
 * 4. Handle AJAX tracking of custom engagement events
 * 5. Hook into the analytics system filters
 */
class EngagementPluginExample
{
    /**
     * Plugin constructor
     */
    public function __construct()
    {
        \add_action('init', [$this, 'init']);
        \add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        \add_action('wp_ajax_track_custom_engagement', [$this, 'track_custom_engagement']);
        \add_action('wp_ajax_nopriv_track_custom_engagement', [$this, 'track_custom_engagement']);
    }

    /**
     * Initialize the plugin
     */
    public function init()
    {
        // Register custom engagement types
        \add_filter('fleekdash_engagement_types', [$this, 'register_engagement_types']);

        // Register custom engagement sources
        \add_filter('fleekdash_engagement_sources', [$this, 'register_engagement_sources']);

        // Provide custom engagement data
        \add_filter('fleekdash_engagement_data', [$this, 'provide_engagement_data'], 10, 4);

        // Hook into engagement event tracking
        \add_action('fleekdash_track_engagement_event', [$this, 'handle_engagement_event']);

        // Create custom database table for storing engagement events
        \add_action('init', [$this, 'create_engagement_table']);
    }

    /**
     * Register custom engagement types
     */
    public function register_engagement_types($types)
    {
        $custom_types = [
            'custom_likes' => [
                'name' => 'Custom Likes',
                'description' => 'Likes from custom social platforms',
                'weight' => 1.0
            ],
            'custom_shares' => [
                'name' => 'Custom Shares',
                'description' => 'Shares from custom social platforms',
                'weight' => 2.0
            ],
            'custom_comments' => [
                'name' => 'Custom Comments',
                'description' => 'Comments from custom social platforms',
                'weight' => 1.5
            ],
            'custom_bookmarks' => [
                'name' => 'Custom Bookmarks',
                'description' => 'Bookmarks from custom platforms',
                'weight' => 1.2
            ],
            'custom_follows' => [
                'name' => 'Custom Follows',
                'description' => 'Follows from custom platforms',
                'weight' => 1.8
            ]
        ];

        return array_merge($types, $custom_types);
    }

    /**
     * Register custom engagement sources
     */
    public function register_engagement_sources($sources)
    {
        $custom_sources = [
            'custom_social' => [
                'name' => 'Custom Social Platform',
                'description' => 'Custom social media platform integration',
                'types' => ['custom_likes', 'custom_shares', 'custom_comments'],
                'active' => true,
                'config' => [
                    'api_endpoint' => 'https://api.customsocial.com',
                    'api_key' => \get_option('fleekdash_custom_social_api_key', ''),
                    'update_frequency' => 3600 // 1 hour
                ]
            ],
            'custom_forum' => [
                'name' => 'Custom Forum',
                'description' => 'Custom forum platform integration',
                'types' => ['custom_comments', 'custom_bookmarks'],
                'active' => true,
                'config' => [
                    'forum_url' => \get_option('fleekdash_custom_forum_url', ''),
                    'api_key' => \get_option('fleekdash_custom_forum_api_key', ''),
                    'update_frequency' => 1800 // 30 minutes
                ]
            ],
            'custom_app' => [
                'name' => 'Custom Mobile App',
                'description' => 'Custom mobile application integration',
                'types' => ['custom_likes', 'custom_shares', 'custom_follows'],
                'active' => true,
                'config' => [
                    'app_id' => \get_option('fleekdash_custom_app_id', ''),
                    'webhook_url' => \get_option('fleekdash_custom_app_webhook', ''),
                    'update_frequency' => 300 // 5 minutes
                ]
            ]
        ];

        return array_merge($sources, $custom_sources);
    }

    /**
     * Provide custom engagement data
     */
    public function provide_engagement_data($data, $date, $engagement_type = null, $source = null)
    {
        // Get custom engagement data from external sources
        $custom_data = $this->get_custom_engagement_data($date, $engagement_type, $source);

        // Merge with existing data
        if (!empty($custom_data)) {
            $data['total'] += $custom_data['total'] ?? 0;
            $data['breakdown']['custom'] = $custom_data['breakdown'] ?? [];
            $data['unique_users'] += $custom_data['unique_users'] ?? 0;

            // Add source-specific data
            if ($source) {
                $data['sources'][$source] = $custom_data['sources'][$source] ?? 0;
            }
        }

        return $data;
    }

    /**
     * Get custom engagement data from external sources
     */
    private function get_custom_engagement_data($date, $engagement_type = null, $source = null)
    {
        $data = [
            'total' => 0,
            'breakdown' => [],
            'unique_users' => 0,
            'sources' => []
        ];

        // Get data from custom social platform
        if (!$source || $source === 'custom_social') {
            $social_data = $this->get_custom_social_data($date, $engagement_type);
            $data['total'] += $social_data['total'];
            $data['breakdown']['custom_social'] = $social_data['breakdown'];
            $data['unique_users'] += $social_data['unique_users'];
            $data['sources']['custom_social'] = $social_data['total'];
        }

        // Get data from custom forum
        if (!$source || $source === 'custom_forum') {
            $forum_data = $this->get_custom_forum_data($date, $engagement_type);
            $data['total'] += $forum_data['total'];
            $data['breakdown']['custom_forum'] = $forum_data['breakdown'];
            $data['unique_users'] += $forum_data['unique_users'];
            $data['sources']['custom_forum'] = $forum_data['total'];
        }

        // Get data from custom mobile app
        if (!$source || $source === 'custom_app') {
            $app_data = $this->get_custom_app_data($date, $engagement_type);
            $data['total'] += $app_data['total'];
            $data['breakdown']['custom_app'] = $app_data['breakdown'];
            $data['unique_users'] += $app_data['unique_users'];
            $data['sources']['custom_app'] = $app_data['total'];
        }

        return $data;
    }

    /**
     * Get data from custom social platform
     */
    private function get_custom_social_data($date, $engagement_type = null)
    {
        // In a real implementation, this would make API calls to your custom social platform
        // For this example, we'll simulate data

        $data = [
            'total' => 0,
            'breakdown' => [],
            'unique_users' => 0
        ];

        // Simulate API call delay
        usleep(100000); // 0.1 seconds

        // Generate realistic simulated data
        $base_engagement = rand(50, 200);
        $date_factor = $this->get_date_engagement_factor($date);

        if (!$engagement_type || $engagement_type === 'custom_likes') {
            $likes = round($base_engagement * $date_factor * 0.6);
            $data['total'] += $likes;
            $data['breakdown']['custom_likes'] = $likes;
        }

        if (!$engagement_type || $engagement_type === 'custom_shares') {
            $shares = round($base_engagement * $date_factor * 0.3);
            $data['total'] += $shares;
            $data['breakdown']['custom_shares'] = $shares;
        }

        if (!$engagement_type || $engagement_type === 'custom_comments') {
            $comments = round($base_engagement * $date_factor * 0.4);
            $data['total'] += $comments;
            $data['breakdown']['custom_comments'] = $comments;
        }

        $data['unique_users'] = round($data['total'] * 0.7); // 70% of total engagement are unique users

        return $data;
    }

    /**
     * Get data from custom forum
     */
    private function get_custom_forum_data($date, $engagement_type = null)
    {
        $data = [
            'total' => 0,
            'breakdown' => [],
            'unique_users' => 0
        ];

        // Simulate API call delay
        usleep(150000); // 0.15 seconds

        $base_engagement = rand(20, 80);
        $date_factor = $this->get_date_engagement_factor($date);

        if (!$engagement_type || $engagement_type === 'custom_comments') {
            $comments = round($base_engagement * $date_factor * 0.8);
            $data['total'] += $comments;
            $data['breakdown']['custom_comments'] = $comments;
        }

        if (!$engagement_type || $engagement_type === 'custom_bookmarks') {
            $bookmarks = round($base_engagement * $date_factor * 0.2);
            $data['total'] += $bookmarks;
            $data['breakdown']['custom_bookmarks'] = $bookmarks;
        }

        $data['unique_users'] = round($data['total'] * 0.6); // 60% of total engagement are unique users

        return $data;
    }

    /**
     * Get data from custom mobile app
     */
    private function get_custom_app_data($date, $engagement_type = null)
    {
        $data = [
            'total' => 0,
            'breakdown' => [],
            'unique_users' => 0
        ];

        // Simulate API call delay
        usleep(80000); // 0.08 seconds

        $base_engagement = rand(30, 120);
        $date_factor = $this->get_date_engagement_factor($date);

        if (!$engagement_type || $engagement_type === 'custom_likes') {
            $likes = round($base_engagement * $date_factor * 0.5);
            $data['total'] += $likes;
            $data['breakdown']['custom_likes'] = $likes;
        }

        if (!$engagement_type || $engagement_type === 'custom_shares') {
            $shares = round($base_engagement * $date_factor * 0.3);
            $data['total'] += $shares;
            $data['breakdown']['custom_shares'] = $shares;
        }

        if (!$engagement_type || $engagement_type === 'custom_follows') {
            $follows = round($base_engagement * $date_factor * 0.2);
            $data['total'] += $follows;
            $data['breakdown']['custom_follows'] = $follows;
        }

        $data['unique_users'] = round($data['total'] * 0.8); // 80% of total engagement are unique users

        return $data;
    }

    /**
     * Get engagement factor based on date (weekends have higher engagement)
     */
    private function get_date_engagement_factor($date)
    {
        $day_of_week = date('N', strtotime($date)); // 1 (Monday) to 7 (Sunday)

        // Higher engagement on weekends
        if ($day_of_week >= 6) {
            return 1.3; // 30% higher on weekends
        } elseif ($day_of_week == 5) {
            return 1.1; // 10% higher on Fridays
        } else {
            return 1.0; // Normal engagement on weekdays
        }
    }

    /**
     * Handle engagement event tracking
     */
    public function handle_engagement_event($event_data)
    {
        // Store the event in our custom table
        $this->store_custom_engagement_event($event_data);

        // Log the event for debugging
        fleekdash_log_debug('FleekDash: Custom engagement event tracked: ' . json_encode($event_data));
    }

    /**
     * AJAX handler for tracking custom engagement events
     */
    public function track_custom_engagement()
    {
        // Verify nonce for security
        if (!\wp_verify_nonce($_POST['nonce'], 'fleekdash_engagement_nonce')) {
            \wp_send_json_error(['message' => 'Security check failed']);
        }

        // Validate required fields
        $engagement_type = \sanitize_text_field($_POST['engagement_type'] ?? '');
        $post_id = intval($_POST['post_id'] ?? 0);
        $source = \sanitize_text_field($_POST['source'] ?? 'custom_plugin');
        $user_id = \get_current_user_id();
        $metadata = $_POST['metadata'] ?? [];

        if (empty($engagement_type)) {
            \wp_send_json_error(['message' => 'Engagement type is required']);
        }

        // Prepare event data
        $event_data = [
            'engagement_type' => $engagement_type,
            'source' => $source,
            'post_id' => $post_id,
            'user_id' => $user_id,
            'timestamp' => \current_time('mysql'),
            'metadata' => $metadata
        ];

        // Store the engagement event
        $event_id = $this->store_custom_engagement_event($event_data);

        if ($event_id) {
            // Trigger the engagement event action for other plugins
            \do_action('fleekdash_track_engagement_event', $event_data);

            \wp_send_json_success([
                'message' => 'Engagement event tracked successfully',
                'event_id' => $event_id
            ]);
        } else {
            \wp_send_json_error(['message' => 'Failed to store engagement event']);
        }
    }

    /**
     * Store custom engagement event in database
     */
    private function store_custom_engagement_event($event_data)
    {
        global $wpdb;

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

        $result = $wpdb->insert(
            $table_name,
            [
                'engagement_type' => $event_data['engagement_type'],
                'source' => $event_data['source'],
                'post_id' => $event_data['post_id'],
                'user_id' => $event_data['user_id'],
                'timestamp' => $event_data['timestamp'],
                'metadata' => json_encode($event_data['metadata'])
            ],
            ['%s', '%s', '%d', '%d', '%s', '%s'],
        );

        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Create custom engagement table
     */
    public function create_engagement_table()
    {
        global $wpdb;

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

        // Check if table already exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name) {
            return;
        }

        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            engagement_type varchar(50) NOT NULL,
            source varchar(50) NOT NULL,
            post_id bigint(20) unsigned DEFAULT NULL,
            user_id bigint(20) unsigned DEFAULT NULL,
            timestamp datetime NOT NULL,
            metadata longtext DEFAULT NULL,
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_engagement_type (engagement_type),
            KEY idx_source (source),
            KEY idx_post_id (post_id),
            KEY idx_user_id (user_id),
            KEY idx_timestamp (timestamp)
        ) $charset_collate;";

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

    /**
     * Enqueue frontend scripts
     */
    public function enqueue_scripts()
    {
        \wp_enqueue_script(
            'fleekdash-engagement-tracking',
            plugin_dir_url(__FILE__) . 'js/engagement-tracking.js',
            ['jquery'],
            '1.0.0',
            true,
        );

        \wp_localize_script('fleekdash-engagement-tracking', 'fleekdashEngagement', [
            'ajax_url' => \admin_url('admin-ajax.php'),
            'nonce' => \wp_create_nonce('fleekdash_engagement_nonce'),
            'user_id' => \get_current_user_id()
        ]);
    }

    /**
     * Get engagement statistics for a specific date range
     */
    public function get_engagement_stats($start_date, $end_date, $engagement_type = null, $source = null)
    {
        global $wpdb;

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

        $where_conditions = ['timestamp BETWEEN %s AND %s'];
        $where_values = [$start_date, $end_date];

        if ($engagement_type) {
            $where_conditions[] = 'engagement_type = %s';
            $where_values[] = $engagement_type;
        }

        if ($source) {
            $where_conditions[] = 'source = %s';
            $where_values[] = $source;
        }

        $where_clause = implode(' AND ', $where_conditions);

        $query = "
            SELECT
                DATE(timestamp) as date,
                engagement_type,
                source,
                COUNT(*) as count,
                COUNT(DISTINCT user_id) as unique_users
            FROM $table_name
            WHERE $where_clause
            GROUP BY DATE(timestamp), engagement_type, source
            ORDER BY date ASC
        ";

        return $wpdb->get_results($wpdb->prepare($query, $where_values));
    }

    /**
     * Get top engaging content
     */
    public function get_top_engaging_content($limit = 10, $engagement_type = null, $source = null)
    {
        global $wpdb;

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

        $where_conditions = ['post_id IS NOT NULL'];
        $where_values = [];

        if ($engagement_type) {
            $where_conditions[] = 'engagement_type = %s';
            $where_values[] = $engagement_type;
        }

        if ($source) {
            $where_conditions[] = 'source = %s';
            $where_values[] = $source;
        }

        $where_clause = implode(' AND ', $where_conditions);

        $query = "
            SELECT
                post_id,
                engagement_type,
                source,
                COUNT(*) as engagement_count,
                COUNT(DISTINCT user_id) as unique_users
            FROM $table_name
            WHERE $where_clause
            GROUP BY post_id, engagement_type, source
            ORDER BY engagement_count DESC
            LIMIT %d
        ";

        $where_values[] = $limit;

        return $wpdb->get_results($wpdb->prepare($query, $where_values));
    }
}

// Initialize the plugin
new EngagementPluginExample();
