<?php
namespace FleekDash\Database\Migrations;

use FleekDash\Database\Core\BaseMigration;
use FleekDash\Database\Core\TableBuilder;

/**
 * Create Site Growth Meter Tables
 *
 * Converted to new format with proper timestamps
 */
return new class extends BaseMigration {

    public function up(): void
    {
        // Create site_growth_events table
        $this->createTable('fleekdash_site_growth_events', function (TableBuilder $table) {
            $table->id();
            $table->string('event_type', 100)->comment('Type of event');
            $table->string('event_name', 255)->comment('Display name');
            $table->text('description')->nullable()->comment('Description');
            $table->enum('tracking_method', [
                'manual',
                'automatic',
                'webhook',
                'advanced_use',
                'external_pageview'
            ])->default('automatic')->comment('How event is tracked');
            $table->longText('tracking_config')->nullable()->comment('JSON config');
            $table->boolean('is_active')->default(true)->comment('Active status');
            $table->unsignedBigInteger('total_occurrences')->default(0)->comment('Total site-wide');
            $table->datetime('last_occurrence_at')->nullable()->comment('Last occurrence');
            $table->timestamps();

            $table->unique('event_type');
            $table->index('is_active');
        });

        // Create site_growth_scores table
        $this->createTable('fleekdash_site_growth_scores', function (TableBuilder $table) {
            $table->id();
            $table->enum('period_type', ['daily', 'weekly', 'monthly', 'yearly']);
            $table->date('period_date')->comment('Period start date');
            $table->unsignedBigInteger('total_posts')->default(0);
            $table->unsignedBigInteger('total_users')->default(0);
            $table->unsignedBigInteger('total_comments')->default(0);
            $table->decimal('total_sales', 15, 2)->default(0.00);
            $table->unsignedBigInteger('total_orders')->default(0);
            $table->unsignedBigInteger('total_traffic')->default(0);
            $table->unsignedBigInteger('total_points')->default(0)->comment('Total growth points');
            $table->integer('goals_achieved')->default(0);
            $table->decimal('growth_percentage', 10, 2)->nullable();
            $table->timestamps();

            $table->unique(['period_type', 'period_date'], 'unique_period');
            $table->index('period_type');
            $table->index('period_date');
        });

        // Create site_growth_templates table
        $this->createTable('fleekdash_site_growth_templates', function (TableBuilder $table) {
            $table->id();
            $table->string('template_name', 255);
            $table->text('description')->nullable();
            $table->string('category', 100)->default('general');
            $table->string('target_audience', 255)->nullable();
            $table->longText('template_config')->comment('JSON config');
            $table->boolean('is_default')->default(false);
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->index('category');
            $table->index('is_default');
            $table->index('is_active');
        });

        // Insert default templates
        $this->insertDefaultTemplates();
    }

    public function down(): void
    {
        $this->dropTable('fleekdash_site_growth_templates');
        $this->dropTable('fleekdash_site_growth_scores');
        $this->dropTable('fleekdash_site_growth_events');

        delete_option('fleekdash_site_growth_meter_version');
    }

    /**
     * Insert default templates
     */
    private function insertDefaultTemplates(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'fleekdash_site_growth_templates';

        $templates = [
            [
                'template_name' => 'Blog Growth Template',
                'description' => 'Track blog growth metrics: posts, comments, users, traffic',
                'category' => 'blog',
                'target_audience' => 'Bloggers and content creators',
                'template_config' => json_encode([
                    'events' => [
                        'new_post' => [
                            'event_type' => 'new_post',
                            'event_name' => 'New Post Published',
                            'description' => 'Track when new posts are published',
                            'tracking_method' => 'automatic'
                        ],
                        'new_comment' => [
                            'event_type' => 'new_comment',
                            'event_name' => 'New Comment Received',
                            'description' => 'Track when new comments are posted',
                            'tracking_method' => 'automatic'
                        ],
                        'new_user' => [
                            'event_type' => 'new_user',
                            'event_name' => 'New User Registration',
                            'description' => 'Track when new users register',
                            'tracking_method' => 'automatic'
                        ],
                        'page_view' => [
                            'event_type' => 'page_view',
                            'event_name' => 'Page View',
                            'description' => 'Track page views',
                            'tracking_method' => 'automatic'
                        ]
                    ],
                    'goals' => [
                        'monthly_posts' => [
                            'goal_name' => 'Monthly Posts',
                            'goal_type' => 'posts',
                            'target_value' => 20,
                            'target_period' => 'monthly',
                            'description' => 'Publish 20 posts this month'
                        ]
                    ]
                ]),
                'is_default' => 1,
                'is_active' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ],
            [
                'template_name' => 'E-commerce Growth Template',
                'description' => 'Track e-commerce growth metrics',
                'category' => 'ecommerce',
                'target_audience' => 'Online stores',
                'template_config' => json_encode([
                    'events' => [
                        'new_product' => [
                            'event_type' => 'new_product',
                            'event_name' => 'New Product Added',
                            'description' => 'Track new products',
                            'tracking_method' => 'automatic'
                        ],
                        'new_order' => [
                            'event_type' => 'new_order',
                            'event_name' => 'New Order',
                            'description' => 'Track orders',
                            'tracking_method' => 'automatic'
                        ]
                    ]
                ]),
                'is_default' => 1,
                'is_active' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ],
            [
                'template_name' => 'Service Business Template',
                'description' => 'Track service business growth',
                'category' => 'services',
                'target_audience' => 'Service providers',
                'template_config' => json_encode([
                    'events' => [
                        'new_lead' => [
                            'event_type' => 'new_lead',
                            'event_name' => 'New Lead',
                            'description' => 'Track leads',
                            'tracking_method' => 'manual'
                        ]
                    ]
                ]),
                'is_default' => 1,
                'is_active' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ]
        ];

        foreach ($templates as $template) {
            $wpdb->insert($table, $template);
        }

        update_option('fleekdash_site_growth_meter_version', '1.0.0');
    }
};

