<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FaucetHistory;
use App\Models\ReferralCommission;
use App\Models\IpData;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Auth\Events\Verified;

class FaucetController extends Controller
{
    public function __construct()
    {
        $faucet_status = get_setting('faucet_status');
        if($faucet_status == 'off'){
            abort(404, "Offerwall not found.");
        }
    }
    public function index(Request $request)
    {
        if (!$request->user()->hasVerifiedEmail()) {
            return redirect('/dashboard')->with('message', 'Please verify your email first')->with('type', 'error');
        }
        $userId = Auth::id();
        $ip = $request->ip();
        $faucetTimer = (int) get_setting('faucet_timer');
        $faucetLimit = get_setting('faucet_limit');
    
        $lastClaim = FaucetHistory::where('ip', $ip)
            ->orWhere('user_id', $userId)
            ->latest()
            ->first();
            
        $remainingTime = 0;
        if ($lastClaim) {
            $nextClaimTime = $lastClaim->created_at->clone()->addSeconds($faucetTimer);
            if ($nextClaimTime->isFuture()) {
                $remainingTime = number_format(max(0, now()->diffInSeconds($nextClaimTime, false)),0);
            }
        }
    
        $claimsToday = FaucetHistory::where(function ($query) use ($userId, $ip) {
            $query->where('ip', $ip)->orWhere('user_id', $userId);
        })->whereDate('created_at', today())->count();
        
        $remainingClaims = max(0, $faucetLimit - $claimsToday);
        $page = 'Faucet';
    
        return view('faucet', compact('remainingTime', 'remainingClaims', 'page'));
    }

    public function fetchHistory(Request $request)
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request'], 400);
        }
        $perPage = 10;
        $query = FaucetHistory::orderBy('created_at', 'desc')->where('user_id', Auth::id());
    
        $FaucetHistory = $query->paginate($perPage);
    
        $records = $FaucetHistory->map(function ($item) {
            return [
                'id' => $item->id,
                'ip' => $item->ip,
                'reward' => '<span class="flex items-center">
                    <i class="fa fa-plus text-xs mr-1 text-success"></i> ' . balanceAndSymbol($item->reward) . '
                  </span>',
                'date' => $item->updated_at->diffForHumans(),
            ];
        });
    
        return response()->json([
            'records' => $records,
            'current_page' => $FaucetHistory->currentPage(),
            'total_pages' => $FaucetHistory->lastPage(),
            'prev_page' => $FaucetHistory->previousPageUrl() ? $FaucetHistory->currentPage() - 1 : null,
            'next_page' => $FaucetHistory->nextPageUrl() ? $FaucetHistory->currentPage() + 1 : null,
        ]);
    }

    public function claimFaucet(Request $request)
    {
        if (!$request->user()->hasVerifiedEmail()) {
            return redirect('/dashboard')->with('message', 'Please verify your email first')->with('type', 'error');
        }
        if (!session()->has('cdata')) {
            return redirect()->back()->with('message', 'The captcha verification failed. Please try again.')->with('type', 'error');
        }
    
        $functionData = session('cdata');
        $captchaResponse = $request->input($functionData['ctoken']);
        $isVerified = verify_ccaptcha($functionData, $captchaResponse);
    
        if (!$isVerified) {
            return redirect()->back()->with('message', 'The captcha verification failed. Please try again.')->with('type', 'error');
        }
        $userId = Auth::id();
        $ip = $request->ip();
        $reward = get_setting('faucet_reward');
        $referral = get_setting('referral');
        $faucetTimer = (int) get_setting('faucet_timer');
        $faucetLimit = get_setting('faucet_limit');
    
        $lastClaim = FaucetHistory::where('ip', $ip)
            ->orWhere('user_id', $userId)
            ->latest()
            ->first();
    
        if ($lastClaim) {
            $nextClaimTime = $lastClaim->created_at->addSeconds($faucetTimer);
            
            if ($nextClaimTime->isFuture()) {
                $remainingTime = number_format(max(0, now()->diffInSeconds($nextClaimTime, false)),0);
                return redirect()->back()->with('message', "Please wait $remainingTime seconds before claiming again.")->with('type', 'error');
            }
        }
    
        $claimsToday = FaucetHistory::where(function ($query) use ($userId, $ip) {
            $query->where('ip', $ip)->orWhere('user_id', $userId);
        })->whereDate('created_at', today())->count();
    
        if ($claimsToday >= $faucetLimit) {
            return redirect()->back()->with('message', 'Daily claim limit reached')->with('type', 'error');
        }
        
        $service = get_setting('lookup_service');

        $cacheKey = "ip_lookup_{$service}_{$ip}";
        
        $ipData = Cache::remember($cacheKey, now()->addHours(6), function () use ($ip, $service) {
            return IpData::where('ip', $ip)->where('api_service', $service)->first();
        });
        
        $country = "";
        if($ipData) {
            $country = $ipData->country_code;
        }
        
        $user = User::find($userId);
        $user->earn($reward);
        $user->updateLastActivity();
        $user->detectAndMarkMultiAccount();
        
        FaucetHistory::create([
            'user_id' => $userId,
            'reward' => $reward,
            'ip' => $ip,
            'country' => $country,
        ]);
        $user = Auth::user();
        if ($user->referred_by != 0) {
            $referrer = User::find($user->referred_by);
            
            if ($referrer) {
                $commission = ($reward * $referral) / 100;
                if($commission > 0) {
                    $referrer->earn($commission, true);
            
                    ReferralCommission::create([
                        'referrer_id' => $referrer->id,
                        'referred_id' => $user->id,
                        'amount' => $commission,
                        'type' => 'faucet',
                        'ip_address' => $ip,
                    ]);
                }
            }
        }

        return redirect()->back()->with('message', 
            '<div style="display: flex; align-items: center; justify-content: center; text-align: center; gap: 5px;">' . 
            balanceAndSymbol(get_setting('faucet_reward')) . 
            '<span>added to your balance!</span></div>'
        )->with('type', 'success');

    }

}
