<?php

namespace App\Http\Controllers\Agent;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function index(Request $request)
    {
        if ($request->has('searchValue')) {
            $searchValue = $request->searchValue;
            $users = User::withCount('withdrawHistory')
                ->withSum('marketRecords as total_market_game_amount', 'amount')
                ->withSum('startLineRecords as total_startLine_game_amount', 'amount')
                ->withSum('desawarRecords as total_desawar_game_amount', 'amount')
                ->withSum('marketRecords as total_market_win_amount', 'win_amount')
                ->withSum('startLineRecords as total_startline_win_amount', 'win_amount')
                ->withSum('desawarRecords as total_desawar_win_amount', 'win_amount')
                ->withSum(['withdrawHistory as total_withdraw_success_amount' => function ($query) {
                    $query->where('status', 'success');
                }], 'amount')
                ->where('role', 'user')
                ->where('user_id', auth()->id())
                ->where(function ($query) use ($searchValue) {
                    $query->where('name', 'LIKE', '%' . $searchValue . '%')
                        ->orWhere('phone', 'LIKE', '%' . $searchValue . '%');
                })->latest()->paginate(250);
            return view('agent.users.index', compact('users', 'searchValue'));
        }

        $users = User::withCount('withdrawHistory')
            ->withSum('marketRecords as total_market_game_amount', 'amount')
            ->withSum('startLineRecords as total_startLine_game_amount', 'amount')
            ->withSum('desawarRecords as total_desawar_game_amount', 'amount')
            ->withSum('marketRecords as total_market_win_amount', 'win_amount')
            ->withSum('startLineRecords as total_startline_win_amount', 'win_amount')
            ->withSum('desawarRecords as total_desawar_win_amount', 'win_amount')
            ->withSum(['withdrawHistory as total_withdraw_success_amount' => function ($query) {
                $query->where('status', 'success');
            }], 'amount')
            ->where('role', 'user')
            ->where('user_id', auth()->id())
            ->latest()->paginate(25);
        return view("agent.users.index", [
            'users' => $users
        ]);
    }
}
