<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\WithdrawHistory;
use Illuminate\Http\Request;

class FrontController extends Controller
{
    public function index(Request $request)
    {
        $page = 'Home';

        if ($request->has('ref')) {
            session(['referrer' => $request->query('ref')]);
        }
        $theme = get_setting('home_page');
        if($theme == 0) {
            $theme = '';
        }
        $registeredUsers = User::count();

        $totalEarned = User::sum('total_earned');

        $totalPayout = WithdrawHistory::where('status', 1)->sum('amountusd');

        return view("home$theme", compact(
            'page',
            'registeredUsers',
            'totalEarned',
            'totalPayout'
        ));
    }

    public function fetchHistory(Request $request)
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request']);
        }
        $perPage = 10;
        $query = WithdrawHistory::orderBy('updated_at', 'desc')->where('status', 1);
    
        $WithdrawHistory = $query->paginate($perPage);
    
        $records = $WithdrawHistory->map(function ($item) {
            return [
                'method' => $item->method_name,
                'address' => $this->maskAddress($item->wallet),
                'crypto' => cryptoAndSymbol($item->amount, $item->currency),
                'date' => $item->updated_at->diffForHumans(),
            ];
        });
    
        return response()->json([
            'records' => $records,
            'current_page' => $WithdrawHistory->currentPage(),
            'total_pages' => $WithdrawHistory->lastPage(),
            'prev_page' => $WithdrawHistory->previousPageUrl() ? $WithdrawHistory->currentPage() - 1 : null,
            'next_page' => $WithdrawHistory->nextPageUrl() ? $WithdrawHistory->currentPage() + 1 : null,
        ]);
    }
    private function maskAddress($address) {
        if (strlen($address) > 10) {
            return substr($address, 0, 4) . str_repeat('*', strlen($address) - 8) . substr($address, -4);
        }
        return str_repeat('*', strlen($address));
    }
}
