<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\User\ReferralController;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Notification;

class ReferralApiController extends Controller
{
    protected $referralController;

    public function __construct()
    {
        $this->referralController = new ReferralController();
    }

    /**
     * Get referral data
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        try {
            $user = auth()->user();

            $referrals = $user->referredUsers()
                ->orderBy('id', 'DESC')
                ->get();

            $totalReferrals = $user->referredUsers()->count();
            $totalEarnings = $user->transactions()
                ->where('description', 'Referral Bonus')
                ->sum('amount');

            return response()->json([
                'status' => 'success',
                'data' => [
                    'total_referrals' => $totalReferrals,
                    'total_earnings' => $totalEarnings,
                    // 'referral_link' => url('/register?ref=' . $user->username),
                    'referral_code' => $user->username,
                    'referrals' => $referrals,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch referral data',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get referral statistics
     * @return JsonResponse
     */
    public function stats(): JsonResponse
    {
        try {
            $user = auth()->user();

            $totalReferrals = $user->referredUsers()->count();
            $activeReferrals = $user->referredUsers()->where('status', 'active')->count();
            $totalEarnings = $user->transactions()
                ->where('remark', 'referral_bonus')
                ->sum('amount');

            $monthlyReferrals = $user->referredUsers()
                ->whereMonth('created_at', now()->month)
                ->whereYear('created_at', now()->year)
                ->count();

            $monthlyEarnings = $user->transactions()
                ->where('remark', 'referral_bonus')
                ->whereMonth('created_at', now()->month)
                ->whereYear('created_at', now()->year)
                ->sum('amount');

            return response()->json([
                'status' => 'success',
                'data' => [
                    'total_referrals' => $totalReferrals,
                    'active_referrals' => $activeReferrals,
                    'total_earnings' => $totalEarnings,
                    'monthly_referrals' => $monthlyReferrals,
                    'monthly_earnings' => $monthlyEarnings,
                    'referral_rate' => site('referral_bonus') ?? 0
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch referral statistics',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
