<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\OfferwallClick;
use App\Models\ReferralEvent;
use App\Models\User;
use Illuminate\Http\Request;

/**
 * "My Profile" ledger: stats cards plus a tabbed history of earnings
 * (offers / surveys / rewards / referrals), started offers, and withdrawals.
 */
class HistoryController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $user->load('latestFaceVerification');

        $tab = in_array($request->input('tab'), ['earnings', 'started', 'withdrawals'], true)
            ? $request->input('tab') : 'earnings';
        $type = in_array($request->input('type'), ['offers', 'surveys', 'rewards', 'referrals'], true)
            ? $request->input('type') : 'offers';
        $pendingOnly = $request->boolean('pending');
        $partner = (string) $request->input('partner', '');

        $approvedLeads = Lead::where('user_id', $user->id)->where('credited_points', '>', 0);

        $stats = [
            'total_usd' => coins_to_usd((clone $approvedLeads)->sum('credited_points')),
            'completed' => (clone $approvedLeads)->count(),
            'referred' => User::where('referred_by', $user->id)->count(),
            'last30_usd' => coins_to_usd((clone $approvedLeads)->where('created_at', '>=', now()->subDays(30))->sum('credited_points')),
            'referral_earnings' => (float) $user->referral_earnings,
        ];

        $levelStep = max(1, site_int('level_points_step', 1000));
        $level = (int) floor((float) $user->total_points / $levelStep);
        $levelProgress = ((float) $user->total_points - $level * $levelStep) / $levelStep * 100;
        $toNextLevel = (int) ceil($levelStep - ((float) $user->total_points - $level * $levelStep));

        $partners = Lead::where('user_id', $user->id)
            ->whereNotNull('company')->distinct()->orderBy('company')->pluck('company');

        if ($tab === 'earnings') {
            if ($type === 'referrals') {
                $rows = ReferralEvent::with('referredUser')->where('referrer_id', $user->id)
                    ->latest()
                    ->paginate(15)->withQueryString();
            } else {
                $rows = Lead::where('user_id', $user->id)
                    ->when($type === 'offers', fn ($q) => $q->where('type', 'offer'))
                    ->when($type === 'surveys', fn ($q) => $q->where('type', 'survey'))
                    ->when($type === 'rewards', fn ($q) => $q->whereIn('type', ['reward', 'bonus']))
                    ->when($pendingOnly, fn ($q) => $q->where('status', 'held'))
                    ->when($partner !== '', fn ($q) => $q->where('company', $partner))
                    ->latest()
                    ->paginate(15)->withQueryString();
            }
        } elseif ($tab === 'started') {
            $rows = OfferwallClick::where('user_id', $user->id)
                ->latest()
                ->paginate(15)->withQueryString();
        } else {
            $rows = $user->withdrawals()->latest()->paginate(15)->withQueryString();
        }

        return view('user.history', compact(
            'user', 'stats', 'tab', 'type', 'pendingOnly', 'partner', 'partners', 'rows',
            'level', 'levelProgress', 'toNextLevel'
        ));
    }
}
