<?php

namespace App\Http\Controllers\Dashboard;

use App\Models\DepositHistory;
use App\Models\DesawarRecord;
use App\Models\GameRecord;
use App\Models\Market;
use App\Models\MarketRecord;
use App\Models\StartLineRecord;
use App\Models\User;
use App\Models\WithdrawHistory;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\AppData;
use App\Models\DesawarMarket;
use App\Models\DesawarResult;
use App\Models\GameType;
use App\Models\MarketResult;
use App\Models\Notification;
use App\Models\StartLineMarket;
use App\Models\Transaction;
use App\Services\DesawarRecordChartService;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class DashboardController extends Controller
{
    public function clearData()
    {
        return 'redirect()->back()';
        
        //delete transaction history, withdrawal history, deposit history, market record, desawar record, starline record of all users
        DepositHistory::truncate();
        WithdrawHistory::truncate();
        Transaction::truncate();
        MarketRecord::truncate();
        DesawarRecord::truncate();
        StartLineRecord::truncate();
        DesawarResult::truncate();
        MarketResult::truncate();
        StartLineMarket::truncate();
        Notification::truncate();

        $appData = AppData::first();
        $appData->total_mannual_amount_added = 0;
        $appData->save();

        return back()->with('success', 'Data Has Been Cleared Successfully');
    }

    //construct fuction
    public function __construct()
    {
        new verify_payments();
    }
    private function getTodaySumOfAmounts()
    {
        // Get all markets
        $markets = DesawarMarket::all();

        $totalSum = 0;

        foreach ($markets as $market) {
            // Get open and close time for the market
            [$openTime, $closeTime] = DesawarRecordChartService::getTimeFrame($market);

            // Convert times to today's date
            $openDateTime = Carbon::today()->setTimeFromTimeString($openTime);
            $closeDateTime = Carbon::today()->setTimeFromTimeString($closeTime);

            // Fetch the sum of amounts for the records within the time frame
            $sum = DesawarRecord::where('desawar_market_id', $market->id)
                ->whereBetween('created_at', [$openDateTime, $closeDateTime])
                ->sum('amount');

            $totalSum += $sum;
        }

        return $totalSum;
    }

    public function index()
    {

        $today = Carbon::today();
        $markets = Market::count() + StartLineMarket::count() + DesawarMarket::count();
        $users = User::where('role', 'user')->count();
        $todayUsers = User::where('role', 'user')->whereDate('created_at', $today)->count();

        //  Today Game Amount
        $todayGameAmount = MarketRecord::whereDate('created_at', $today)->sum('amount') + StartLineRecord::whereDate('created_at', $today)->sum('amount') + $this->getTodaySumOfAmounts();

        // DesawarRecord::whereDate('created_at', $today)->sum('amount');

        //  Today Win Amount
        $todayWinAmount = MarketRecord::whereDate('created_at', $today)->where('status', 'success')->sum('win_amount')
            + StartLineRecord::whereDate('created_at', $today)->where('status', 'success')->sum('win_amount')
            + DesawarRecord::whereDate('created_at', $today)->where('status', 'success')->sum('win_amount');

        //  Deposit
        $deposit = DepositHistory::where('status', 'success')
            ->sum('amount');
        //  Today Deposit
        $todayDeposit = DepositHistory::whereDate('created_at', $today)
            ->where('status', 'success')
            ->sum('amount');
        //  WithDraw
        $withdraw = WithdrawHistory::where('status', 'success')
            ->sum('amount');
        //  Today Withdraw
        $todayWithdraw = WithdrawHistory::whereDate('created_at', $today)
            ->where('status', 'success')
            ->sum('amount');
        //Wallet Blance
        $walletBalance = User::where('role', 'user')->sum('balance');
        $gameType = Market::all();
        $appData = AppData::first();

        return view("dashboard.index", [
            'markets' => $markets,
            'users' => $users,
            'todayUsers' => $todayUsers,
            'todayGameAmount' => $todayGameAmount,
            'todayWinAmount' => $todayWinAmount,
            'deposit' => $deposit,
            'todayDeposit' => $todayDeposit,
            'withdraw' => $withdraw,
            'todayWithdraw' => $todayWithdraw,
            'walletBalance' => $walletBalance,
            'gameType' => $gameType,
            'appData' => $appData
        ]);
    }

    public function getBidsDetail(Request $request)
    {
        $request->validate([
            'game_id' => 'required',
            'market_time' => 'required'
        ]);
        $today = Carbon::today();
        $bids = MarketRecord::where(['market_id' => $request->game_id, 'game_type_id' => 1, 'session' => $request->market_time])->whereDate('created_at', $today)
            ->select(
                DB::raw('count(*) as ank_bids, SUM(amount) as ank_amount')
            )->groupBy('number')->orderBy('number', 'ASC')->get();
        return response()->json(['status' => 'success', 'bids' => $bids]);
    }
}
