<?php

namespace App\Http\Controllers\AdminAPI\GameManagement;

# 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\SinglePattiPannaBit;
use App\Models\DoublePattiBit;
use App\Models\DoublePattiPannaBit;
use App\Models\TriplePattiBit;
use App\Models\TriplePattiPannaBit;
use App\Models\JodiBit;
use App\Models\HalfSangamBit;
use App\Models\FullSangamBit;
use App\Models\JodiFamilyBit;
use App\Models\JodiFamilyJodiBit;
use App\Models\RedJodiBit;
use App\Models\RedFamilyJodiBit;
use App\Models\RedFamilyJodi;
use App\Models\CyclePattiiBit;
use App\Models\CyclePattiPannaBit;
use App\Models\PannaFamilyBit;
use App\Models\PannaFamilyPannaBit;
use App\Models\DpMotorBit;
use App\Models\SpMotorBit;
use App\Models\DPMotorPannaBit;
use App\Models\SPMotorPannaBit;
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\API\BaseController as BaseController;
use Maatwebsite\Excel\Facades\Excel;
use App\Traits\FirebaseTraits;
use Auth;
use App\Exports\ExportPlayedOpen;
use App\Exports\ExportPlayedClose;
use App\Traits\EditTrait;


class OCCuttingController extends BaseController
{
  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 storePlayOpen(Request $request, $id)
  {

    // try {

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

    $input     = $request->all();
    $type      = $request->type;
    $stores_id = $request->stores_id;
    $game_id = $request->game_id;


    $details['storess'] = $this->store->whereId($stores_id)->first();
    
    $details['all_copy'] = "Market: ".$details['storess']->name." (".$type.")\nDate: ".$dateFilter."\n===============\n";
    
    $mainText = "Market: ".$details['storess']->name." (".$type.")\nDate: ".$dateFilter."\n===============\n";
        
      $gameMap = [
            'single'      => [1],
            'jodi'        => [2,11,12,13],
            'pana'        => [3,4,5,6,7,8,14,15,16,17],
            'halfsangam'  => [9],
            'fullsangam'  => [10],
        ];
        
        $gameIds = $gameMap[$game_id] ?? [];
        
        $summary_bet = $this->bit
            ->whereDate('created_at', $dateFilter)
            ->where('stores_id', $stores_id)
            ->when($gameIds, function ($q) use ($gameIds) {
                return $q->whereIn('game_id', $gameIds);
            });
        
        $summary_win = $this->userWinnersAmount
            ->whereDate('created_at', $dateFilter)
            ->where('stores_id', $stores_id)
            ->when($gameIds, function ($q) use ($gameIds) {
                return $q->whereIn('game_id', $gameIds);
            });
        
        $details['total_summary_bet_amount'] = (clone $summary_bet)->sum('amount');
        $details['total_summary_bet']        = (clone $summary_bet)->count();
        $total_summary_bet_ids   = (clone $summary_bet)->pluck('id');
        
        $details['total_summary_win_amount'] = (clone $summary_win)->sum('amount');
        $details['total_summary_win']        = (clone $summary_win)->count();
        $total_summary_win_ids    = (clone $summary_win)->pluck('id');
        
        
         /*
        |--------------------------------------------------------------------------
        | SINGLE DIGIT
        |--------------------------------------------------------------------------
        */
        
        
       $details['single_bits'] = SingleDigitBit::select(
                        'bit_place',
                        \DB::raw('SUM(single_digit_bit.amount) as total_amount'),
                        \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                    )
                    ->leftJoin(
                        'user_winners_amount',
                        'user_winners_amount.payment_new_history_id',
                        '=',
                        'single_digit_bit.payment_new_history_id'
                    )
                    ->whereIn('single_digit_bit.bit_id', $total_summary_bet_ids)
                    ->groupBy('bit_place')
                    ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(1, $item->total_amount);
                
                        return $item;
                    });
            
            $details['single_ank_total'] = $this->bit
                ->whereDate('created_at', $dateFilter)
                ->where('stores_id', $stores_id)->where('game_id',1)->sum('amount');
                
            $details['single_ank_total_bits'] = $this->bit
                ->whereDate('created_at', $dateFilter)
                ->where('stores_id', $stores_id)->where('game_id',1)->count();
                
            $details['single_digit_win_amount'] = $this->userWinnersAmount
                ->whereDate('created_at', $dateFilter)
                ->where('stores_id', $stores_id)->where('game_id',1)->sum('amount');
                
                 $details['all_copy'] .= "Single Ank\n===============\n";
                 
                 $details['single_ank_copy'] = $mainText . "Single Ank\n===============\n";
                 
                 foreach( $details['single_bits'] as $value){
                     $details['all_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                     $details['single_ank_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                 }
                 
                 $details['single_ank_copy'] .= "===============\n" . "Total = ₹".  $details['single_ank_total'];
                 
                  $details['all_copy'] .= "Total = ₹".  $details['single_ank_total']."\n===============\n";
            
            /*
            |--------------------------------------------------------------------------
            | SINGLE PANA
            |--------------------------------------------------------------------------
            */ 
           
           $singlePannaQueries = [

                SinglePannaBit::select(
                    'bit_place',
                    'amount',
                    'payment_new_history_id'
                )->whereIn('bit_id', $total_summary_bet_ids),
            
                SinglePattiPannaBit::select(
                    'bit_place',
                    'amount',
                    'payment_new_history_id'
                )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^(?!.*(.).*\\1)[0-9]{3}$'"),
            
                PannaFamilyPannaBit::select(
                    'bit_place',
                    'amount',
                    'payment_new_history_id'
                )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^(?!.*(.).*\\1)[0-9]{3}$'"),
            
                CyclePattiPannaBit::select(
                    'bit_place',
                    'amount',
                    'payment_new_history_id'
                )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^(?!.*(.).*\\1)[0-9]{3}$'"),
            
                SPMotorPannaBit::select(
                    'bit_place',
                    'amount',
                    'payment_new_history_id'
                )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^(?!.*(.).*\\1)[0-9]{3}$'"),
            ];
            
            $singlePannaUnionQuery = array_shift($singlePannaQueries);
            
            foreach ($singlePannaQueries as $query) {
                $singlePannaUnionQuery->unionAll($query);
            }
            
            $details['single_pannas'] = \DB::query()
                    ->fromSub($singlePannaUnionQuery, 'single_pannas')
                    ->leftJoin(
                        'user_winners_amount',
                        'user_winners_amount.payment_new_history_id',
                        '=',
                        'single_pannas.payment_new_history_id'
                    )
                    ->select(
                        'bit_place',
                        \DB::raw('SUM(single_pannas.amount) as total_amount'),
                        \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                    )
                    ->groupBy('bit_place')
                    ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(5, $item->total_amount);
                
                        return $item;
                    });
            
            
            $details['single_pana_total'] = $details['single_pannas']->sum('total_amount');

            $details['single_pana_total_bits'] = $details['single_pannas']->count();
            
            $details['single_pana_win_amount'] = $details['single_pannas']->sum('win_amount');
            
            
                $details['all_copy'] .= "Single Pana\n===============\n";
                 $details['single_pana_copy'] = $mainText . "Single Pana\n===============\n";
                 foreach( $details['single_pannas'] as $value){
                     $details['all_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                     $details['single_pana_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['single_pana_total']."\n===============\n";
                 $details['single_pana_copy'] .= "===============\n" . "Total = ₹".  $details['single_pana_total'];
                
                
                /*
            |--------------------------------------------------------------------------
            | DOUBLLE PANA
            |--------------------------------------------------------------------------
            */ 
           
                $doublePannaQueries = [

                    DoublePannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                    DoublePattiPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1[0-9]|([0-9])[0-9]\\2|[0-9]([0-9])\\3$'"),
                
                    PannaFamilyPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1[0-9]|([0-9])[0-9]\\2|[0-9]([0-9])\\3$'"),
                
                    CyclePattiPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1[0-9]|([0-9])[0-9]\\2|[0-9]([0-9])\\3$'"),
                
                    DPMotorPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1[0-9]|([0-9])[0-9]\\2|[0-9]([0-9])\\3$'"),
                ];
                
                $doublePannaUnionQuery = array_shift($doublePannaQueries);
                
                foreach ($doublePannaQueries as $query) {
                    $doublePannaUnionQuery->unionAll($query);
                }
                
                $details['double_pannas'] = \DB::query()
                        ->fromSub($doublePannaUnionQuery, 'double_pannas')
                        ->leftJoin(
                            'user_winners_amount',
                            'user_winners_amount.payment_new_history_id',
                            '=',
                            'double_pannas.payment_new_history_id'
                        )
                        ->select(
                            'bit_place',
                            \DB::raw('SUM(double_pannas.amount) as total_amount'),
                            \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                        )
                        ->groupBy('bit_place')
                        ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(6, $item->total_amount);
                
                        return $item;
                    });
                
                
                $details['double_pana_total'] = $details['double_pannas']->sum('total_amount');
    
                $details['double_pana_total_bits'] = $details['double_pannas']->count();
                
                $details['double_pana_win_amount'] = $details['double_pannas']->sum('win_amount');
            
            $details['all_copy'] .= "Double Pana\n===============\n";
                 $details['double_pana_copy'] = $mainText . "Double Pana\n===============\n";
                 foreach( $details['double_pannas'] as $value){
                     $details['all_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                     $details['double_pana_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['double_pana_total']."\n===============\n";
                 $details['double_pana_copy'] .= "===============\n" . "Total = ₹".  $details['double_pana_total'];
            
                
                 /*
                |--------------------------------------------------------------------------
                | TRIPLE PANA
                |--------------------------------------------------------------------------
                */ 
               
                $triplePannaQueries = [

                    TripplePannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                    TriplePattiPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1\\1$'"),
                
                    PannaFamilyPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1\\1$'"),
                
                    CyclePattiPannaBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids)->whereRaw("bit_place REGEXP '^([0-9])\\1\\1$'"),
                
                ];
                
                $triplePannaUnionQuery = array_shift($triplePannaQueries);
                
                foreach ($triplePannaQueries as $query) {
                    $triplePannaUnionQuery->unionAll($query);
                }
                
                $details['triple_pannas'] = \DB::query()
                        ->fromSub($triplePannaUnionQuery, 'triple_pannas')
                        ->leftJoin(
                            'user_winners_amount',
                            'user_winners_amount.payment_new_history_id',
                            '=',
                            'triple_pannas.payment_new_history_id'
                        )
                        ->select(
                            'bit_place',
                            \DB::raw('SUM(triple_pannas.amount) as total_amount'),
                            \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                        )
                        ->groupBy('bit_place')
                        ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(7, $item->total_amount);
                
                        return $item;
                    });
                
                
                $details['triple_pana_total'] = $details['triple_pannas']->sum('total_amount');
    
                $details['triple_pana_total_bits'] = $details['triple_pannas']->count();
                
                $details['triple_pana_win_amount'] = $details['triple_pannas']->sum('win_amount');
                
                $details['all_copy'] .= "Triple Pana\n===============\n";
                 $details['triple_pana_copy'] = $mainText . "Triple Pana\n===============\n";
                 foreach( $details['triple_pannas'] as $value){
                     $details['all_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                     $details['triple_pana_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['triple_pana_total']."\n===============\n";
                 $details['triple_pana_copy'] .= "===============\n" . "Total = ₹".  $details['triple_pana_total'];
                
               
                    
                    
                     /*
                |--------------------------------------------------------------------------
                | Jodi
                |--------------------------------------------------------------------------
                */ 
               
               
                    
                    $jodiQueries = [

                    JodiBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                    RedJodiBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                    RedFamilyJodi::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                    JodiFamilyJodiBit::select(
                        'bit_place',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                ];
                
                $jodiUnionQuery = array_shift($jodiQueries);
                
                foreach ($jodiQueries as $query) {
                    $jodiUnionQuery->unionAll($query);
                }
                
                $details['jodi_bits'] = \DB::query()
                        ->fromSub($jodiUnionQuery, 'jodi_bits')
                        ->leftJoin(
                            'user_winners_amount',
                            'user_winners_amount.payment_new_history_id',
                            '=',
                            'jodi_bits.payment_new_history_id'
                        )
                        ->select(
                            'bit_place',
                            \DB::raw('SUM(jodi_bits.amount) as total_amount'),
                            \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                        )
                        ->groupBy('bit_place')
                        ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(2, $item->total_amount);
                
                        return $item;
                    });
                
                
                $details['jodi_total'] = $details['jodi_bits']->sum('total_amount');
    
                $details['jodi_total_bits'] = $details['jodi_bits']->count();
                
                $details['jodi_win_amount'] = $details['jodi_bits']->sum('win_amount');
                
                $details['all_copy'] .= "Jodi\n===============\n";
                 $details['jodi_copy'] = $mainText . "Jodi\n===============\n";
                 foreach( $details['jodi_bits'] as $value){
                     $details['all_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                     $details['jodi_copy'] .= $value->bit_place ."= ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['jodi_total']."\n===============\n";
                 $details['jodi_copy'] .= "===============\n" . "Total = ₹".  $details['jodi_total'];
                
                
                    
                    
                     /*
                |--------------------------------------------------------------------------
                | Half Sangam
                |--------------------------------------------------------------------------
                */ 
               
               
                
                     $halfSangamQueries = [

                    HalfSangamBit::select(
                        'bit_place_panna','bit_place_single',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                ];
                
                $halfSangamUnionQuery = array_shift($halfSangamQueries);
                
                foreach ($halfSangamQueries as $query) {
                    $halfSangamUnionQuery->unionAll($query);
                }
                
                $details['half_sangam'] = \DB::query()
                        ->fromSub($halfSangamUnionQuery, 'half_sangam')
                        ->leftJoin(
                            'user_winners_amount',
                            'user_winners_amount.payment_new_history_id',
                            '=',
                            'half_sangam.payment_new_history_id'
                        )
                        ->select(
                            'bit_place_panna','bit_place_single',
                            \DB::raw('SUM(half_sangam.amount) as total_amount'),
                            \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                        )
                        ->groupBy('bit_place_panna','bit_place_single')
                        ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(9, $item->total_amount);
                
                        return $item;
                    });
                
                
                $details['half_sangam_total'] = $details['half_sangam']->sum('total_amount');
    
                $details['half_sangam_total_bits'] = $details['half_sangam']->count();
                
                $details['half_sangam_win_amount'] = $details['half_sangam']->sum('win_amount');
                    
                    
                    $details['all_copy'] .= "Half Sangam\n===============\n";
                 $details['half_sangam_copy'] = $mainText . "Half Sangam\n===============\n";
                 foreach( $details['half_sangam'] as $value){
                     $details['all_copy'] .= $value->bit_place_panna."-".$value->bit_place_single ." = ₹". $value->total_amount ."\n";
                     $details['half_sangam_copy'] .= $value->bit_place_panna."-".$value->bit_place_single ." = ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['half_sangam_total']."\n===============\n";
                 $details['half_sangam_copy'] .= "===============\n" . "Total = ₹".  $details['half_sangam_total'];
                      /*
                |--------------------------------------------------------------------------
                | Full Sangam
                |--------------------------------------------------------------------------
                */ 
               
                $fullSangamQueries = [

                    FullSangamBit::select(
                        'bit_place_panna','bit_place_single',
                        'amount',
                        'payment_new_history_id'
                    )->whereIn('bit_id', $total_summary_bet_ids),
                
                ];
                
                $fullSangamUnionQuery = array_shift($fullSangamQueries);
                
                foreach ($fullSangamQueries as $query) {
                    $fullSangamUnionQuery->unionAll($query);
                }
                
                $details['full_sangam'] = \DB::query()
                        ->fromSub($fullSangamUnionQuery, 'full_sangam')
                        ->leftJoin(
                            'user_winners_amount',
                            'user_winners_amount.payment_new_history_id',
                            '=',
                            'full_sangam.payment_new_history_id'
                        )
                        ->select(
                            'bit_place_panna','bit_place_single',
                            \DB::raw('SUM(full_sangam.amount) as total_amount'),
                            \DB::raw('COALESCE(SUM(user_winners_amount.amount),0) as win_amount')
                        )
                        ->groupBy('bit_place_panna','bit_place_single')
                        ->get()
                    ->map(function ($item) {
                
                        $item->predict_win = predictWin(10, $item->total_amount);
                
                        return $item;
                    });
                
                
                $details['full_sangam_total'] = $details['full_sangam']->sum('total_amount');
    
                $details['full_sangam_total_bits'] = $details['full_sangam']->count();
                
                $details['full_sangam_win_amount'] = $details['full_sangam']->sum('win_amount');
           
           
            $details['all_copy'] .= "Full Sangam\n===============\n";
                 $details['full_sangam_copy'] = $mainText . "Full Sangam\n===============\n";
                 foreach( $details['full_sangam'] as $value){
                     $details['all_copy'] .= $value->bit_place_panna."-".$value->bit_place_single ." = ₹". $value->total_amount ."\n";
                     $details['full_sangam_copy'] .= $value->bit_place_panna."-".$value->bit_place_single ." = ₹". $value->total_amount ."\n";
                 }
                  $details['all_copy'] .= "Total = ₹".  $details['full_sangam_total']."\n===============\n";
                 $details['full_sangam_copy'] .= "===============\n" . "Total = ₹".  $details['full_sangam_total'];
            
            
            $details['all_copy'] .= "Total Amount : ₹" .  $details['total_summary_bet_amount'];
            
            
            
            // return $details['single_bits'];

    #render view
    return $this->sendResponse($details, 'Result Get successfully.');
    // } 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();
        $type      = $request->type;
        $stores_id = $request->stores_id;
    
        $relation = ['username', 'bit'];
    
        $details = [];
    
        /*
    |--------------------------------------------------------------------------
    | SINGLE DIGIT
    |--------------------------------------------------------------------------
    */
    
    $singles = singleList();

    $singleAnk = SingleDigitBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->whereDate('created_at', $dateFilter)
        ->groupBy('bit_place')
        ->pluck('total_amount', 'bit_place')
        ->toArray();
    
    $details['single_ank'] = collect($singles)->map(function ($single) use ($singleAnk) {
        return [
            'bit_place'   => $single,
            'total_amount'=> $singleAnk[$single] ?? 0,
        ];
    })->sortByDesc('total_amount')->values();
    
    
    // return $details['single_ank'];
    
    $details['single_ank_total'] = SingleDigitBit::with($relation)
            ->whereHas('bit', function ($q) use ($type, $stores_id) {
                $q->where('type', $type)
                  ->where('stores_id', $stores_id);
            })
            ->where('created_at', 'LIKE', "%{$dateFilter}%")
            ->sum('amount');


    
    
    /*
    |--------------------------------------------------------------------------
    | SINGLE PATTI
    |--------------------------------------------------------------------------
    */
    
    $pannas = pannaList();
    $single_panna = SinglePannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
        
    
    $single_panna_total = SinglePannaBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $single_patti_ids = SinglePattiBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $single_patti = SinglePattiPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('single_patti_bit_id', $single_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $single_patti_total = SinglePattiPannaBit::whereIn('single_patti_bit_id', $single_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['single_patti'] = $single_panna->concat($single_patti)
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['single_patti_total'] = $single_panna_total + $single_patti_total;
    
    
    /*
    |--------------------------------------------------------------------------
    | DOUBLE PATTI
    |--------------------------------------------------------------------------
    */
    $double_panna = DoublePannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $double_panna_total = DoublePannaBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $double_patti_ids = DoublePattiBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $double_patti = DoublePattiPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('double_patti_bit_id', $double_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $double_patti_total = DoublePattiPannaBit::whereIn('double_patti_bit_id', $double_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['double_patti'] = $double_panna->concat($double_patti)
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['double_patti_total'] = $double_panna_total + $double_patti_total;


    /*
    |--------------------------------------------------------------------------
    | TRIPLE PATTI
    |--------------------------------------------------------------------------
    */
    $triple_panna = TripplePannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $triple_panna_total = TripplePannaBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $triple_patti_ids = TriplePattiBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $triple_patti = TriplePattiPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('triple_patti_bit_id', $triple_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $triple_patti_total = TriplePattiPannaBit::whereIn('triple_patti_bit_id', $triple_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['triple_patti'] = $triple_panna->concat($triple_patti)
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['triple_patti_total'] = $triple_panna_total + $triple_patti_total;
    
    
    /*
    |--------------------------------------------------------------------------
    | CYCLE PATTI
    |--------------------------------------------------------------------------
    */
    $cycle_patti_ids = CyclePattiiBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $cycle_patti = CyclePattiPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('cycle_patti_bit_id', $cycle_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $cycle_patti_total = CyclePattiPannaBit::whereIn('cycle_patti_bit_id', $cycle_patti_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['cycle_patti'] = $cycle_patti
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['cycle_patti_total'] = $cycle_patti_total;
    
    
    /*
    |--------------------------------------------------------------------------
    | PANNA FAMILY
    |--------------------------------------------------------------------------
    */
    $panna_family_ids = PannaFamilyBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $panna_family = PannaFamilyPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('panna_family_bit_id', $panna_family_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $panna_family_total = PannaFamilyPannaBit::whereIn('panna_family_bit_id', $panna_family_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['panna_family'] = $panna_family
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['panna_family_total'] = $panna_family_total;
    
    
    /*
    |--------------------------------------------------------------------------
    | SP MOTOR
    |--------------------------------------------------------------------------
    */
    $sp_motor_ids = SpMotorBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $sp_motor = SPMotorPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('sp_motor_bit_id', $sp_motor_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $sp_motor_total = SPMotorPannaBit::whereIn('sp_motor_bit_id', $sp_motor_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['sp_motor'] = $sp_motor
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['sp_motor_total'] = $sp_motor_total;
    
    
    /*
    |--------------------------------------------------------------------------
    | DP MOTOR
    |--------------------------------------------------------------------------
    */
    $dp_motor_ids = DpMotorBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->pluck('id');
    
    $dp_motor = DPMotorPannaBit::select(
            'bit_place',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->whereIn('dp_motor_bit_id', $dp_motor_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $dp_motor_total = DPMotorPannaBit::whereIn('dp_motor_bit_id', $dp_motor_ids)
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
    $details['dp_motor'] = $dp_motor
        ->groupBy('bit_place')
        ->map(function ($items) {
            return (object)[
                'bit_place' => $items->first()->bit_place,
                'total_amount' => $items->sum('total_amount')
            ];
        })
        ->values();
    
    $details['dp_motor_total'] = $dp_motor_total;
    
    
            /*
        |--------------------------------------------------------------------------
        | GET ALL PANNA TOTALS
        |--------------------------------------------------------------------------
        */
        
        // create default panna array with 0 amount
        $allPannas = collect($pannas)->mapWithKeys(function ($panna) {
            return [
                $panna => (object)[
                    'bit_place'   => $panna,
                    'total_amount'=> 0
                ]
            ];
        });
        
        
        /*
        |--------------------------------------------------------------------------
        | MERGE ALL PANNA BETS
        |--------------------------------------------------------------------------
        */
        
        $mergedPannas = collect()
        
            // SINGLE PATTI
            ->merge($details['single_patti'] ?? [])
        
            // DOUBLE PATTI
            ->merge($details['double_patti'] ?? [])
        
            // TRIPLE PATTI
            ->merge($details['triple_patti'] ?? [])
        
            // CYCLE PATTI
            ->merge($details['cycle_patti'] ?? [])
        
            // PANNA FAMILY
            ->merge($details['panna_family'] ?? [])
        
            // SP MOTOR
            ->merge($details['sp_motor'] ?? [])
        
            // DP MOTOR
            ->merge($details['dp_motor'] ?? []);
        
        
        
        /*
        |--------------------------------------------------------------------------
        | GROUP & SUM TOTAL AMOUNTS
        |--------------------------------------------------------------------------
        */
        
        $finalPannas = $mergedPannas
            ->groupBy('bit_place')
            ->map(function ($items) {
                return (object)[
                    'bit_place'    => $items->first()->bit_place,
                    'total_amount' => $items->sum('total_amount')
                ];
            });
        
        
        /*
        |--------------------------------------------------------------------------
        | MERGE WITH ALL PANNA LIST
        |--------------------------------------------------------------------------
        */
        
        $details['all_pannas'] = $allPannas->map(function ($item, $key) use ($finalPannas) {
                if (isset($finalPannas[$key])) {
                    return $finalPannas[$key];
                }
                return $item;
            })->values();
        
        
        /*
        |--------------------------------------------------------------------------
        | TOTAL OF ALL PANNA BETS
        |--------------------------------------------------------------------------
        */
        
        $details['all_pannas_total'] =
              ($details['single_patti_total'] ?? 0)
            + ($details['double_patti_total'] ?? 0)
            + ($details['triple_patti_total'] ?? 0)
            + ($details['cycle_patti_total'] ?? 0)
            + ($details['panna_family_total'] ?? 0)
            + ($details['sp_motor_total'] ?? 0)
            + ($details['dp_motor_total'] ?? 0);
    
    
    /*
    |--------------------------------------------------------------------------
    | HALF SANGAM
    |--------------------------------------------------------------------------
    */
    $details['half_sangam'] = HalfSangamBit::select(
            'bit_place_panna',
            'bit_place_single',
            \DB::raw('SUM(amount) as total_amount')
        )
        ->with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->groupBy('bit_place_panna', 'bit_place_single')
        ->orderBy('total_amount', 'DESC')
        ->get();
    
    $details['half_sangam_total'] = HalfSangamBit::with($relation)
        ->whereHas('bit', function ($q) use ($type, $stores_id) {
            $q->where('type', $type)
              ->where('stores_id', $stores_id);
        })
        ->where('created_at', 'LIKE', "%{$dateFilter}%")
        ->sum('amount');
    
      
$details['stores'] = $this->store->where('status',1)->get();
      $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.oc-cutting.index', $details);
    } catch (\Exception $ex) {
      return back()->with('error', $ex->getMessage());
    }
  }
  
  
  
  public function reportGenerate(Request $request){
      
      $details['stores'] = $this->store->where('status',1)->get();
             $details['games'] = $this->game->where('status',1)->get();
             $details['customerss'] = User::where('status', 1)->where('type', 'customer')->get();
             
             
             return view('admin.report-generation.index', $details);
      
  }
  
  public function reportGeneration(Request $request){
      
      $id = $request->stores_id;
      
      return $this->storePlayOpen($request, $id);
      if($request->type == "close"){
          return $this->storePlayClose($request, $id);
      }else{
          
      }
      
      
  }

}