<?php

namespace FleekDash\Services\SiteGrowthMeter;

use FleekDash\Models\SiteGrowthTemplate;

/**
 * Growth Helpers
 *
 * Utility methods for Site Growth Meter
 *
 * @package FleekDash\Services\SiteGrowthMeter
 */
class GrowthHelpers
{
    /**
     * Select default template based on WordPress setup
     *
     * @return object|null Template object
     */
    public static function selectDefaultTemplate()
    {
        $site_type = self::detectSiteType();
        $templates = SiteGrowthTemplate::getByCategory($site_type);

        if (empty($templates)) {
            $popular = SiteGrowthTemplate::getPopular(1);
            return !empty($popular) ? SiteGrowthTemplate::find($popular[0]['id']) : null;
        }

        return SiteGrowthTemplate::find($templates[0]['id']);
    }

    /**
     * Detect WordPress site type
     *
     * @return string Site type
     */
    public static function detectSiteType()
    {
        if (class_exists('WooCommerce')) {
            return 'ecommerce';
        }

        if (class_exists('bbPress') || class_exists('WP_Job_Manager')) {
            return 'services';
        }

        return 'blog';
    }

    /**
     * Build event name from type and config
     *
     * @param string $event_type Event type
     * @param array $config Configuration
     * @return string Event name
     */
    public static function buildEventName(string $event_type, array $config = []): string
    {
        $base_names = [
            'new_post' => 'New Post Published',
            'new_comment' => 'New Comment',
            'new_user' => 'New User Registration',
            'new_order' => 'New Order (WooCommerce)',
            'new_product' => 'New Product Added',
            'product_review' => 'Product Review'
        ];

        return $config['event_name'] ?? $base_names[$event_type] ?? ucwords(str_replace('_', ' ', $event_type));
    }

    /**
     * Validate and normalize event config
     *
     * @param string $event_type Event type
     * @param array $config Configuration
     * @return array Normalized config
     */
    public static function validateAndNormalizeEventConfig(string $event_type, array $config = []): array
    {
        $defaults = [
            'event_name' => self::buildEventName($event_type, $config),
            'tracking_method' => $config['tracking_method'] ?? 'automatic',
            'is_active' => $config['is_active'] ?? true,
            'description' => $config['description'] ?? '',
            'points' => $config['points'] ?? 10
        ];

        return array_merge($defaults, $config);
    }

    /**
     * Compute event total points
     *
     * Now uses points_per_event column directly (Bug #1 & #2)
     * Maintains backward compatibility with tracking_config for old events
     *
     * @param string|array $event_type Event type OR full event array (with points_per_event)
     * @param int $occurrences Number of occurrences
     * @param array|null $tracking_config Tracking configuration (optional, for backward compatibility)
     * @return int Total points
     */
    public static function computeEventTotalPoints($event_type, $occurrences, $tracking_config = null)
    {
        $points_per_occurrence = 10; // Default

        // If first param is an array (event object), extract points_per_event
        if (is_array($event_type)) {
            $event = $event_type;
            $occurrences = $occurrences ?? 0;

            // Priority 1: Use points_per_event column (new way)
            if (isset($event['points_per_event']) && is_numeric($event['points_per_event'])) {
                $points_per_occurrence = max(1, (int) $event['points_per_event']);
            }
            // Priority 2: Fallback to tracking_config (old way - backward compatibility)
            elseif (!empty($event['tracking_config'])) {
                $config = is_string($event['tracking_config'])
                    ? json_decode($event['tracking_config'], true)
                    : $event['tracking_config'];

                // Handle double-encoded JSON
                if (is_string($config)) {
                    $config = json_decode($config, true);
                }

                if (is_array($config) || is_object($config)) {
                    $config_array = is_array($config) ? $config : (array) $config;
                    if (isset($config_array['points_override'])) {
                        $points_per_occurrence = max(1, (int) $config_array['points_override']);
                    } elseif (isset($config_array['points'])) {
                        $points_per_occurrence = max(1, (int) $config_array['points']);
                    }
                }
            }
        } else {
            // Legacy signature: event_type, occurrences, tracking_config
            if (is_array($tracking_config)) {
                if (isset($tracking_config['points_override'])) {
                    $points_per_occurrence = max(1, (int) $tracking_config['points_override']);
                } elseif (isset($tracking_config['points'])) {
                    $points_per_occurrence = max(1, (int) $tracking_config['points']);
                }
            }
        }

        return $occurrences * $points_per_occurrence;
    }
}
