<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Bonus;
use App\Models\BonusHistory;
use App\Models\Lead;
use App\Models\Offerwall;
use App\Models\User;
use App\Models\Withdrawal;
use App\Support\DirectOfferFeed;
use App\Support\OfferAudience;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        $rank = User::where('is_admin', false)
            ->where('total_points', '>', $user->total_points)
            ->count() + 1;

        $offerwalls = Offerwall::where('is_active', true)
            ->when(OfferAudience::deviceForRequest(request()) === 'desktop', fn ($query) => $query->where('is_mobile', false))
            ->withCount(['clicks as recent_clicks_count' => function ($query) {
                $query->where('created_at', '>=', now()->subDays(14));
            }])
            ->get();
        $providerOffers = DirectOfferFeed::activeProviderOffers();
        $directOffers = DirectOfferFeed::from($offerwalls, $providerOffers);

        $stats = [
            'rank' => $rank,
            'completed_offers' => Lead::where('user_id', $user->id)->where('status', 'approved')->count(),
            'total_cashout' => Withdrawal::where('user_id', $user->id)->where('status', 'approved')->sum('amount'),
            'lifetime_income' => Lead::where('user_id', $user->id)->sum('credited_points'),
            'offerwalls' => $offerwalls->count(),
            'hot_offers' => DirectOfferFeed::hot($directOffers, 10),
            'featured_offers' => DirectOfferFeed::featured($directOffers, 10),
            'providers' => $offerwalls->where('type', 'offer')->sortByDesc('recent_clicks_count')->take(12)->values(),
            'surveys' => $offerwalls->where('type', 'survey')->take(6)->values(),
            'recent_leads' => Lead::where('user_id', $user->id)->latest()->take(5)->get(),
            'recent_withdrawals' => Withdrawal::where('user_id', $user->id)->latest()->take(3)->get(),
            'campaigns' => collect(),
        ];

        return view('user.home', compact('stats'));
    }

    public function redeem(Request $request)
    {
        $request->validate(['code' => ['required', 'string', 'max:64']]);

        $code = trim((string) $request->code);
        // Codes are case-insensitive.
        $bonus = Bonus::whereRaw('UPPER(code) = ?', [strtoupper($code)])->first();

        if (!$bonus)
            return redirect()->back()->with('error', 'Invalid bonus code');

        if (!$bonus->is_active)
            return redirect()->back()->with('error', 'Bonus code is not active');

        if ($this->IsBonusRedeemed($bonus->id))
            return redirect()->back()->with('error', 'You have already redeemed this bonus');

        // Global usage cap (0 / null = unlimited).
        if ($bonus->max_uses && $bonus->history()->count() >= (int) $bonus->max_uses) {
            return redirect()->back()->with('error', 'This bonus code has reached its usage limit');
        }

        $user = auth()->user();

        // firstOrCreate + wasRecentlyCreated guards against double-submit races
        // crediting the same bonus twice.
        $history = $user->bonusHistory()->firstOrCreate([
            'bonus_id' => $bonus->id,
        ]);

        if (!$history->wasRecentlyCreated) {
            return redirect()->back()->with('error', 'You have already redeemed this bonus');
        }

        $user->addPoints($bonus->points);

        return redirect()->back()->with('success', 'Bonus of '.number_format($bonus->points).' coins redeemed successfully!');
    }

    public function IsBonusRedeemed($id): bool
    {
        $history = BonusHistory::where('user_id', auth()->user()->id)->where('bonus_id', $id)->first();
        if ($history)
            return true;

        return false;
    }
}
