<?php

namespace App\Http\Controllers\Admin;

# Models
use App\Models\Day;
use App\Models\SingleDigitBit;
use App\Models\SinglePannaBit;
use App\Models\DoublePannaBit;
use App\Models\TripplePannaBit;
use App\Models\SinglePattiBit;
use App\Models\DoublePattiBit;
use App\Models\TriplePattiBit;
use App\Models\JodiBit;
use App\Models\HalfSangamBit;
use App\Models\FullSangamBit;
use App\Models\JodiFamilyBit;
use App\Models\RedJodiBit;
use App\Models\RedFamilyJodiBit;
use App\Models\CyclePattiiBit;
use App\Models\PannaFamilyBit;
use App\Models\Bit;
use App\Models\NewBit;
use App\User;
use App\Models\Game;
use App\Models\Store;
use App\Models\NewStore;
use App\Models\GameGroup;
use App\Models\StoreGame;
use App\Models\Payment;
use App\Models\PaymentHistory;
use App\Models\PaymentNewHistory;
use App\Models\DebitPayment;
use App\Models\GameWinner;
use App\Models\UserWinnersAmount;

# Other Classes
use DB;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Traits\FirebaseTraits;
use Auth;
use App\Exports\ExportPlayedOpen;
use App\Exports\ExportPlayedClose;
use App\Traits\EditTrait;


class StoresGameScheduleController extends Controller
{
  use FirebaseTraits;
  use EditTrait;
  # Define Base view
  protected $view = 'admin.stores-game.';

  #Bind GameGroup model
  protected $gameGroup;

  #Bind SinglePannaBit model
  protected $singlePannaBit;

  #Bind StoreGame model
  protected $storeGame;

  #Bind Game model
  protected $game;

  #Bind Store model
  protected $store;

  #Bind Day model
  protected $day;

  #Bind Bit model
  protected $bit;

  #Bind JodiBit model
  protected $jodiBit;

  #Bind Payment model
  protected $payment;


  #Bind PaymentHistory model
  protected $paymentHistory;

  #Bind DebitPayment model
  protected $debitPayment;


  #Bind DebitPayment model
  protected $gameWinner;

  #Bind UserWinnersAmount model
  protected $userWinnersAmount;

