<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Badge;
use App\Models\UserBadge;
use App\Models\UserActivity;

class GamificationController extends Controller
{
    public function getProgress(Request $request)
    {
        $user = $request->user();
        $streakDays = $this->calculateStreak($user);
        $calendar = $this->getStreakCalendar($user);
        $recentActivities = UserActivity::where('user_id', $user->id)
            ->latest()->take(5)->get()
            ->map(fn($a) => ['title' => $a->description, 'points' => $a->points, 'date' => $a->created_at->format('Y-m-d')]);

        return response()->json([
            'success' => true,
            'data' => [
                'level' => $user->level ?? 1,
                'points' => $user->points ?? 0,
                'experience' => $user->experience ?? 0,
                'next_level_xp' => ($user->level ?? 1) * 300,
                'streak_days' => $streakDays,
                'streak_calendar' => $calendar,
                'recent_activities' => $recentActivities,
            ]
        ]);
    }

    public function triggerAction(Request $request)
    {
        $user = $request->user();
        $action = $request->input('action');
        $pointsMap = ['daily_login' => 5, 'complete_content' => 20, 'complete_course' => 100, 'write_review' => 10];
        $points = $pointsMap[$action] ?? 0;
        if ($points > 0) {
            $user->increment('points', $points);
            $user->increment('experience', $points);
            UserActivity::create(['user_id' => $user->id, 'action' => $action, 'points' => $points, 'description' => 'امتیاز دریافت شد']);
            $this->checkLevelUp($user);
        }
        return response()->json(['success' => true, 'data' => ['points_earned' => $points]]);
    }

    private function calculateStreak($user): int
    {
        return $user->streak_days ?? 0;
    }

    private function getStreakCalendar($user): array
    {
        $calendar = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->format('Y-m-d');
            $calendar[] = ['date' => $date, 'completed' => ($i >= 3), 'is_today' => ($i === 0)];
        }
        return $calendar;
    }

    private function checkLevelUp($user): void
    {
        $nextXp = $user->level * 300;
        if ($user->experience >= $nextXp) {
            $user->increment('level');
        }
    }
}
