<?php

namespace FleekDash\Controllers;

// Load debug helpers
if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

use FleekDash\Core\AuthMiddleware;
use FleekDash\Models\SiteGrowthAchievement;
use FleekDash\Services\SiteGrowthAchievementsEngine;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Site Growth Achievements Controller
 *
 * High-performance REST API endpoints for the achievements system
 */
class SiteGrowthAchievementsController
{
    /**
     * Get achievements dashboard data
     */
    public function getDashboard(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $data = SiteGrowthAchievementsEngine::getDashboardData();

            return new WP_REST_Response([
                'success' => true,
                'data' => $data,
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting achievements dashboard: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get achievements by category
     */
    public function getByCategory(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $category = $request->get_param('category');
            $limit = $request->get_param('limit') ?: 10;

            if (!$category) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Category parameter is required',
                    'auth_status' => 'error'
                ], 400);
            }

            $achievements = SiteGrowthAchievement::getByCategory($category, $limit);

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'category' => $category,
                    'achievements' => $achievements
                ],
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting achievements by category: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get single achievement with detailed information
     */
    public function getSingle(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $achievement_id = $request->get_param('id');

            $achievement = SiteGrowthAchievement::find($achievement_id);

            if (!$achievement) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Achievement not found',
                    'auth_status' => 'error'
                ], 404);
            }

            // Calculate current month progress for this achievement
            $month_start = date('Y-m-01 00:00:00');
            $month_end = date('Y-m-t 23:59:59');

            $event_config = json_decode($achievement['event_config'] ?? '{}', true) ?: [];
            $current_month_value = SiteGrowthAchievementsEngine::calculateMonthlyValue(
                $achievement['event_type'] ?? '',
                $event_config,
                $month_start,
                $month_end
            );

            $detailed_data = [
                'achievement' => $achievement,
                'current_month_progress' => [
                    'value' => $current_month_value,
                    'target' => $achievement['target_value'] ?? 0,
                    'percentage' => ($achievement['target_value'] ?? 0) > 0
                        ? min(100, round(($current_month_value / ($achievement['target_value'] ?? 1)) * 100, 1))
                        : 0,
                    'remaining' => max(0, ($achievement['target_value'] ?? 0) - $current_month_value)
                ],
                'historical_data' => [
                    'best_record' => $achievement['current_record'] ?? 0,
                    'record_period' => $achievement['record_period'] ?? '',
                    'times_achieved' => $achievement['times_achieved'] ?? 0,
                    'last_achieved' => $achievement['last_achieved_at'] ?? null
                ]
            ];

            return new WP_REST_Response([
                'success' => true,
                'data' => $detailed_data,
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting achievement details: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Bootstrap achievements system (create achievements for existing events)
     */
    public function bootstrap(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to bootstrap achievements',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $results = SiteGrowthAchievementsEngine::bootstrap();

            return new WP_REST_Response([
                'success' => $results['success'],
                'data' => $results,
                'message' => $results['message'],
                'auth_status' => 'authenticated'
            ], $results['success'] ? 200 : 500);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error bootstrapping achievements: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Process monthly achievements (manual trigger)
     */
    public function processMonthly(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to process monthly achievements',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $month_period = $request->get_param('month'); // Optional YYYY-MM-01 format

            $results = SiteGrowthAchievementsEngine::processMonthlyAchievements($month_period);

            return new WP_REST_Response([
                'success' => true,
                'data' => $results,
                'message' => "Processed {$results['achievements_checked']} achievements, unlocked {$results['achievements_unlocked']}",
                'auth_status' => 'authenticated'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error processing monthly achievements: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Recalculate all achievements (maintenance endpoint)
     */
    public function recalculateAll(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to recalculate achievements',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $results = SiteGrowthAchievementsEngine::recalculateAllAchievements();

            return new WP_REST_Response([
                'success' => true,
                'data' => $results,
                'message' => "Recalculated {$results['total_processed']} achievements",
                'auth_status' => 'authenticated'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error recalculating achievements: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get achievements categories
     */
    public function getCategories(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $categories = SiteGrowthAchievement::getCategories();

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'categories' => $categories
                ],
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting categories: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Update achievement settings
     */
    public function updateAchievement(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to update achievement',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $achievement_id = $request->get_param('id');
            $data = $request->get_json_params();

            $achievement = SiteGrowthAchievement::find($achievement_id);

            if (!$achievement) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Achievement not found',
                    'auth_status' => 'error'
                ], 404);
            }

            // Allow updating specific fields
            $allowed_fields = [
                'achievement_name',
                'description',
                'target_value',
                'auto_scale',
                'scale_factor',
                'min_target',
                'max_target',
                'is_active',
                'achievement_icon',
                'achievement_color'
            ];

            $updated_fields = [];
            $update_data = [];

            foreach ($allowed_fields as $field) {
                if (isset($data[$field])) {
                    $update_data[$field] = $data[$field];
                    $updated_fields[] = $field;
                }
            }

            if (!empty($update_data)) {
                $update_data['updated_at'] = \current_time('mysql');
                SiteGrowthAchievement::update($achievement_id, $update_data);

                // Re-fetch updated achievement
                $achievement = SiteGrowthAchievement::find($achievement_id);
            }

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'achievement' => $achievement,
                    'updated_fields' => $updated_fields
                ],
                'message' => 'Achievement updated successfully',
                'auth_status' => 'authenticated'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error updating achievement: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Delete achievement
     */
    public function deleteAchievement(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to delete achievement',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $achievement_id = $request->get_param('id');

            $achievement = SiteGrowthAchievement::find($achievement_id);

            if (!$achievement) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Achievement not found',
                    'auth_status' => 'error'
                ], 404);
            }

            $achievement_name = $achievement['achievement_name'];
            SiteGrowthAchievement::delete($achievement_id);

            return new WP_REST_Response([
                'success' => true,
                'message' => "Achievement '{$achievement_name}' deleted successfully",
                'auth_status' => 'authenticated'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error deleting achievement: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get achievements statistics and analytics
     */
    public function getStatistics(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $period = $request->get_param('period') ?: 'monthly';
            $limit = $request->get_param('limit') ?: 10;

            $stats = [
                'summary' => SiteGrowthAchievement::getDashboardSummary(),
                'recent_achievements' => SiteGrowthAchievementsEngine::getRecentAchievements(30, $limit),
                'close_to_completion' => SiteGrowthAchievement::getCloseToCompletion($limit),
                'categories_breakdown' => [],
                'monthly_trends' => self::getMonthlyTrends($period)
            ];

            // Get breakdown by category
            $categories = SiteGrowthAchievement::getCategories();
            foreach ($categories as $category_key => $category_meta) {
                $category_achievements = SiteGrowthAchievement::getByCategory($category_key);

                // Count completed achievements
                $completed_count = count(array_filter($category_achievements, function($achievement) {
                    return !empty($achievement['is_achieved']);
                }));

                // Calculate average progress
                $total_count = count($category_achievements);
                $avg_progress = 0;

                if ($total_count > 0) {
                    $progress_sum = array_reduce($category_achievements, function($sum, $achievement) {
                        $target = $achievement['target_value'] ?? 0;
                        $current = $achievement['current_record'] ?? 0;

                        if ($target > 0) {
                            return $sum + min(100, ($current / $target) * 100);
                        }
                        return $sum;
                    }, 0);

                    $avg_progress = $total_count > 0 ? $progress_sum / $total_count : 0;
                }

                $stats['categories_breakdown'][$category_key] = [
                    'meta' => $category_meta,
                    'total' => $total_count,
                    'completed' => $completed_count,
                    'avg_progress' => $avg_progress
                ];
            }

            return new WP_REST_Response([
                'success' => true,
                'data' => $stats,
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting achievements statistics: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Create custom achievement
     */
    public function createCustom(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            if (!($auth['authenticated'] ?? false)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Authentication required to create achievement',
                    'auth_status' => 'fallback'
                ], 401);
            }

            $data = $request->get_json_params();

            // Validate required fields
            $required = ['achievement_name', 'target_value', 'category'];
            foreach ($required as $field) {
                if (empty($data[$field])) {
                    return new WP_REST_Response([
                        'success' => false,
                        'message' => "Field '{$field}' is required",
                        'auth_status' => 'error'
                    ], 400);
                }
            }

            // Create achievement
            $achievement = SiteGrowthAchievement::create([
                'achievement_type' => 'monthly_record',
                'achievement_name' => $data['achievement_name'],
                'achievement_slug' => sanitize_title($data['achievement_name']),
                'description' => $data['description'] ?? '',
                'category' => $data['category'],
                'target_value' => (int) $data['target_value'],
                'current_record' => 0,
                'is_achieved' => false,
                'auto_scale' => $data['auto_scale'] ?? true,
                'scale_factor' => (float) ($data['scale_factor'] ?? 1.20),
                'min_target' => (int) ($data['min_target'] ?? 20),
                'max_target' => (int) ($data['max_target'] ?? 0),
                'achievement_icon' => $data['achievement_icon'] ?? 'award',
                'achievement_color' => $data['achievement_color'] ?? '#22C55E',
                'is_active' => true,
                'display_order' => SiteGrowthAchievement::getNextDisplayOrder($data['category'])
            ]);

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'achievement' => $achievement
                ],
                'message' => 'Custom achievement created successfully',
                'auth_status' => 'authenticated'
            ], 201);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error creating custom achievement: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get monthly trends for achievements
     */
    private function getMonthlyTrends($period)
    {
        try {
            global $wpdb;
            $table = $wpdb->prefix . 'fleekdash_site_growth_achievements';

            // Get achievement completion trends over time
            $months_back = $period === 'yearly' ? 12 : 6;

            $sql = "SELECT
                        DATE_FORMAT(achieved_at, '%Y-%m') as month,
                        COUNT(*) as achievements_unlocked,
                        AVG(target_value) as avg_target,
                        AVG(current_record) as avg_record
                    FROM {$table}
                    WHERE achieved_at >= DATE_SUB(NOW(), INTERVAL {$months_back} MONTH)
                    AND is_achieved = 1
                    GROUP BY DATE_FORMAT(achieved_at, '%Y-%m')
                    ORDER BY month DESC";

            $trends = $wpdb->get_results($sql, ARRAY_A);

            return array_map(function($trend) {
                return [
                    'month' => $trend['month'],
                    'achievements_unlocked' => (int) $trend['achievements_unlocked'],
                    'avg_target' => round((float) $trend['avg_target'], 0),
                    'avg_record' => round((float) $trend['avg_record'], 0)
                ];
            }, $trends);

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: Error getting monthly trends: " . $e->getMessage());
            return [];
        }
    }

    /**
     * Get API summary (V2.2 - uses refactored getApiSummary)
     */
    public function getSummary(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $summary = SiteGrowthAchievementsEngine::getApiSummary();

            return new WP_REST_Response([
                'success' => true,
                'data' => $summary,
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting achievements summary: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Get recent achievements (V2.2 - uses refactored getRecentAchievements)
     */
    public function getRecent(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth_graceful('authenticated');

            $days = $request->get_param('days') ?: 7;
            $limit = $request->get_param('limit') ?: 5;

            $recent = SiteGrowthAchievementsEngine::getRecentAchievements($days, $limit);

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'achievements' => $recent,
                    'days' => $days,
                    'limit' => $limit
                ],
                'auth_status' => ($auth['authenticated'] ?? false) ? 'authenticated' : 'fallback'
            ], 200);

        } catch (\Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error getting recent achievements: ' . $e->getMessage(),
                'auth_status' => 'error'
            ], 500);
        }
    }

    /**
     * Graceful auth check: never throws, logs and returns unauthenticated state
     */
    private function check_auth_graceful($required_level = 'authenticated')
    {
        try {
            $auth = AuthMiddleware::check($required_level);
            if (!$auth['authenticated']) {
                fleekdash_log_debug('FleekDash: Achievements access without proper authentication');
            }
            return $auth;
        } catch (\Throwable $e) {
            fleekdash_log_error('FleekDash: Achievements AuthMiddleware error: ' . $e->getMessage());
            return [
                'authenticated' => false,
                'user_id' => 0,
                'level' => $required_level,
            ];
        }
    }
}