  /**
   * Defining the default constructor for controller
   *
   */
  public function __construct(
    GameGroup $gameGroup,
    GameWinner $gameWinner,
    SinglePannaBit $singlePannaBit,
    StoreGame $storeGame,
    Store $store,
    NewStore $newstore,
    Game $game,
    Day $day,
    JodiBit $jodiBit,
    NewBit $newBit,
    User $user,
    Payment $payment,
    PaymentHistory $paymentHistory,
    UserWinnersAmount $userWinnersAmount,
    PaymentNewHistory $paymentNewHistory,
    DebitPayment $debitPayment,
    Bit $bit


  ) {
    $this->singlePannaBit  = $singlePannaBit;
    $this->gameWinner  = $gameWinner;
    $this->gameGroup  = $gameGroup;
    $this->game       = $game;
    $this->store      = $store;
    $this->user               = $user;
    $this->day        = $day;
    $this->bit        = $bit;
    $this->newBit     = $newBit;
    $this->storeGame  = $storeGame;
    $this->newstore  = $newstore;
    $this->jodiBit    = $jodiBit;
    $this->paymentNewHistory  = $paymentNewHistory;
    $this->payment            = $payment;
    $this->paymentHistory     = $paymentHistory;
    $this->debitPayment       = $debitPayment;
    $this->userWinnersAmount       = $userWinnersAmount;
  }
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    try {

      $input = $request->all();
      $relation = ['storesDayGame'];
      #get all paymentUser resources
      $stores = $this->store->with($relation)->where('created_at', '!=', null);

      $search_name = '';
      $search_status = '';
      if (isset($input['search_name']) || isset($input['search_status'])) {
        $search_name = $input['search_name'];
        $search_status = $input['search_status'];
        if (isset($search_name) && $search_name != null) {
          $day->where('name', 'LIKE', '%' . $search_name . '%');
        }
        if ($search_status != null && $search_status == 1) {
          $day->where('status', $search_status);
        } else if ($search_status != null && $search_status == 0) {
          $day->where('status', $search_status);
        }
      }
      $details['lists'] = $stores->paginate(15);
      
    //   return $details['lists'];

      #render view
      return view($this->view . 'index', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }


  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function playedGame(Request $request)
  {

    try {

      $input = $request->all();

$relation = ['storesDay'];
$stores = $this->store->with($relation);

// 🔍 Search filters
if (!empty($input['search_name'])) {
    $stores->where('name', 'LIKE', '%' . $input['search_name'] . '%');
}

if (isset($input['search_status'])) {
    $stores->where('status', $input['search_status']);
}

$details['lists'] = $stores->paginate(15);

// 📅 today date
$today = currentDate(); // example: 2025-12-20

$details['total_bid_amount'] = 0;
$details['total_win_amount'] = 0;
$details['total_profit_amount'] = 0;

foreach ($details['lists'] as $store) {

    $store->bid_amount = $this->bit
        ->where('stores_id', $store->id)
        ->whereDate('created_at', $today)   // ✅ FIXED
        ->sum('amount');

    $store->win_amount = $this->userWinnersAmount
        ->where('stores_id', $store->id)
        ->whereDate('created_at', $today)   // ✅ FIXED
        ->sum('amount');
        
        $details['total_bid_amount'] += $store->bid_amount;
        $details['total_win_amount'] += $store->win_amount;
        $details['total_profit_amount'] += $store->bid_amount - $store->win_amount;
}



      #render view
      return view('admin.played-game.index', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }

  public function storePlay(Request $request, $id)
  {

    try {

      $input = $request->all();
      $realtion = ['username', 'game'];
      $details['lists'] = $this->bit->where('created_at', 'like', currentDate() . '%')->with($realtion)->where('stores_id', $id)->paginate(150);

      $details['storess'] = $this->store->whereId($id)->first();
      $details['totalamount'] = $this->bit->where('created_at', 'like', currentDate() . '%')->where('stores_id', $id)->sum('amount');
      #render view
      return view($this->view . 'playedgame', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }
 public function storePlayOpen(Request $request, $id)
  {


    // try {

    $dateFilter = isset($request->date) ? dateYYYYMMDD($request->date) : currentDate();

    $input = $request->all();
    // $relation = ['bit'=> function($query) use($id){
    //           $query->where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('type','=','open');}];
    $gamess = $this->game->where('status', 1);

    if($request->session == 'close'){
     $gamess= $gamess->whereNotIn('id', [2, 10, 11, 12, 13]);
    }

    $gamess = $gamess->orderBy('id', 'asc')->get();

    $data = array();
    $datanew = array();
    $i = 0;

    $relationgame = ['username'];
    foreach ($gamess as $key) {
      $result = '';
      $data[$i]['name'] = $key->name;
      $data[$i]['id'] = $key->id;
      $bsss = $this->bit->where('created_at', 'like', $dateFilter . '%')->where('stores_id', $id);
      if (isset($input['search_user'])) {

        if (isset($input['search_user'])) {

          $bsss->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
        }
      }
      $data[$i]['amount'] = $bsss->where('game_id', $key->id)->where('type', '=', $request->session)->sum('amount');


      $bitaa =  $this->bit->where('created_at', 'like', $dateFilter . '%')->where('stores_id', $id)->where('type', '=', $request->session);
      if (isset($input['search_user'])) {

        if (isset($input['search_user'])) {

          $bitaa->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
        }
      }
      $bitaata = $bitaa->where('game_id', $key->id)->pluck('id');
      if ($key->id == 1) {
            $table = (new SingleDigitBit)->getTable();

            $result = SingleDigitBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
      $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 2) {
        
            $table = (new JodiBit)->getTable();

            $result = JodiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
      $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 3) {

     
            $table = (new SinglePattiBit)->getTable();

            $result = SinglePattiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
      $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 4) {


     
            $table = (new DoublePattiBit)->getTable();

            $result = DoublePattiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
      $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 5) {

     
            $table = (new SinglePannaBit)->getTable();

            $result = SinglePannaBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 6) {

            $table = (new DoublePannaBit)->getTable();

            $result = DoublePannaBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 7) {

            $table = (new TripplePannaBit)->getTable();

            $result = TripplePannaBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 8) {

            $table = (new TriplePattiBit)->getTable();

            $result = TriplePattiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 9) {
        //   dd($key->id);
            $table = (new HalfSangamBit)->getTable();

            $result = HalfSangamBit::select(
                    "$table.id",
                    "$table.bit_place_panna",
                    "$table.bit_place_single",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place_panna",
                    "$table.bit_place_single",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place_panna")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 10) {
        //   dd($key->id);
            $table = (new FullSangamBit)->getTable();

            $result = FullSangamBit::select(
                    "$table.id",
                    "$table.bit_place_panna",
                    "$table.bit_place_single",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place_panna",
                    "$table.bit_place_single",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place_panna")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 11) {

            $table = (new JodiFamilyBit)->getTable();

            $result = JodiFamilyBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 12) {

            $table = (new RedJodiBit)->getTable();

            $result = RedJodiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 13) {

            $table = (new RedFamilyJodiBit)->getTable();

            $result = RedFamilyJodiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 14) {

            $table = (new CyclePattiiBit)->getTable();

            $result = CyclePattiiBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      if ($key->id == 15) {

            $table = (new PannaFamilyBit)->getTable();

            $result = PannaFamilyBit::select(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id",
                    \DB::raw("SUM($table.amount - ($table.amount * users.commission / 100)) as total_val"),
                    \DB::raw("SUM($table.amount) as total_val_per")
                )
                ->join('users', 'users.id', '=', "$table.user_id")
                ->where("$table.created_at", 'like', $dateFilter . '%')
                ->whereIn("$table.bit_id", $bitaata)
                ->groupBy(
                    "$table.id",
                    "$table.bit_place",
                    "$table.user_id",
                    "$table.bit_id"
                )
                ->orderBy("$table.bit_place")
                ->get();
        $data[$i]['amount'] = $result->sum('total_val');
      }
      $datanew[$key->id] = $result;

      $i++;
    }

    $details['game'] = $data;
    $details['result'] = $datanew;

    $details['storess'] = $this->store->whereId($id)->first();
    $totot = $this->bit->where('created_at', 'like', $dateFilter . '%')->where('type', '=', $request->session);
    if (isset($input['search_user'])) {

      if (isset($input['search_user'])) {

        $totot->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
      }
    }
    $details['totalamount'] =  $totot->where('stores_id', $id)->sum('amount');

    $details['customerss'] = User::where('status', 1)->where('type', 'customer')->get();

    $details['type'] = $request->session;

    $details['date'] = $dateFilter;

    if (isset($request->type)) {
      if ($request->type == 'excel') {
        return Excel::download(new ExportPlayedOpen($details), 'playedopen.xlsx');
      }

      if ($request->type == 'share') {

        $html = view('played-text', compact('details'))->render();

        $html = str_replace(['<br>', '<br/>', '<br />'], "\n", $html);
        $text = strip_tags($html);
        $text = preg_replace("/\n\s*\n/", "\n", $text);
        $text = preg_replace("/[ \t]+/", " ", $text);
        $text = trim($text);

        // Encode for WhatsApp
        $encoded = urlencode($text);

        // Redirect to WhatsApp
        return redirect("https://wa.me/?text={$encoded}");
      }
    }

    #render view
    return view('admin.played-game.open', $details);
    // } catch (\Exception $ex) {
    //   return back()->with('error', $ex->getMessage());
    // }
  }


  public function storePlayClose(Request $request, $id)
  {

    try {
        
        $dateFilter = isset($request->date) ? dateYYYYMMDD($request->date) : currentDate();

      $input = $request->all();
      // $relation = ['bit'=> function($query) use($id){
      //           $query->where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('type','=','open');}];
      $gamess = $this->game->whereNotIn('id', [2, 10, 11, 12, 13])->where('status', 1)->orderBy('id', 'asc')->get();
      $data = array();
      $datanew = array();
      $i = 0;

      $relationgame = ['username'];
      foreach ($gamess as $key) {
        $result = '';
        $data[$i]['name'] = $key->name;
        $data[$i]['id'] = $key->id;
        $bsss = $this->bit->where('created_at', 'like', $dateFilter . '%')->where('stores_id', $id);
        if (isset($input['search_user'])) {

          if (isset($input['search_user'])) {

            $bsss->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
          }
        }
        $data[$i]['amount'] = $bsss->where('game_id', $key->id)->where('type', '=', 'close')->sum('amount');

        $bitaa =  $this->bit->where('created_at', 'like', $dateFilter . '%')->where('stores_id', $id)->where('type', '=', 'close');
        if (isset($input['search_user'])) {

          if (isset($input['search_user'])) {

            $bitaa->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
          }
        }
        $bitaata = $bitaa->where('game_id', $key->id)->pluck('id');
        if ($key->id == 1) {
          $result = SingleDigitBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 2) {
          $result = JodiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 3) {

          $result = SinglePattiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 4) {

          $result = DoublePattiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 5) {

          $result = SinglePannaBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 6) {

          $result = DoublePannaBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 7) {

          $result = TripplePannaBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 8) {

          $result = TriplePattiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 9) {
          //   dd($key->id);
          $result = HalfSangamBit::with($relationgame)->select(
            'id',
            'bit_place_panna',
            'bit_place_single',
            'user_id',
            'bit_id',
            \DB::raw('SUM(amount) as total_val')
          )
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place_panna', 'bit_place_single', 'user_id', 'bit_id')
            ->orderBy('bit_place_panna')
            ->get();
        }
        if ($key->id == 10) {
          //   dd($key->id);
          $result = FullSangamBit::with($relationgame)->select(
            'id',
            'bit_place_panna',
            'bit_place_single',
            'user_id',
            'bit_id',
            \DB::raw('SUM(amount) as total_val')
          )
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place_panna', 'bit_place_single', 'user_id', 'bit_id')
            ->orderBy('bit_place_panna')
            ->get();
        }
        if ($key->id == 11) {

          $result = JodiFamilyBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 12) {

          $result = RedJodiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 13) {

          $result = RedFamilyJodiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 14) {

          $result = CyclePattiiBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        if ($key->id == 15) {

          $result = PannaFamilyBit::with($relationgame)->select('id', 'bit_place', 'user_id', 'bit_id', \DB::raw('SUM(amount) as total_val'))
            ->whereIn('bit_id', $bitaata)
            ->groupBy('id', 'bit_place', 'user_id', 'bit_id')
            ->orderBy('bit_place')
            ->get();
        }
        $datanew[$key->id] = $result;

        $i++;
      }

      $details['game'] = $data;
      $details['result'] = $datanew;

      $details['storess'] = $this->store->whereId($id)->first();
      $totot = $this->bit->where('created_at', 'like', $dateFilter . '%')->where('type', '=', 'close');
      if (isset($input['search_user'])) {

        if (isset($input['search_user'])) {

          $totot->where('user_id', 'LIKE', '%' . $input['search_user'] . '%');
        }
      }
      $details['totalamount'] =  $totot->where('stores_id', $id)->sum('amount');

      $details['customerss'] = User::where('status', 1)->where('type', 'customer')->get();

      $details['type'] = 'close';
      
    $details['date'] = $dateFilter;

      if (isset($request->type)) {
        if ($request->type == 'excel') {
          return Excel::download(new ExportPlayedOpen($details), 'playedclose.xlsx');
        }
        
         if ($request->type == 'share') {

    $html = view('played-text', compact('details'))->render();

    $html = str_replace(['<br>', '<br/>', '<br />'], "\n", $html);
    $text = strip_tags($html);
    $text = preg_replace("/\n\s*\n/", "\n", $text);
    $text = preg_replace("/[ \t]+/", " ", $text);
    $text = trim($text);

    // Encode for WhatsApp
    $encoded = urlencode($text);

    // Redirect to WhatsApp
    return redirect("https://wa.me/?text={$encoded}");
}
      }
      #render view
      return view('admin.played-game.open', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    try {
      $details['store'] = $this->store->get();
      $details['gameGroup'] = $this->gameGroup->get();
      $details['game']      = $this->game->get();
      $details['day'] = $this->day->get();
      #render view
      return view($this->view . 'create', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {

    try {
      #validate the request

      $validate = Validator::make($request->all(), [
        'stores_id'          => 'required',
        'opent_time'          => 'required',
        'close_time'          => 'required',
      ]);
      if ($validate->fails()) {

        return redirect()->back()->withErrors($validate);
      }


      if ($request->sort_order) {
        $sortCheck = $this->store->where('sort_order', $request->sort_order)->first();
        if (isset($sortCheck)) {
          $sortCheck->sort_order = null;
          $sortCheck->save();
        }
      }

      #update data
      $data = [
        'name'       => $request->stores_id,
        'link'       => $request->link,
        'email'      => 'test@gmail.com',
        'mobile'     => 9898989898,
        'user_id'    => Auth::user()->id,
        'sort_order'    => $request->sort_order,
      ];
      #store the newly creted resoures
      $storesid = $this->store->create($data);



      $day = $this->day->get();
      foreach ($day as $key => $value) {
        #get the requested data in Data variable

        $data = [
          'stores_id'        => $storesid->id,
          'stores_day_id'    => $value->id,
          'opent_time'       => $request->opent_time,
          'close_time'       => $request->close_time,
          'user_id'          => Auth::user()->id,
        ];
        #store the newly creted resoures
        $this->storeGame->create($data);
      }





      // #return redirect back to view
      toastr()->success('Store Create Sucess fully ...');
      return redirect('/admin/stores-game-schedule');
    } catch (\Exception $ex) {
      toastr()->success($ex->getMessage());
      return back()->with('error', $ex->getMessage());
    }
  }

  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function show($id)
  {
    //
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    try {
      $details['day'] = $this->day->get();
      $relation = ['storesDay'];
      $details['detail'] = $this->store->with($relation)->whereId($id)->first();
      $details['dayid'] =  $this->storeGame->where('stores_id', $id)->where('status', 1)->pluck('stores_day_id')->all();


      #render view
      return view($this->view . 'edit', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {


    try {
      #validate the request

      $validate = Validator::make($request->all(), [
        'stores_id'          => 'required',
        'opent_time'          => 'required',
        'close_time'          => 'required',
      ]);
      if ($validate->fails()) {

        return redirect()->back()->withErrors($validate);
      }

      $store = $this->store->where('id', $id)->first();

      if ($request->sort_order) {
        $sortCheck = $this->store->where('sort_order', $request->sort_order)->first();
        if (isset($sortCheck)) {
          $sortCheck->sort_order = $store->sort_order;
          $sortCheck->save();
        }
      }



      #update data
      $data = [
        'name'       => $request->stores_id,
        'link'       => $request->link,
        'email'      => 'test@gmail.com',
        'mobile'     => 9898989898,
        'user_id'    => Auth::user()->id,
        'sort_order'    => $request->sort_order,
      ];
      #store the newly creted resoures
      $storesid = $this->store->whereId($id)->update($data);

      $day = $this->day->get();
      $ddd =   $data = [

        'status'           => '0',
      ];
      $this->storeGame->where('stores_id', $id)->update($ddd);
      foreach ($day as $key => $value) {
        #get the requested data in Data variable

        $data = [
          'stores_id'        => $id,
          'stores_day_id'    => $value->id,
          'opent_time'       => $request->opent_time,
          'close_time'       => $request->close_time,
          'user_id'          => Auth::user()->id,
          'status'           => '1',
        ];
        #store the newly creted resoures
        $check =  $this->storeGame->where('stores_day_id', $value->id)->where('stores_id', $id)->first();
        if ($check) {
          $this->storeGame->whereId($check->id)->update($data);
        } else {
          $this->storeGame->create($data);
        }
      }


      // #return redirect back to view
      toastr()->success('Store Create Sucess fully ...');
      return redirect('/admin/stores-game-schedule');
    } catch (\Exception $ex) {
      toastr()->success($ex->getMessage());
      return back()->with('error', $ex->getMessage());
    }
  }
  
  
  public function updateStoreGame(Request $request, $id)
        {
            try {
        
                $validate = Validator::make($request->all(), [
                    'opent_time' => 'required',
                    'close_time' => 'required',
                ]);
        
                if ($validate->fails()) {
                    return redirect()->back()->withErrors($validate);
                }
        
                // FIND BY storeGame ID
                $storeGame = $this->storeGame->where('id', $id)->first();
        
                if (!$storeGame) {
                    return back()->with('error', 'Record not found');
                }
        
                $storeGame->update([
                    'opent_time' => $request->opent_time,
                    'close_time' => $request->close_time,
                    'status'     => $request->status ?? $storeGame->status,
                    'user_id'    => Auth::user()->id,
                ]);
        
                toastr()->success('Store Game updated successfully');
                return redirect()->back();
        
            } catch (\Exception $ex) {
        
                toastr()->error($ex->getMessage());
                return back()->with('error', $ex->getMessage());
            }
        }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    $caste = Store::find($id);
    $caste->delete();
    toastr()->success('You are successfully Deleted');
    return redirect('admin/stores-game-schedule');
  }
  /**
   * Get Sore Wise game Group .
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function StoreGameGroup(Request $request)
  {
    $game_group_id = $this->storeGame->where('stores_id', $request->store_id)->groupBy('game_group_id')->pluck('game_group_id');
    $data = $this->gameGroup->whereIn('id', $game_group_id)->get();

    return view($this->view . 'option', compact('data'));
  }
  /**
   * Get Sore Wise game Group .
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function GroupGame(Request $request)
  {

    $data = $this->game->where('game_group_id', $request->game_group_id)->get();

    return view($this->view . 'option', compact('data'));
  }

  /**
   * Get Group Wise game Group .
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function GroupGameSchedule(Request $request)
  {

    $data = $this->game->where('game_group_id', $request->game_group_id)->get();

    return view($this->view . 'option', compact('data'));
  }


  /**
   * Get Store Wise Open Time .
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function storeOpen(Request $request)
  {

    $data = $this->storeGame->select('stores_game.opent_time  as time')->where('stores_id', $request->store_id)->where('game_group_id', $request->game_group_id)->where('game_id', $request->game_id)->where('stores_day_id', $request->day_id)->get();


    return view($this->view . 'option_time', compact('data'));
  }


  /**
   * Get Store Wise Close Time .
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function storeClose(Request $request)
  {

    $data = $this->storeGame->select('stores_game.close_time  as time')->where('stores_id', $request->store_id)->where('game_group_id', $request->game_group_id)->where('game_id', $request->game_id)->where('stores_day_id', $request->day_id)->get();

    return view($this->view . 'option_time', compact('data'));
  }

  public function betCheck($bet_id) {}

  public function editBet(Request $request)
  {

    // return $request->all();
    // try{

    DB::beginTransaction();
    //   return $request->all();

    $bet = $this->bit->where('id', $request->bit_id)->first();

    $storess = $this->store->whereId($bet->stores_id)->first();

    $result = $this->gameWinner->where('stores_id', $bet->stores_id)->where('date', currentDate())->first();



    $singledigitopen = '';
    $singledigitclose = '';
    $jodi = '';
    $pannaopen = '';
    $pannaclose = '';

    if ($result) {
      if ($result->open_time) {
        $resultopen = (str_replace('-', '', $result->open_time));
        $singledigitopen = $resultopen[3];
        $pannaopen = $resultopen[0] . $resultopen[1] . $resultopen[2];
      }

      if ($result->close_time) {
        $resultclose = (str_replace('-', '', $result->close_time));
        $singledigitclose = $resultclose[0];
        $pannaclose = $resultclose[1] . $resultclose[2] . $resultclose[3];
      }

      if ($singledigitopen != '' && $singledigitclose != '') {
        $jodi = $singledigitopen . $singledigitclose;
      }
    }



    $store_id = '';
    $user_id = '';
    $amount = '';
    if ($request->game_id == 1) {
      $checkBet = SingleDigitBit::where('id', $request->id)->first();

      $changedbet = null;

      $resultCheck = UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->first();

      if ($resultCheck) {
        debitAmount($resultCheck->user_id, $resultCheck->amount);
        PaymentNewHistory::where('id', $resultCheck->win_pay_id)->delete();
        UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->delete();
      }

      $duplicateBet = SingleDigitBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();



      if ($duplicateBet) {

        $resultDuplicate = UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->first();

        if ($resultDuplicate) {
          debitAmount($resultDuplicate->user_id, $resultDuplicate->amount);
          PaymentNewHistory::where('id', $resultDuplicate->win_pay_id)->delete();
          UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->delete();
        }

        $totalAmount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->amount = $totalAmount;
        $duplicateBet->save();
        $changedbet = $duplicateBet;


        $remark = "Played {$storess->name} {$bet->type} single digit {$request->bit_place} of amount {$totalAmount}";

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $totalAmount,
          $duplicateBet->payment_new_history_id
        );

        PaymentNewHistory::where('id', $checkBet->payment_new_history_id)->delete();
        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
        $changedbet = $checkBet;


        $remark = "Played {$storess->name} {$bet->type} single digit {$request->bit_place} of amount {$checkBet->amount}";

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $checkBet->amount,
          $checkBet->payment_new_history_id
        );
      }

      if ($request->type == 'open' && $request->bit_place == $singledigitopen) {
        $this->SingleDigitOpen($storess->id, $request->bit_place, $result->id, $changedbet);
      }
      if ($request->type == 'close' && $request->bit_place == $singledigitclose) {
        $this->SingleDigitClose($storess->id, $request->bit_place, $result->id, $changedbet);
      }
    }
    if ($request->game_id == 2) {

      $checkBet = JodiBit::where('id', $request->id)->first();

      $changedbet = null;

      $resultCheck = UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->first();

      if ($resultCheck) {
        debitAmount($resultCheck->user_id, $resultCheck->amount);
        PaymentNewHistory::where('id', $resultCheck->win_pay_id)->delete();
        UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->delete();
      }

      $duplicateBet = JodiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();



      if ($duplicateBet) {

        $resultDuplicate = UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->first();

        if ($resultDuplicate) {
          debitAmount($resultDuplicate->user_id, $resultDuplicate->amount);
          PaymentNewHistory::where('id', $resultDuplicate->win_pay_id)->delete();
          UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->delete();
        }

        $totalAmount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->amount = $totalAmount;
        $duplicateBet->save();
        $changedbet = $duplicateBet;


        $remark =  'Played ' . $storess->name . ' Jodi ' . $request->bit_place . ' of amount ' . $totalAmount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $totalAmount,
          $duplicateBet->payment_new_history_id
        );

        PaymentNewHistory::where('id', $checkBet->payment_new_history_id)->delete();
        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
        $changedbet = $checkBet;


        $remark =  'Played ' . $storess->name . ' Jodi ' . $request->bit_place . ' of amount ' . $checkBet->amount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $checkBet->amount,
          $checkBet->payment_new_history_id
        );
      }


      if ($request->bit_place == $jodi) {
        $this->JodiClose($storess->id, $request->bit_place, $result->id, $changedbet);
      }
    }
    if ($request->game_id == 3) {

      $checkBet = SinglePattiBit::where('id', $request->id)->first();

      $duplicateBet = SinglePattiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 4) {

      $checkBet = DoublePattiBit::where('id', $request->id)->first();

      $duplicateBet = DoublePattiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 5) {

      $checkBet = SinglePannaBit::where('id', $request->id)->first();

      $changedbet = null;

      $resultCheck = UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->first();

      if ($resultCheck) {
        debitAmount($resultCheck->user_id, $resultCheck->amount);
        PaymentNewHistory::where('id', $resultCheck->win_pay_id)->delete();
        UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->delete();
      }

      $duplicateBet = SinglePannaBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();



      if ($duplicateBet) {

        $resultDuplicate = UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->first();

        if ($resultDuplicate) {
          debitAmount($resultDuplicate->user_id, $resultDuplicate->amount);
          PaymentNewHistory::where('id', $resultDuplicate->win_pay_id)->delete();
          UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->delete();
        }

        $totalAmount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->amount = $totalAmount;
        $duplicateBet->save();
        $changedbet = $duplicateBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' single panna ' . $request->bit_place . ' of amount ' . $totalAmount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $totalAmount,
          $duplicateBet->payment_new_history_id
        );

        PaymentNewHistory::where('id', $checkBet->payment_new_history_id)->delete();
        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
        $changedbet = $checkBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' single panna ' . $request->bit_place . ' of amount ' . $checkBet->amount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $checkBet->amount,
          $checkBet->payment_new_history_id
        );
      }

      if ($request->type == 'open' && $request->bit_place == $pannaopen) {
        $this->SinglePannaOpen($storess->id, $request->bit_place, $result->id, $changedbet);
      }
      if ($request->type == 'close' && $request->bit_place == $pannaclose) {
        $this->SinglePannaClose($storess->id, $request->bit_place, $result->id, $changedbet);
      }
    }
    if ($request->game_id == 6) {

      $checkBet = DoublePannaBit::where('id', $request->id)->first();

      $changedbet = null;

      $resultCheck = UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->first();

      if ($resultCheck) {
        debitAmount($resultCheck->user_id, $resultCheck->amount);
        PaymentNewHistory::where('id', $resultCheck->win_pay_id)->delete();
        UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->delete();
      }

      $duplicateBet = DoublePannaBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();



      if ($duplicateBet) {

        $resultDuplicate = UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->first();

        if ($resultDuplicate) {
          debitAmount($resultDuplicate->user_id, $resultDuplicate->amount);
          PaymentNewHistory::where('id', $resultDuplicate->win_pay_id)->delete();
          UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->delete();
        }

        $totalAmount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->amount = $totalAmount;
        $duplicateBet->save();
        $changedbet = $duplicateBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' double panna ' . $request->bit_place . ' of amount ' . $totalAmount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $totalAmount,
          $duplicateBet->payment_new_history_id
        );

        PaymentNewHistory::where('id', $checkBet->payment_new_history_id)->delete();
        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
        $changedbet = $checkBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' double panna ' . $request->bit_place . ' of amount ' . $checkBet->amount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $checkBet->amount,
          $checkBet->payment_new_history_id
        );
      }

      if ($request->type == 'open' && $request->bit_place == $pannaopen) {
        $this->DoublePannaOpen($storess->id, $request->bit_place, $result->id, $changedbet);
      }
      if ($request->type == 'close' && $request->bit_place == $pannaclose) {
        $this->DoublePannaClose($storess->id, $request->bit_place, $result->id, $changedbet);
      }
    }
    if ($request->game_id == 7) {

      $checkBet = TripplePannaBit::where('id', $request->id)->first();

      $changedbet = null;

      $resultCheck = UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->first();

      if ($resultCheck) {
        debitAmount($resultCheck->user_id, $resultCheck->amount);
        PaymentNewHistory::where('id', $resultCheck->win_pay_id)->delete();
        UserWinnersAmount::where('payment_new_history_id', $checkBet->payment_new_history_id)->delete();
      }

      $duplicateBet = TripplePannaBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();



      if ($duplicateBet) {

        $resultDuplicate = UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->first();

        if ($resultDuplicate) {
          debitAmount($resultDuplicate->user_id, $resultDuplicate->amount);
          PaymentNewHistory::where('id', $resultDuplicate->win_pay_id)->delete();
          UserWinnersAmount::where('payment_new_history_id', $duplicateBet->payment_new_history_id)->delete();
        }

        $totalAmount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->amount = $totalAmount;
        $duplicateBet->save();
        $changedbet = $duplicateBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' triple panna ' . $request->bit_place . ' of amount ' . $totalAmount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $totalAmount,
          $duplicateBet->payment_new_history_id
        );

        PaymentNewHistory::where('id', $checkBet->payment_new_history_id)->delete();
        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
        $changedbet = $checkBet;



        $remark =  'Played ' . $storess->name . ' ' . $bet->type . ' triple panna ' . $request->bit_place . ' of amount ' . $checkBet->amount;

        $paymentremark = PaymentRemark(
          Auth::user()->id,
          $remark,
          $checkBet->amount,
          $checkBet->payment_new_history_id
        );
      }

      if ($request->type == 'open' && $request->bit_place == $pannaopen) {
        $this->TripplePannaOpen($storess->id, $request->bit_place, $result->id, $changedbet);
      }
      if ($request->type == 'close' && $request->bit_place == $pannaclose) {
        $this->TripplePannaClose($storess->id, $request->bit_place, $result->id, $changedbet);
      }
    }
    if ($request->game_id == 8) {

      $checkBet = TriplePattiBit::where('id', $request->id)->first();

      $duplicateBet = TriplePattiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 9) {

      $checkBet = HalfSangamBit::where('id', $request->id)->first();



      $duplicateBet = HalfSangamBit::where('bit_place_panna', $request->bit_place_panna)->where('bit_place_single', $request->bit_place_single)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place_panna = $request->bit_place_panna;
        $checkBet->bit_place_single = $request->bit_place_single;
        $checkBet->save();
      }
    }
    if ($request->game_id == 10) {

      $checkBet = FullSangamBit::where('id', $request->id)->first();

      $duplicateBet = FullSangamBit::where('bit_place_panna', $request->bit_place_panna)->where('bit_place_single', $request->bit_place_single)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place_panna = $request->bit_place_panna;
        $checkBet->bit_place_single = $request->bit_place_single;
        $checkBet->save();
      }
    }
    if ($request->game_id == 11) {

      $checkBet = JodiFamilyBit::where('id', $request->id)->first();


      $duplicateBet = JodiFamilyBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 12) {

      $checkBet = RedJodiBit::where('id', $request->id)->first();

      $duplicateBet = RedJodiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 13) {

      $checkBet = RedFamilyJodiBit::where('id', $request->id)->first();

      $duplicateBet = RedFamilyJodiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 14) {

      $checkBet = CyclePattiiBit::where('id', $request->id)->first();

      $duplicateBet = CyclePattiiBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }
    if ($request->game_id == 15) {

      $checkBet = PannaFamilyBit::where('id', $request->id)->first();

      $duplicateBet = PannaFamilyBit::where('bit_place', $request->bit_place)->where('user_id', $checkBet->user_id)->where('bit_id', $checkBet->bit_id)->first();

      if ($duplicateBet) {
        $duplicateBet->amount = $duplicateBet->amount + $checkBet->amount;
        $duplicateBet->save();

        $checkBet->delete();
      } else {
        $checkBet->bit_place = $request->bit_place;
        $checkBet->save();
      }
    }




    DB::commit();
    return back();
    // } catch (\Exception $ex) {
    //     DB::rollback();
    //     toastr()->success($ex->getMessage());
    //     return back()->with('error', $ex->getMessage());
    //   }
  }


  public function deleteBet(Request $request)
  {

    try {

      DB::beginTransaction();



      $store_id = '';
      $user_id = '';
      $amount = '';
      if ($request->game_id == 1) {
        $checkBet = SingleDigitBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;

        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        SingleDigitBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 2) {

        $checkBet = JodiBit::where('id', $request->id)->first();

        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        JodiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 3) {

        $checkBet = SinglePattiBit::where('id', $request->id)->first();

        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        SinglePattiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 4) {

        $checkBet = DoublePattiBit::where('id', $request->id)->first();

        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        DoublePattiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 5) {

        $checkBet = SinglePannaBit::where('id', $request->id)->first();

        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        SinglePannaBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 6) {

        $checkBet = DoublePannaBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        DoublePannaBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 7) {

        $checkBet = TripplePannaBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        TripplePannaBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 8) {

        $checkBet = TriplePattiBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        TriplePattiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 9) {

        $checkBet = HalfSangamBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        HalfSangamBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 10) {

        $checkBet = FullSangamBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        FullSangamBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 11) {

        $checkBet = JodiFamilyBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        JodiFamilyBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 12) {

        $checkBet = RedJodiBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        RedJodiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 13) {

        $checkBet = RedFamilyJodiBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        RedFamilyJodiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 14) {

        $checkBet = CyclePattiiBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;

        $amount = $checkBet->amount;
        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        CyclePattiiBit::where('id', $request->id)->delete();
      }
      if ($request->game_id == 15) {

        $checkBet = PannaFamilyBit::where('id', $request->id)->first();
        $user_id = $checkBet->user_id;
        $amount = $checkBet->amount;

        $bit = Bit::where('id', $checkBet->bit_id)->first();

        $store_id = $bit->stores_id;
        $bit->amount = $bit->amount - $checkBet->amount;
        $bit->save();

        PannaFamilyBit::where('id', $request->id)->delete();
      }

      if ($user_id && $amount) {
        $paymentchecck = $this->payment->where('user_id', $user_id)->first();
        if (!empty($paymentchecck)) {
          $paymentchecck->amount = $paymentchecck->amount + $amount;
          $paymentchecck->save();
          $paymentid = $paymentchecck->id;
        } else {
          #get the requested data in Data variable
          $data = [
            'payment_id' => 1,
            'amount'       => $amount,
            'user_id'    => $user_id,
          ];
          #store the newly creted resoures
          $paymentchecck = $this->payment->create($data);
          $paymentid = $paymentchecck->id;
        }


        $data = [
          'debit_amount'       => 0,
          'credit_amount'       => $amount,
          'user_id'    => $user_id,
          'created_by'        => Auth::user()->id,
        ];
        #store the newly creted resoures
        $this->debitPayment->create($data);

        $paymentHistorychecck = $this->paymentHistory->where('user_id', $user_id)->first();

        if (!empty($paymentHistorychecck)) {
          $remainamount = $paymentHistorychecck->remain_amount + $amount;
          $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount + $amount;
          $paymentHistorychecck->remain_amount =  $remainamount;
          $paymentHistorychecck->save();
        } else {
          #get the requested data in Data variable
          $data = [
            'total_amount'       => $amount,
            'remain_amount'      => $amount,
            'debit_total_amount' => 0,
            'user_id'    => $user_id,
          ];
          #store the newly creted resoures
          $this->paymentHistory->create($data);
          $remainamount = $amount;
        }

        $data = [
          'reamount' => $remainamount,
          'remark' => 'Bet Amount Refunded ' . $amount . ' by admin',
          'amount'       => $amount,
          'payment_id'      => $paymentid,
          'type'            => 'add',
          'user_id'    => $user_id,
        ];
        #store the newly creted resoures
        $this->paymentNewHistory->create($data);


        $postcust = $this->user->whereId($user_id)->first();
        $user_id = $user_id;
        $name = $postcust->name;
        $body = 'Dear ' . $name . ' Bet Amount Refunded ' . $amount . ' by admin';
        $title = "Point Refunded";
        $this->notificationUser($title, $body, $user_id);
      }



      DB::commit();
      return back();
    } catch (\Exception $ex) {
      DB::rollback();
      toastr()->success($ex->getMessage());
      return back()->with('error', $ex->getMessage());
    }
  }
}
