<?php
/**
 * Growth Routes
 *
 * Consolidated API routes for Growth Meter and Achievements systems.
 * Migrated from:
 * - GrowthMeterAPI.php (22 routes)
 * - GrowthAchievementsAPI.php (6 routes)
 * - SiteGrowthAchievementsAPI.php (13 routes)
 *
 * @package FleekDash V2.2
 * @since   V2.2 Refactoring - Phase 1
 */

namespace FleekDash\Routes\Groups;

use FleekDash\Libs\API\Route;
use FleekDash\Libs\API\RouteAuthMiddleware;
use FleekDash\Controllers\SiteGrowthMeterController;
use FleekDash\Controllers\GrowthAchievementsController;
use FleekDash\Controllers\SiteGrowthAchievementsController;

class GrowthRoutes
{
    /**
     * Register all growth-related routes
     *
     * @param Route $route Route instance
     * @return void
     */
    public static function register(Route $route)
    {
        // ============================================
        // GROWTH METER ROUTES (22 routes)
        // ============================================

        // Dashboard
        Route::get('growth-meter/dashboard', [SiteGrowthMeterController::class, 'getDashboard'],
            RouteAuthMiddleware::authenticated(), [
            'period' => [
                'type' => 'string',
                'required' => false,
                'default' => 'daily',
                'enum' => ['daily', 'weekly', 'monthly'],
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        // Initialize Growth Meter
        Route::post('growth-meter/initialize', [SiteGrowthMeterController::class, 'initialize'],
            RouteAuthMiddleware::authenticated(), [
            'template_id' => [
                'type' => 'integer',
                'required' => false,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Force initialize Growth Meter
        Route::post('growth-meter/force-initialize', [SiteGrowthMeterController::class, 'forceInitialize'],
            RouteAuthMiddleware::admin());

        // Events - Get all or Create
        Route::get('growth-meter/events', [SiteGrowthMeterController::class, 'getEvents'],
            RouteAuthMiddleware::authenticated(), [
            'active_only' => [
                'type' => 'string',
                'required' => false,
                'default' => 'false',
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        Route::post('growth-meter/events', [SiteGrowthMeterController::class, 'createEvent'],
            RouteAuthMiddleware::admin());

        // Single event - Get, Update or Delete
        Route::get('growth-meter/events/{id}', [SiteGrowthMeterController::class, 'getEvent'],
            RouteAuthMiddleware::authenticated(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        Route::put('growth-meter/events/{id}', [SiteGrowthMeterController::class, 'updateEvent'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        Route::delete('growth-meter/events/{id}', [SiteGrowthMeterController::class, 'deleteEvent'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Record event occurrence
        Route::post('growth-meter/events/{id}/record', [SiteGrowthMeterController::class, 'recordEvent'],
            RouteAuthMiddleware::authenticated(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ],
            'custom_points' => [
                'type' => 'integer',
                'required' => false,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Goals - Get all or Create
        Route::get('growth-meter/goals', [SiteGrowthMeterController::class, 'getGoals'],
            RouteAuthMiddleware::authenticated(), [
            'active_only' => [
                'type' => 'string',
                'required' => false,
                'default' => 'true',
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'with_progress' => [
                'type' => 'string',
                'required' => false,
                'default' => 'false',
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        Route::post('growth-meter/goals', [SiteGrowthMeterController::class, 'createGoal'],
            RouteAuthMiddleware::admin());

        // Single goal - Update or Delete
        Route::put('growth-meter/goals/{id}', [SiteGrowthMeterController::class, 'updateGoal'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        Route::delete('growth-meter/goals/{id}', [SiteGrowthMeterController::class, 'deleteGoal'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Analytics
        Route::get('growth-meter/analytics', [SiteGrowthMeterController::class, 'getAnalytics'],
            RouteAuthMiddleware::authenticated(), [
            'period' => [
                'type' => 'string',
                'required' => false,
                'default' => 'daily',
                'enum' => ['daily', 'weekly', 'monthly'],
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'days' => [
                'type' => 'integer',
                'required' => false,
                'default' => 30,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Points map - Get or Save
        Route::get('growth-meter/points-map', [SiteGrowthMeterController::class, 'getPointsMap'],
            RouteAuthMiddleware::authenticated());

        Route::post('growth-meter/points-map', [SiteGrowthMeterController::class, 'savePointsMap'],
            RouteAuthMiddleware::admin());

        // Event types registry
        Route::get('growth-meter/event-types', function () {
            try {
                $service = new \FleekDash\Services\SiteGrowthMeterService();
                $types = $service->getEventTypes();

                $event_types_data = [];
                foreach ($types as $key => $type) {
                    $event_types_data[$key] = [
                        'label' => $type['label'] ?? ucfirst(str_replace('_', ' ', $key)),
                        'description' => $type['description'] ?? '',
                        'customization_schema' => $type['customization_schema'] ?? []
                    ];
                }

                return new \WP_REST_Response([
                    'success' => true,
                    'data' => ['event_types' => $event_types_data],
                    'auth_status' => 'authenticated',
                ], 200);
            } catch (\Throwable $e) {
                return new \WP_REST_Response([
                    'success' => false,
                    'message' => 'Error loading event types: ' . $e->getMessage(),
                    'auth_status' => 'error',
                ], 500);
            }
        }, RouteAuthMiddleware::authenticated());

        // Dynamic options for UI - Post Types
        Route::get('growth-meter/options/post-types', function () {
            try {
                $post_types = \get_post_types(['public' => true], 'names');
                $excluded = ['page', 'profile'];
                $allowed = array_values(array_diff($post_types, $excluded));
                $opts = [];
                foreach ($allowed as $pt) {
                    $opts[] = ['value' => $pt, 'label' => ucfirst(str_replace('_', ' ', $pt))];
                }
                return new \WP_REST_Response([
                    'success' => true,
                    'data' => ['options' => $opts],
                    'auth_status' => 'authenticated',
                ], 200);
            } catch (\Throwable $e) {
                return new \WP_REST_Response([
                    'success' => false,
                    'message' => 'Error loading post types: ' . $e->getMessage(),
                    'auth_status' => 'error',
                ], 500);
            }
        }, RouteAuthMiddleware::authenticated());

        // Dynamic options for UI - User Roles
        Route::get('growth-meter/options/user-roles', function () {
            try {
                if (!function_exists('get_editable_roles')) {
                    require_once(ABSPATH . 'wp-admin/includes/user.php');
                }

                $roles = [];
                if (function_exists('get_editable_roles')) {
                    $roles = get_editable_roles();
                } else if (function_exists('wp_roles')) {
                    $wp_roles = wp_roles();
                    $roles = $wp_roles->get_names();
                } else {
                    $roles = [
                        'subscriber' => ['name' => 'Subscriber'],
                        'contributor' => ['name' => 'Contributor'],
                        'author' => ['name' => 'Author'],
                        'editor' => ['name' => 'Editor'],
                        'administrator' => ['name' => 'Administrator']
                    ];
                }

                $opts = [];
                foreach ($roles as $slug => $r) {
                    $label = isset($r['name']) ? $r['name'] : (is_string($r) ? $r : ucfirst($slug));
                    $opts[] = ['value' => $slug, 'label' => $label];
                }

                return new \WP_REST_Response([
                    'success' => true,
                    'data' => ['options' => $opts],
                    'auth_status' => 'authenticated',
                ], 200);
            } catch (\Throwable $e) {
                return new \WP_REST_Response([
                    'success' => false,
                    'message' => 'Error loading user roles: ' . $e->getMessage(),
                    'auth_status' => 'error',
                ], 500);
            }
        }, RouteAuthMiddleware::authenticated());

        // Leaderboard
        Route::get('growth-meter/leaderboard', [SiteGrowthMeterController::class, 'getLeaderboard'],
            RouteAuthMiddleware::authenticated(), [
            'period' => [
                'type' => 'string',
                'required' => false,
                'default' => 'monthly',
                'enum' => ['daily', 'weekly', 'monthly'],
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'default' => 10,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Templates - Get all
        Route::get('growth-meter/templates', [SiteGrowthMeterController::class, 'getTemplates'],
            RouteAuthMiddleware::authenticated(), [
            'category' => [
                'type' => 'string',
                'required' => false,
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'popular_only' => [
                'type' => 'string',
                'required' => false,
                'default' => 'false',
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'default' => 6,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Single template
        Route::get('growth-meter/templates/{id}', [SiteGrowthMeterController::class, 'getTemplate'],
            RouteAuthMiddleware::authenticated(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Apply template
        Route::post('growth-meter/templates/{id}/apply', [SiteGrowthMeterController::class, 'applyTemplate'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Template categories
        Route::get('growth-meter/templates/categories', [SiteGrowthMeterController::class, 'getCategories'],
            RouteAuthMiddleware::authenticated());

        // Export data
        Route::get('growth-meter/export', [SiteGrowthMeterController::class, 'exportData'],
            RouteAuthMiddleware::admin(), [
            'format' => [
                'type' => 'string',
                'required' => false,
                'default' => 'json',
                'enum' => ['json', 'csv'],
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        // Retroactive metrics calculation
        Route::post('growth-meter/retroactive', [SiteGrowthMeterController::class, 'calculate_retroactive_metrics'],
            RouteAuthMiddleware::admin());

        // Test data insertion
        Route::post('growth-meter/test-data', [SiteGrowthMeterController::class, 'insert_test_data'],
            RouteAuthMiddleware::admin());

        // Snapshot scheduler - Status and manual trigger
        Route::get('growth-meter/snapshot/status', [SiteGrowthMeterController::class, 'getSnapshotStatus'],
            RouteAuthMiddleware::authenticated());

        Route::post('growth-meter/snapshot/trigger', [SiteGrowthMeterController::class, 'triggerSnapshot'],
            RouteAuthMiddleware::admin(), [
            'month_year' => [
                'type' => 'string',
                'required' => false,
                'validate_callback' => function ($param) {
                    return empty($param) || preg_match('/^\d{4}-\d{2}$/', $param);
                },
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        // Recalculate points manually
        Route::post('growth-meter/recalculate-points', [SiteGrowthMeterController::class, 'recalculatePoints'],
            RouteAuthMiddleware::authenticated());

        // ============================================
        // GROWTH ACHIEVEMENTS ROUTES (6 routes)
        // ============================================

        // Get all achievements
        Route::get('growth-meter/achievements', [GrowthAchievementsController::class, 'get_achievements'],
            RouteAuthMiddleware::public(), [
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'sanitize_callback' => 'absint'
            ],
            'type' => [
                'type' => 'string',
                'required' => false,
                'enum' => [
                    'daily_record',
                    'weekly_record',
                    'monthly_record',
                    'all_time_record',
                    'streak_milestone',
                    'points_milestone'
                ],
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'period' => [
                'type' => 'string',
                'required' => false,
                'enum' => ['daily', 'weekly', 'monthly', 'all_time'],
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        // Get single achievement
        Route::get('growth-meter/achievements/{id}', [GrowthAchievementsController::class, 'get_achievement'],
            RouteAuthMiddleware::public(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Get achievement statistics
        Route::get('growth-meter/achievements/stats', [GrowthAchievementsController::class, 'get_achievement_stats'],
            RouteAuthMiddleware::public());

        // Get milestones only
        Route::get('growth-meter/achievements/milestones', [GrowthAchievementsController::class, 'get_milestones'],
            RouteAuthMiddleware::public(), [
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Get grouped achievements
        Route::get('growth-meter/achievements/grouped', [GrowthAchievementsController::class, 'get_achievements_grouped'],
            RouteAuthMiddleware::public());

        // Trigger achievement check
        Route::post('growth-meter/achievements/check', [GrowthAchievementsController::class, 'check_achievements'],
            RouteAuthMiddleware::authenticated());

        // ============================================
        // SITE GROWTH ACHIEVEMENTS ROUTES (13 routes)
        // ============================================

        // Dashboard
        Route::get('growth-achievements/dashboard', [SiteGrowthAchievementsController::class, 'getDashboard'],
            RouteAuthMiddleware::authenticated());

        // Get achievements by category
        Route::get('growth-achievements/category/{category}', [SiteGrowthAchievementsController::class, 'getByCategory'],
            RouteAuthMiddleware::authenticated(), [
            'category' => [
                'type' => 'string',
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'default' => 10,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Get single achievement details
        Route::get('growth-achievements/{id}', [SiteGrowthAchievementsController::class, 'getSingle'],
            RouteAuthMiddleware::authenticated(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Update achievement
        Route::put('growth-achievements/{id}', [SiteGrowthAchievementsController::class, 'updateAchievement'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Delete achievement
        Route::delete('growth-achievements/{id}', [SiteGrowthAchievementsController::class, 'deleteAchievement'],
            RouteAuthMiddleware::admin(), [
            'id' => [
                'type' => 'integer',
                'required' => true,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Bootstrap achievements system
        Route::post('growth-achievements/bootstrap', [SiteGrowthAchievementsController::class, 'bootstrap'],
            RouteAuthMiddleware::admin());

        // Process monthly achievements
        Route::post('growth-achievements/process-monthly', [SiteGrowthAchievementsController::class, 'processMonthly'],
            RouteAuthMiddleware::admin(), [
            'month' => [
                'type' => 'string',
                'required' => false,
                'validate_callback' => function ($param) {
                    return empty($param) || preg_match('/^\d{4}-\d{2}-01$/', $param);
                },
                'sanitize_callback' => 'sanitize_text_field'
            ]
        ]);

        // Recalculate all achievements
        Route::post('growth-achievements/recalculate', [SiteGrowthAchievementsController::class, 'recalculateAll'],
            RouteAuthMiddleware::admin());

        // Get categories
        Route::get('growth-achievements/categories', [SiteGrowthAchievementsController::class, 'getCategories'],
            RouteAuthMiddleware::authenticated());

        // Get statistics and analytics
        Route::get('growth-achievements/statistics', [SiteGrowthAchievementsController::class, 'getStatistics'],
            RouteAuthMiddleware::authenticated(), [
            'period' => [
                'type' => 'string',
                'required' => false,
                'default' => 'monthly',
                'enum' => ['monthly', 'yearly'],
                'sanitize_callback' => 'sanitize_text_field'
            ],
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'default' => 10,
                'sanitize_callback' => 'absint'
            ]
        ]);

        // Create custom achievement
        Route::post('growth-achievements/custom', [SiteGrowthAchievementsController::class, 'createCustom'],
            RouteAuthMiddleware::admin());

        // Get API summary
        Route::get('growth-achievements/summary', [SiteGrowthAchievementsController::class, 'getSummary'],
            RouteAuthMiddleware::authenticated());

        // Get recent achievements
        Route::get('growth-achievements/recent', [SiteGrowthAchievementsController::class, 'getRecent'],
            RouteAuthMiddleware::authenticated(), [
            'days' => [
                'type' => 'integer',
                'required' => false,
                'default' => 7,
                'sanitize_callback' => 'absint'
            ],
            'limit' => [
                'type' => 'integer',
                'required' => false,
                'default' => 5,
                'sanitize_callback' => 'absint'
            ]
        ]);
    }
}
