<?php

namespace FleekDash\Models;

defined('ABSPATH') || exit;

class SiteGrowthTemplate extends BaseModel
{
    protected $table = 'fleekdash_site_growth_templates';
    protected $primaryKey = 'id';

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'template_name',
        'description',
        'category',
        'target_audience',
        'template_config',
        'is_default',
        'is_active'
    ];

    /**
     * Attributes that should be cast to specific types
     */
    protected $casts = [
        'is_default' => 'boolean',
        'is_active' => 'boolean',
        'template_config' => 'json'
    ];

    /**
     * Get all active templates
     */
    public static function getActive($category = null)
    {
        $instance = new static();

        $where_clause = "WHERE is_active = 1";
        $params = [];

        if ($category) {
            $where_clause .= " AND category = %s";
            $params[] = $category;
        }

        $sql = "SELECT * FROM {$instance->table} {$where_clause} ORDER BY is_default DESC, template_name ASC";

        $results = $instance->wpdb->get_results(
            $params ? $instance->wpdb->prepare($sql, $params) : $sql,
            ARRAY_A
        );

        return array_map([$instance, 'castAttributes'], $results);
    }

    /**
     * Get templates by category
     */
    public static function getByCategory($category)
    {
        return self::getActive($category);
    }

    /**
     * Get default templates
     */
    public static function getDefaults()
    {
        $instance = new static();

        $results = $instance->wpdb->get_results(
            "SELECT * FROM {$instance->table} WHERE is_default = 1 AND is_active = 1 ORDER BY template_name ASC",
            ARRAY_A
        );

        return array_map([$instance, 'castAttributes'], $results);
    }

    /**
     * Get popular templates
     */
    public static function getPopular($limit = 6)
    {
        $instance = new static();

        $results = $instance->wpdb->get_results(
            $instance->wpdb->prepare(
                "SELECT * FROM {$instance->table}
                WHERE is_active = 1
                ORDER BY is_default DESC, template_name ASC
                LIMIT %d",
                $limit
            ),
            ARRAY_A
        );

        return array_map([$instance, 'castAttributes'], $results);
    }

    /**
     * Apply template to site
     */
    public static function applyToSite($template_id)
    {
        $template = self::find($template_id);

        if (!$template) {
            return ['success' => false, 'error' => 'Template not found'];
        }

        $config = $template['template_config'];
        $results = [
            'events' => [],
            'goals' => [],
            'success' => false
        ];

        try {
            // Create events from template
            if (isset($config['events'])) {
                $results['events'] = SiteGrowthEvent::autoCreateFromTemplate($config);
            }

            // Apply points map overrides if provided by template
            if (isset($config['points_map']) && is_array($config['points_map'])) {
                try {
                    $service = new \FleekDash\Services\SiteGrowthMeterService();
                    $service->savePointsMap($config['points_map']);
                } catch (\Throwable $e) {
                    // Log but do not fail template application
                    fleekdash_log_error('FleekDash Site Growth: Failed to apply points_map: ' . $e->getMessage());
                }
            }

            $results['success'] = true;

            // Log template application
            fleekdash_log_info("FleekDash Site Growth: Template '{$template['template_name']}' applied to site");

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash Site Growth: Error applying template '{$template['template_name']}': " . $e->getMessage());
            $results['error'] = $e->getMessage();
        }

        return $results;
    }

    /**
     * Get all categories
     */
    public static function getCategories()
    {
        $instance = new static();

        return $instance->wpdb->get_results(
            "SELECT DISTINCT category, COUNT(*) as template_count
            FROM {$instance->table}
            WHERE is_active = 1
            GROUP BY category
            ORDER BY template_count DESC, category ASC",
            ARRAY_A
        );
    }

    /**
     * Search templates
     */
    public static function search($query, $category = null)
    {
        $instance = new static();

        $where_clause = "WHERE is_active = 1 AND (template_name LIKE %s OR description LIKE %s OR target_audience LIKE %s)";
        $params = ["%{$query}%", "%{$query}%", "%{$query}%"];

        if ($category) {
            $where_clause .= " AND category = %s";
            $params[] = $category;
        }

        $sql = "SELECT * FROM {$instance->table} {$where_clause} ORDER BY is_default DESC, template_name ASC";

        $results = $instance->wpdb->get_results(
            $instance->wpdb->prepare($sql, $params),
            ARRAY_A
        );

        return array_map([$instance, 'castAttributes'], $results);
    }

    /**
     * Get template with preview data
     */
    public static function getWithPreview($template_id)
    {
        $template = self::find($template_id);

        if (!$template) {
            return null;
        }

        $config = $template['template_config'];
        $preview = [
            'template' => $template,
            'events_count' => isset($config['events']) ? count($config['events']) : 0,
            'events_preview' => isset($config['events']) ? array_slice($config['events'], 0, 3) : []
        ];

        return $preview;
    }

    /**
     * Create custom template
     */
    public static function createCustom($data)
    {
        $template_data = [
            'template_name' => $data['template_name'],
            'description' => $data['description'],
            'category' => $data['category'],
            'target_audience' => $data['target_audience'],
            'template_config' => is_array($data['template_config']) ? json_encode($data['template_config']) : $data['template_config'],
            'is_default' => 0,
            'is_active' => 1
        ];

        return self::create($template_data);
    }

    /**
     * Get statistics
     */
    public static function getStatistics()
    {
        $instance = new static();

        return [
            'total_templates' => $instance->wpdb->get_var("SELECT COUNT(*) FROM {$instance->table}"),
            'active_templates' => $instance->wpdb->get_var("SELECT COUNT(*) FROM {$instance->table} WHERE is_active = 1"),
            'default_templates' => $instance->wpdb->get_var("SELECT COUNT(*) FROM {$instance->table} WHERE is_default = 1"),
            'categories' => $instance->wpdb->get_var("SELECT COUNT(DISTINCT category) FROM {$instance->table} WHERE is_active = 1")
        ];
    }

    /**
     * Validate template data
     */
    public static function validate($data)
    {
        $errors = [];

        if (empty($data['template_name'])) {
            $errors[] = 'Template name is required';
        }

        if (empty($data['category'])) {
            $errors[] = 'Category is required';
        }

        if (empty($data['template_config'])) {
            $errors[] = 'Template configuration is required';
        }

        if (isset($data['template_config'])) {
            $config = $data['template_config'];

            if (!isset($config['events'])) {
                $errors[] = 'Template must have at least one event';
            }

            if (isset($config['events'])) {
                foreach ($config['events'] as $event) {
                    if (empty($event['event_type']) || empty($event['event_name'])) {
                        $errors[] = 'Event type and name are required';
                    }
                }
            }
        }

        return $errors;
    }

    /**
     * Export template
     */
    public static function export($template_id)
    {
        $template = self::find($template_id);

        if (!$template) {
            return null;
        }

        return [
            'template_name' => $template['template_name'],
            'description' => $template['description'],
            'category' => $template['category'],
            'target_audience' => $template['target_audience'],
            'template_config' => $template['template_config'],
            'exported_at' => \current_time('mysql')
        ];
    }

    /**
     * Import template
     */
    public static function import($template_data)
    {
        // Remove exported_at if present
        unset($template_data['exported_at']);

        $template_data['is_default'] = 0;
        $template_data['is_active'] = 1;
        $template_data['template_config'] = is_array($template_data['template_config'])
            ? json_encode($template_data['template_config'])
            : $template_data['template_config'];

        return self::create($template_data);
    }
}
