<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use App\Models\OfferwallHistory;
use App\Models\User;
use Illuminate\Auth\Events\Verified;

class OfferwallController extends Controller
{
    public function index(Request $request)
    {
        $page = 'Offerwall Leads';

        return view('admin.history.offerwall', compact('page'));
    }

    public function fetchHistory(Request $request, $status, $uid = '')
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request'], 400);
        }
        
        $perPage = $request->input('perpage');
        $search = $request->input('search');

        if(!empty($uid)) {
            $query = OfferwallHistory::with('user')
                ->orderBy('created_at', 'desc')
                ->where('user_id', $uid)
                ->where('status', $status);
        }else{
            $query = OfferwallHistory::with('user')
                ->orderBy('created_at', 'desc')
                ->where('status', $status);
        }
        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('ip', 'like', "%{$search}%")
                  ->orWhere('txid', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  });
            });
        }

        $offerwallHistory = $query->paginate($perPage);

        $records = $offerwallHistory->map(function ($item) {
            return [
                'id' => $item->id,
                'ip' => $item->ip,
                'user_id' => $item->user_id,
                'offerwall' => ucfirst($item->name),
                'country' => $item->country,
                'username' => optional($item->user)->name,
                'status' => $this->getStatusLabel($item->status),
                'transaction' => $item->txid,
                'reward' => $item->reward*get_setting('currency_rate').' '.get_setting('currency_name'),
                'date' => $item->updated_at->format('Y-m-d H:i:s'),
            ];
        });

        return response()->json([
            'records' => $records,
            'current_page' => $offerwallHistory->currentPage(),
            'total_pages' => $offerwallHistory->lastPage(),
            'prev_page' => $offerwallHistory->previousPageUrl() ? $offerwallHistory->currentPage() - 1 : null,
            'next_page' => $offerwallHistory->nextPageUrl() ? $offerwallHistory->currentPage() + 1 : null,
        ]);
    }

    private function getFormattedBalance($status, $reward)
    {
        return match ($status) {
            0 => '<span class="flex items-center">
                    <i class="fa fa-clock text-xs mr-1 text-warning"></i> ' . balanceAndSymbol($reward) . '
                  </span>', // Pending
            1 => '<span class="flex items-center">
                    <i class="fa fa-plus text-xs mr-1 text-success"></i> ' . balanceAndSymbol($reward) . '
                  </span>', // Approved
            2 => '<span class="flex items-center">
                    <i class="fa fa-minus text-xs mr-1 text-error"></i> ' . balanceAndSymbol($reward) . '
                  </span>', // Rejected
            default => balanceAndSymbol($reward),
        };
    }
    private function getStatusLabel($status)
    {
        $statusLabels = [
            0 => ['text' => 'Pending', 'color' => 'warning'],
            1 => ['text' => 'Approved', 'color' => 'success'],
            2 => ['text' => 'Rejected', 'color' => 'error'],
        ];
    
        return $statusLabels[$status] ?? ['text' => 'Unknown', 'color' => 'secondary'];
    }
    public function updateStatus(Request $request)
    {
        $request->validate([
            'status' => 'required|integer|in:1,2',
            'id' => 'required|integer',
        ]);
        $id = $request->id;
        $status = $request->status;
        if ($status == 1) {
            return $this->approve($id);
        } else if ($status == 2) {
            return $this->reject($id);
        }
    }

    public function approve($id)
    {
        $offer = OfferwallHistory::findOrFail($id);

        if (!$offer) {
            return response()->json(['error' => 'Lead not found']);
        }

        if ($offer->status != 0) {
            return response()->json(['error' => 'Lead has already been processed.']);
        }
        $user = User::findOrFail($offer->user_id);
        if($user) {
            $user->earn($offer->reward);
        }
        $offer->update(['status' => 1]);
        return response()->json(['success' => true, 'message' => "Lead Approved. Sent: ".balanceAndSymbol($offer->reward)]);
    }

    public function reject($id)
    {
        $offer = OfferwallHistory::findOrFail($id);
        
        if (!$offer) {
            return response()->json(['error' => 'Lead not found']);
        }

        if ($offer->status != 0) {
            return response()->json(['error' => 'Lead has already been processed.']);
        }

        $offer->update(['status' => 2]);
        
        return response()->json(['success' => true, 'message' => "Lead rejected."]);
    }
}