<?php

namespace FleekDash\Services;

use FleekDash\Services\Dashboard\TemplateFactory;
use FleekDash\Services\Dashboard\TemplateDefinitions;

/**
 * Dashboard Template Service
 *
 * Manages pre-configured dashboard templates for different business types
 *
 * @since 2.2.0 Refactored - Extracted large templates to TemplateFactory and TemplateDefinitions
 */
class DashboardTemplateService
{
    private $wpdb;
    private $table_templates;
    private $cache_service;
    private $templateFactory;

    public function __construct()
    {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table_templates = $wpdb->prefix . 'fleekdash_analytics_dashboard_templates';
        $this->cache_service = new AnalyticsCacheService();
        $this->templateFactory = new TemplateFactory();
    }

    /**
     * Get all available dashboard templates
     */
    public function getTemplates($category = null)
    {
        $cache_key = "dashboard_templates" . ($category ? "_{$category}" : "");

        return $this->cache_service->get_cached_data(
            $cache_key,
            [],
            function () use ($category) {
                $where = $category ?
                    $this->wpdb->prepare("WHERE category = %s", $category) :
                    "WHERE is_active = 1";

                $sql = "SELECT * FROM {$this->table_templates} {$where} ORDER BY is_default DESC, name ASC";
                return $this->wpdb->get_results($sql, ARRAY_A);
            },
            3600,
        );
    }

    /**
     * Get template by ID
     */
    public function getTemplate($template_id)
    {
        $cache_key = "dashboard_template_{$template_id}";

        return $this->cache_service->get_cached_data(
            $cache_key,
            [],
            function () use ($template_id) {
                $sql = $this->wpdb->prepare(
                    "SELECT * FROM {$this->table_templates} WHERE id = %d",
                    $template_id,
                );
                return $this->wpdb->get_row($sql, ARRAY_A);
            },
            3600,
        );
    }

    /**
     * Create default templates if they don't exist
     */
    public function createDefaultTemplates()
    {
        $default_templates = TemplateDefinitions::getDefaultTemplates();

        foreach ($default_templates as $template) {
            $this->createTemplate($template);
        }
    }

    /**
     * Create a new template
     */
    public function createTemplate($data)
    {
        // Check if template already exists
        $existing = $this->wpdb->get_row(
            $this->wpdb->prepare(
                "SELECT id FROM {$this->table_templates} WHERE name = %s AND category = %s",
                $data['name'],
                $data['category'],
            ),
        );

        if ($existing) {
            return $existing->id;
        }

        $result = $this->wpdb->insert($this->table_templates, [
            'name' => $data['name'],
            'description' => $data['description'],
            'category' => $data['category'],
            'is_default' => $data['is_default'] ?? 0,
            'is_active' => $data['is_active'] ?? 1,
            'config' => $data['config'],
            'created_at' => \current_time('mysql'),
            'updated_at' => \current_time('mysql')
        ]);

        if ($result !== false) {
            $this->cache_service->invalidate_cache('dashboard_templates');
            return $this->wpdb->insert_id;
        }

        return false;
    }

    /**
     * Apply template to create a new dashboard layout
     */
    public function applyTemplate($template_id, $user_id = null)
    {
        $template = $this->getTemplate($template_id);

        if (!$template) {
            return false;
        }

        $config = json_decode($template['config'], true);

        if (!$config) {
            return false;
        }

        // Create dashboard layout from template
        $layout = [
            'id' => 'dashboard-' . time(),
            'name' => $template['name'] . ' (Copy)',
            'description' => $template['description'],
            'widgets' => $config['widgets'] ?? [],
            'filters' => $config['filters'] ?? [
                'timeRange' => '30d',
                'sources' => [],
                'categories' => []
            ]
        ];

        // If user_id provided, save to user dashboards
        if ($user_id) {
            $this->saveUserDashboard($user_id, $layout);
        }

        return $layout;
    }

    /**
     * Save user dashboard
     */
    private function saveUserDashboard($user_id, $layout)
    {
        $table_user_dashboards = $this->wpdb->prefix . 'fleekdash_analytics_user_dashboards';

        $this->wpdb->insert($table_user_dashboards, [
            'user_id' => $user_id,
            'name' => $layout['name'],
            'description' => $layout['description'],
            'config' => json_encode($layout),
            'is_default' => 0,
            'created_at' => \current_time('mysql'),
            'updated_at' => \current_time('mysql')
        ]);

        return $this->wpdb->insert_id;
    }

    /**
     * Get template categories
     */
    public function getCategories()
    {
        $sql = "SELECT DISTINCT category FROM {$this->table_templates} WHERE is_active = 1 ORDER BY category";
        return $this->wpdb->get_col($sql);
    }

    /**
     * Update template
     */
    public function updateTemplate($template_id, $data)
    {
        $result = $this->wpdb->update(
            $this->table_templates,
            array_merge($data, ['updated_at' => \current_time('mysql')]),
            ['id' => $template_id],
        );

        if ($result !== false) {
            $this->cache_service->invalidate_cache('dashboard_templates');
            $this->cache_service->invalidate_cache("dashboard_template_{$template_id}");
            return true;
        }

        return false;
    }

    /**
     * Delete template
     */
    public function deleteTemplate($template_id)
    {
        $result = $this->wpdb->delete(
            $this->table_templates,
            ['id' => $template_id],
        );

        if ($result !== false) {
            $this->cache_service->invalidate_cache('dashboard_templates');
            $this->cache_service->invalidate_cache("dashboard_template_{$template_id}");
            return true;
        }

        return false;
    }

    /**
     * Get all available templates
     */
    public function get_templates(): array
    {
        return [
            'fleekdash-default' => $this->get_fleekdash_default_template(),
            'analytics-focus' => $this->get_analytics_focus_template(),
        ];
    }

    /**
     * Get FleekDash Default template
     */
    private function get_fleekdash_default_template(): array
    {
        return [
            'id' => 'fleekdash-default',
            'name' => 'FleekDash Default',
            'description' => 'Default dashboard layout with KPI cards and analytics charts',
            'category' => 'general',
            'version' => '1.0.0',
            'author' => 'FleekDash',
            'created' => '2024-01-01',
            'layout' => [
                'type' => 'grid',
                'columns' => 12,
                'rows' => 'auto',
                'gap' => 6,
                'containerClass' => 'grid gap-6'
            ],
            'widgets' => [
                [
                    'id' => 'kpi-1',
                    'type' => 'kpi',
                    'title' => 'Total Visitors',
                    'value' => '12,345',
                    'change' => '+20.1%',
                    'period' => 'from last month',
                    'position' => ['x' => 0, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-2',
                    'type' => 'kpi',
                    'title' => 'Page Views',
                    'value' => '45,678',
                    'change' => '+15.3%',
                    'period' => 'from last month',
                    'position' => ['x' => 3, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-3',
                    'type' => 'kpi',
                    'title' => 'Bounce Rate',
                    'value' => '23.4%',
                    'change' => '-2.1%',
                    'period' => 'from last month',
                    'position' => ['x' => 6, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-4',
                    'type' => 'kpi',
                    'title' => 'Avg. Session',
                    'value' => '2m 34s',
                    'change' => '+12.5%',
                    'period' => 'from last month',
                    'position' => ['x' => 9, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'chart-1',
                    'type' => 'chart',
                    'title' => 'Visitors Over Time',
                    'description' => 'Unique visitors and page views for the selected period',
                    'chartType' => 'area',
                    'data' => [
                        ['date' => '2024-01-01', 'visitors' => 120, 'pageviews' => 450],
                        ['date' => '2024-01-02', 'visitors' => 135, 'pageviews' => 520],
                        ['date' => '2024-01-03', 'visitors' => 142, 'pageviews' => 580],
                        ['date' => '2024-01-04', 'visitors' => 128, 'pageviews' => 490],
                        ['date' => '2024-01-05', 'visitors' => 156, 'pageviews' => 620],
                        ['date' => '2024-01-06', 'visitors' => 168, 'pageviews' => 680],
                        ['date' => '2024-01-07', 'visitors' => 145, 'pageviews' => 550]
                    ],
                    'yKeys' => ['visitors', 'pageviews'],
                    'position' => ['x' => 0, 'y' => 1, 'w' => 8, 'h' => 2]
                ],
                [
                    'id' => 'chart-2',
                    'type' => 'chart',
                    'title' => 'Popular Posts',
                    'description' => 'Most viewed posts in the selected period',
                    'chartType' => 'bar',
                    'data' => [
                        ['date' => 'Post 1', 'views' => 1250],
                        ['date' => 'Post 2', 'views' => 980],
                        ['date' => 'Post 3', 'views' => 850],
                        ['date' => 'Post 4', 'views' => 720],
                        ['date' => 'Post 5', 'views' => 680],
                        ['date' => 'Post 6', 'views' => 620],
                        ['date' => 'Post 7', 'views' => 580],
                        ['date' => 'Post 8', 'views' => 520]
                    ],
                    'yKeys' => ['views'],
                    'position' => ['x' => 8, 'y' => 1, 'w' => 4, 'h' => 2]
                ]
            ],
            'filters' => [
                'timeRange' => '30d',
                'sources' => ['wordpress'],
                'categories' => ['all']
            ],
            'metadata' => [
                'version' => '1.0.0',
                'created' => '2024-01-01',
                'author' => 'FleekDash',
                'description' => 'Default dashboard layout with KPI cards and analytics charts'
            ]
        ];
    }

    /**
     * Get Analytics Focus template
     */
    private function get_analytics_focus_template(): array
    {
        return [
            'id' => 'analytics-focus',
            'name' => 'Analytics Focus',
            'description' => 'Comprehensive analytics dashboard with detailed metrics and real-time data',
            'category' => 'analytics',
            'version' => '1.0.0',
            'author' => 'FleekDash',
            'created' => '2024-01-01',
            'layout' => [
                'type' => 'grid',
                'columns' => 12,
                'rows' => 'auto',
                'gap' => 6,
                'containerClass' => 'grid gap-6'
            ],
            'widgets' => [
                [
                    'id' => 'kpi-1',
                    'type' => 'kpi',
                    'title' => 'Unique Visitors',
                    'value' => '8,234',
                    'change' => '+12.5%',
                    'period' => 'from last week',
                    'position' => ['x' => 0, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-2',
                    'type' => 'kpi',
                    'title' => 'Page Views',
                    'value' => '32,156',
                    'change' => '+8.2%',
                    'period' => 'from last week',
                    'position' => ['x' => 3, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-3',
                    'type' => 'kpi',
                    'title' => 'Bounce Rate',
                    'value' => '18.7%',
                    'change' => '-3.2%',
                    'period' => 'from last week',
                    'position' => ['x' => 6, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'kpi-4',
                    'type' => 'kpi',
                    'title' => 'Avg. Session',
                    'value' => '4m 12s',
                    'change' => '+15.8%',
                    'period' => 'from last week',
                    'position' => ['x' => 9, 'y' => 0, 'w' => 3, 'h' => 1]
                ],
                [
                    'id' => 'chart-1',
                    'type' => 'chart',
                    'title' => 'Visitor Analytics',
                    'description' => 'Detailed visitor and page view analytics over time',
                    'chartType' => 'area',
                    'data' => [
                        ['date' => '2024-01-01', 'visitors' => 180, 'pageviews' => 650],
                        ['date' => '2024-01-02', 'visitors' => 195, 'pageviews' => 720],
                        ['date' => '2024-01-03', 'visitors' => 202, 'pageviews' => 780],
                        ['date' => '2024-01-04', 'visitors' => 188, 'pageviews' => 690],
                        ['date' => '2024-01-05', 'visitors' => 216, 'pageviews' => 820],
                        ['date' => '2024-01-06', 'visitors' => 228, 'pageviews' => 880],
                        ['date' => '2024-01-07', 'visitors' => 205, 'pageviews' => 750]
                    ],
                    'yKeys' => ['visitors', 'pageviews'],
                    'position' => ['x' => 0, 'y' => 1, 'w' => 8, 'h' => 2]
                ],
                [
                    'id' => 'realtime-1',
                    'type' => 'realtime',
                    'title' => 'Real-time Activity',
                    'description' => 'Current active visitors and recent activity',
                    'data' => [
                        'active_visitors' => 23,
                        'recent_pageviews' => [
                            ['page' => '/home', 'timestamp' => '2024-01-07T10:30:00Z'],
                            ['page' => '/about', 'timestamp' => '2024-01-07T10:28:00Z'],
                            ['page' => '/contact', 'timestamp' => '2024-01-07T10:25:00Z']
                        ]
                    ],
                    'position' => ['x' => 8, 'y' => 1, 'w' => 4, 'h' => 2]
                ]
            ],
            'filters' => [
                'timeRange' => '30d',
                'sources' => ['wordpress', 'analytics'],
                'categories' => ['all']
            ],
            'metadata' => [
                'version' => '1.0.0',
                'created' => '2024-01-01',
                'author' => 'FleekDash',
                'description' => 'Comprehensive analytics dashboard with detailed metrics and real-time data'
            ]
        ];
    }

    /**
     * Get user customization for a template
     */
    public function get_user_customization($template_id, $user_id = null): array
    {
        if (!$user_id) {
            $user_id = \get_current_user_id();
        }

        $customization_key = "_fleekdash_template_customization_{$template_id}";
        $customization = \get_user_meta($user_id, $customization_key, true);

        if (!$customization) {
            return [
                'has_customization' => false,
                'template_id' => $template_id,
                'last_modified' => null,
                'customization' => null
            ];
        }

        return [
            'has_customization' => true,
            'template_id' => $template_id,
            'last_modified' => \get_user_meta($user_id, "{$customization_key}_modified", true),
            'customization' => $customization
        ];
    }

    /**
     * Save user customization for a template
     */
    public function save_user_customization($template_id, $customization, $user_id = null): bool
    {
        if (!$user_id) {
            $user_id = \get_current_user_id();
        }

        $customization_key = "_fleekdash_template_customization_{$template_id}";
        $modified_key = "{$customization_key}_modified";

        $result = \update_user_meta($user_id, $customization_key, $customization);
        if ($result) {
            \update_user_meta($user_id, $modified_key, \current_time('mysql'));
        }

        return $result !== false;
    }

    /**
     * Delete user customization for a template
     */
    public function delete_user_customization($template_id, $user_id = null): bool
    {
        if (!$user_id) {
            $user_id = \get_current_user_id();
        }

        $customization_key = "_fleekdash_template_customization_{$template_id}";
        $modified_key = "{$customization_key}_modified";

        \delete_user_meta($user_id, $customization_key);
        \delete_user_meta($user_id, $modified_key);

        return true;
    }
}
