<?php

namespace App\Http\Controllers;

use App\Models\DailyLevelComission;
use App\Models\DailyProfit;
use App\Models\DailySecondLevelCommission;
use App\Models\investlimit;
use App\Models\InvestMoney;
use App\Models\MoneyModel;
use App\Models\ProfitPercentage;
use App\Models\ReferenceBalanceModel;
use App\Models\RequestWithdrawDailyProfit;
use App\Models\UserLogin;
use App\Models\UsersMoneyReqModel;
use App\Models\UserTotalDailyProfit;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Coinremitter\Coinremitter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserInvestMoney extends Controller
{
    //
    public function user_invest_money_page(){
      
         $ms =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
      
        
         $user_money  = UsersMoneyReqModel::where('status',1)->where('customer_id',Auth::guard('user_login')->user()->id)->get();
         $al_mm = 0;
         foreach($user_money as $sssa){
              $al_mm += $sssa->ammount;
         }
          $al_mm;
        $fst = 25;
        $per = $fst/100;
        $second =15;
        $sec_per = $second/100;
         
        //First Refered By
           $sd =  UserLogin::where('Refer_by',Auth::guard('user_login')->user()->Refer_id)->get();
           foreach($sd as $s){
             
             $s->id;
            $s->Refer_id;
             $secend = UserLogin::where('Refer_by',$s->Refer_id)->first();
            if($secend){
                $secon_dai =  DailyProfit::where('invest_user_id',$secend->id)->get();
                foreach($secon_dai as $seccc){


                    $existingRecordss = DailySecondLevelCommission::where('user_id', Auth::guard('user_login')->user()->id)
                    ->where('first_level_user_id', $s->id)
                    ->where('seceond_level_invest_id',$seccc->invest_money_id)
                    ->whereDate('seceond_level_created_at', $seccc->created_at->toDateString())
                    ->first();

                    if(!$existingRecordss){
                        DailySecondLevelCommission::create([
                            'user_id'=>Auth::guard('user_login')->user()->id,
                            'first_level_user_id'=>$s->id,
                            'seceond_level_user_id'=>$secend->id,
                            'seceond_level_invest_id'=>$seccc->invest_money_id,
                            'seceond_level_daily_profit_ammount'=>$seccc->profitted_ammount,
                            'seceond_level_commission_percentage'=>$second,
                            'seceond_level_commission_ammount_after_per'=>$seccc->profitted_ammount*$sec_per,
                            'seceond_level_created_at'=>$seccc->created_at,
        
                          ]);
                    }
                 
                }

            }



            Auth::guard('user_login')->user()->name ." Referred To " .$s->name."<br>";//user refered to 1st person
            $daiii =  DailyProfit::where('invest_user_id',$s->id)->get();//1st person daily profit
            if($daiii){
                foreach($daiii as $dd){
                    $existingRecords = DailyLevelComission::where('user_id', Auth::guard('user_login')->user()->id)
                    ->where('first_level_user_id', $s->id)
                    ->where('first_level_invest_id',$dd->invest_money_id)
                    ->whereDate('first_level_created_at', $dd->created_at->toDateString())
                    ->first();
                    
                    if(!$existingRecords){
                        DailyLevelComission::create([
                            'user_id'=>Auth::guard('user_login')->user()->id,
                            'first_level_user_id'=>$s->id,
                            'first_level_invest_id'=>$dd->invest_money_id,
                            'first_level_daily_profit_ammount'=>$dd->profitted_ammount,
                            'fist_level_commission_percentage'=>$fst,
                            'fist_level_commission_ammount_after_per'=> $dd->profitted_ammount * $per ,
                            'first_level_created_at'=>$dd->created_at,
                        ]);
                    }
                  
                    // echo $dd->invest_user_id;
                    // echo UserLogin::find($dd->invest_user_id)->name;
                    // echo $dd->profitted_ammount * $per ;
                }
                 
            }
           

              $t = UserLogin::where('Refer_by',$s->Refer_id)->first();//1st person referred to the person
              if($t){
                  $s->name." referred To : ".$t->name;  
              }
             
           
           }

        foreach($sd as $w){
              $ree =  InvestMoney::where('user_id',$w->id)->where('time_period','!=',null)->where('status',1)->get();
              
            foreach($ree as $r){
                 $r;
                 $existingRecord = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_id',$r->id)->first();
            
                 if(!$existingRecord){
                     ReferenceBalanceModel::create([
                         'user_id'=>Auth::guard('user_login')->user()->id,
                         'refer_to_id'=>$w->id,
                         'refer_to_tk'=>$r->Tk,
                         'invest_id'=>$r->id,
                         'percentage'=>5,
                         'after_percentage'=>$r->Tk * 0.005
                     ]);
                 }
                
                   
              
               
            }
        }
        // return back();
          
        $profit_percentage = ProfitPercentage::latest()->first();
        if ($profit_percentage) {
            // The record exists, you can safely access its properties
            $per = $profit_percentage->profit_percentage;
        } else {
            // The record does not exist, handle this case accordingly
      
            $per = 0; // or any default value you want to set
        }
          
           $percantage =  ($per)/100;
         $invested_money = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
         $today = Carbon::now();
       
         $take = [];
         $allProfitPercentages = ProfitPercentage::all();

        




foreach ($invested_money as $in) {
    $startingDate = Carbon::parse($in->created_at);
    $endDates = $startingDate->copy()->addMonths($in->time_period);

    $profitDates = [];
    $dates = [];

    foreach ($allProfitPercentages as $p) {
        $profitCreatedAt = Carbon::parse($p->created_at)->toDateString();
        $date = Carbon::parse($p->created_at)->toDateString();
        $dates[] = $date;
        $profitDates[$profitCreatedAt] = $p->profit_percentage;
       
    }

     $firstDate = min($dates);
     $lastDate = max($dates);

    $startDate = Carbon::parse($in->created_at)->startOfDay();
    $endDate = Carbon::now();

    $processedDates = [];
    $firstDaySkipped = false; // Flag to indicate whether the first day is skipped

    $period = CarbonPeriod::create($startDate, $endDate);

    foreach ($period as $date) {
        $formattedDate = $date->toDateString();

        if (!$firstDaySkipped) {
            // Skip the first day
            $firstDaySkipped = true;
            continue;
        }

        if ($date->greaterThan($endDates)) {
            InvestMoney::find($in->id)->update([
                'withdraw' => 1,
                'end_package_time' => $endDates,
            ]);
            break;
        }

        if ($date->isWeekend()) {
            continue; // Skip weekends
        }

        if (array_key_exists($formattedDate, $profitDates) && !in_array($formattedDate, $processedDates)) {
            $profitPercentage = $profitDates[$formattedDate];
            "Match found for date: $formattedDate with Profit Percentage: $profitPercentage\n";

            $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                ->whereDate('created_at', $formattedDate)
                ->first();

            if (!$existingDailyProfit) {
                $perr = $profitPercentage / 100;
                $after_per = $perr * $in->Tk;

                DailyProfit::create([
                    'invest_money_id' => $in->id,
                    'invest_user_id' => $in->user_id,
                    'profit_percentage' => $profitPercentage,
                    'profitted_ammount' => $after_per,
                    'created_at' => $formattedDate,
                ]);
            }
        } else {
            // Find the nearest smaller date from $allProfitPercentages
            $nearestSmallerDate = null;
            $nearestSmallerPercentage = null;

            foreach ($allProfitPercentages as $p) {
                $pDate = Carbon::parse($p->created_at)->toDateString();

                if ($pDate < $formattedDate) {
                    if (!$nearestSmallerDate || $nearestSmallerDate < $pDate) {
                        $nearestSmallerDate = $pDate;
                        $nearestSmallerPercentage = $p->profit_percentage;
                    }
                }
            }

            if ($nearestSmallerDate !== null) {
                // Insert data for non-matching dates using the nearest smaller date's profit percentage
                $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                    ->whereDate('created_at', $formattedDate)
                    ->first();

                if (!$existingDailyProfit) {
                    $perr = $nearestSmallerPercentage / 100;
                    $after_per = $perr * $in->Tk;

                    DailyProfit::create([
                        'invest_money_id' => $in->id,
                        'invest_user_id' => $in->user_id,
                        'profit_percentage' => $nearestSmallerPercentage,
                        'profitted_ammount' => $after_per,
                        'created_at' => $formattedDate,
                    ]);
                }
            }
        }

        $processedDates[] = $formattedDate;
    }
}


       
        
        $invest_limit = investlimit::first();
        $daily_profits = DailyProfit::where('invest_user_id',Auth::guard('user_login')->user()->id)->get();
        $user_id = Auth::guard('user_login')->user()->id;
        $total_d = 0;
        $ta = 0; 
        $reque =  RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
        $total_invest_money= 0;
         $invest_money_record = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->get();

        //  $inn = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_deduct',null)->get();
        foreach($invest_money_record as $invested){
            $total_invest_money += $invested->Tk;
        }
        $money =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
        $total_amm = 0;
       $useraa =  UsersMoneyReqModel::where('customer_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
       foreach($useraa as $ssa){
        $total_amm += $ssa->ammount;
       }
        $total_amm;
       $t_m = 0;
     foreach($invest_money_record as $ia){
        $t_m += $ia->Tk;
     }
      $t_m;
 


        if($money){
            $s = $money->total;
            $rest = $total_amm - $t_m;
            $money->update([
                'total'=>$rest,
             ]);
        }else{
            $rest = 0;
            MoneyModel::create([
                'customer_id'=>Auth::guard('user_login')->user()->id,
                'total'=>$rest
            ]);
        }

        
         
         foreach($invest_money_record as $invested){
            InvestMoney::find($invested->id)->update([
                'invest_deduct'=>'deduct_done'
            ]);
        }

        foreach($reque as $re){
            $ta += $re->ammount;
        }
         $ta;
        
        if ($daily_profits) {
            foreach ($daily_profits as $daiii) {
                $total_d += $daiii->profitted_ammount;
            }
        }
        $u = UserTotalDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->first();
        if($u){
            $u->update([
                'user_id'=>Auth::guard('user_login')->user()->id,
            'total'=>$total_d-$ta,
            ]);
        }else{
            UserTotalDailyProfit::create([
                'user_id'=>Auth::guard('user_login')->user()->id,
                'total'=>$total_d-$ta,
            ]);
        }
        
     
    
        
        return view('user.user_invest_money_page',[
            'invest_money_record'=>$invest_money_record,
            'invest_limit'=>$invest_limit,
            'al_mm'=>$al_mm,
            'ms'=>$ms,
          
        ]);
    }
    function user_invest_money_page_1(){
        $ms =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
      
        
         $user_money  = UsersMoneyReqModel::where('status',1)->where('customer_id',Auth::guard('user_login')->user()->id)->get();
         $al_mm = 0;
         foreach($user_money as $sssa){
              $al_mm += $sssa->ammount;
         }
          $al_mm;
        $fst = 25;
        $per = $fst/100;
        $second =15;
        $sec_per = $second/100;
         
        //First Refered By
           $sd =  UserLogin::where('Refer_by',Auth::guard('user_login')->user()->Refer_id)->get();
           foreach($sd as $s){
             
             $s->id;
            $s->Refer_id;
             $secend = UserLogin::where('Refer_by',$s->Refer_id)->first();
            if($secend){
                $secon_dai =  DailyProfit::where('invest_user_id',$secend->id)->get();
                foreach($secon_dai as $seccc){


                    $existingRecordss = DailySecondLevelCommission::where('user_id', Auth::guard('user_login')->user()->id)
                    ->where('first_level_user_id', $s->id)
                    ->where('seceond_level_invest_id',$seccc->invest_money_id)
                    ->whereDate('seceond_level_created_at', $seccc->created_at->toDateString())
                    ->first();

                    if(!$existingRecordss){
                        DailySecondLevelCommission::create([
                            'user_id'=>Auth::guard('user_login')->user()->id,
                            'first_level_user_id'=>$s->id,
                            'seceond_level_user_id'=>$secend->id,
                            'seceond_level_invest_id'=>$seccc->invest_money_id,
                            'seceond_level_daily_profit_ammount'=>$seccc->profitted_ammount,
                            'seceond_level_commission_percentage'=>$second,
                            'seceond_level_commission_ammount_after_per'=>$seccc->profitted_ammount*$sec_per,
                            'seceond_level_created_at'=>$seccc->created_at,
        
                          ]);
                    }
                 
                }

            }



            Auth::guard('user_login')->user()->name ." Referred To " .$s->name."<br>";//user refered to 1st person
            $daiii =  DailyProfit::where('invest_user_id',$s->id)->get();//1st person daily profit
            if($daiii){
                foreach($daiii as $dd){
                    $existingRecords = DailyLevelComission::where('user_id', Auth::guard('user_login')->user()->id)
                    ->where('first_level_user_id', $s->id)
                    ->where('first_level_invest_id',$dd->invest_money_id)
                    ->whereDate('first_level_created_at', $dd->created_at->toDateString())
                    ->first();
                    
                    if(!$existingRecords){
                        DailyLevelComission::create([
                            'user_id'=>Auth::guard('user_login')->user()->id,
                            'first_level_user_id'=>$s->id,
                            'first_level_invest_id'=>$dd->invest_money_id,
                            'first_level_daily_profit_ammount'=>$dd->profitted_ammount,
                            'fist_level_commission_percentage'=>$fst,
                            'fist_level_commission_ammount_after_per'=> $dd->profitted_ammount * $per ,
                            'first_level_created_at'=>$dd->created_at,
                        ]);
                    }
                  
                    // echo $dd->invest_user_id;
                    // echo UserLogin::find($dd->invest_user_id)->name;
                    // echo $dd->profitted_ammount * $per ;
                }
                 
            }
           

              $t = UserLogin::where('Refer_by',$s->Refer_id)->first();//1st person referred to the person
              if($t){
                  $s->name." referred To : ".$t->name;  
              }
             
           
           }

        foreach($sd as $w){
              $ree =  InvestMoney::where('user_id',$w->id)->where('time_period','!=',null)->where('status',1)->get();
              
            foreach($ree as $r){
                 $r;
                 $existingRecord = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_id',$r->id)->first();
            
                 if(!$existingRecord){
                     ReferenceBalanceModel::create([
                         'user_id'=>Auth::guard('user_login')->user()->id,
                         'refer_to_id'=>$w->id,
                         'refer_to_tk'=>$r->Tk,
                         'invest_id'=>$r->id,
                         'percentage'=>5,
                         'after_percentage'=>$r->Tk * 0.005
                     ]);
                 }
                
                   
              
               
            }
        }
        // return back();
          
        $profit_percentage = ProfitPercentage::latest()->first();
        if ($profit_percentage) {
            // The record exists, you can safely access its properties
            $per = $profit_percentage->profit_percentage;
        } else {
            // The record does not exist, handle this case accordingly
      
            $per = 0; // or any default value you want to set
        }
          
           $percantage =  ($per)/100;
           $invested_money = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
           $today = Carbon::now();
         
           $take = [];
           $allProfitPercentages = ProfitPercentage::all();
  
          
  
  
  
  
  foreach ($invested_money as $in) {
      $startingDate = Carbon::parse($in->created_at);
      $endDates = $startingDate->copy()->addMonths($in->time_period);
  
      $profitDates = [];
      $dates = [];
  
      foreach ($allProfitPercentages as $p) {
          $profitCreatedAt = Carbon::parse($p->created_at)->toDateString();
          $date = Carbon::parse($p->created_at)->toDateString();
          $dates[] = $date;
          $profitDates[$profitCreatedAt] = $p->profit_percentage;
         
      }
  
       $firstDate = min($dates);
       $lastDate = max($dates);
  
      $startDate = Carbon::parse($in->created_at)->startOfDay();
      $endDate = Carbon::now();
  
      $processedDates = [];
      $firstDaySkipped = false; // Flag to indicate whether the first day is skipped
  
      $period = CarbonPeriod::create($startDate, $endDate);
  
      foreach ($period as $date) {
          $formattedDate = $date->toDateString();
  
          if (!$firstDaySkipped) {
              // Skip the first day
              $firstDaySkipped = true;
              continue;
          }
  
          if ($date->greaterThan($endDates)) {
              InvestMoney::find($in->id)->update([
                  'withdraw' => 1,
                  'end_package_time' => $endDates,
              ]);
              break;
          }
  
          if ($date->isWeekend()) {
              continue; // Skip weekends
          }
  
          if (array_key_exists($formattedDate, $profitDates) && !in_array($formattedDate, $processedDates)) {
              $profitPercentage = $profitDates[$formattedDate];
              "Match found for date: $formattedDate with Profit Percentage: $profitPercentage\n";
  
              $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                  ->whereDate('created_at', $formattedDate)
                  ->first();
  
              if (!$existingDailyProfit) {
                  $perr = $profitPercentage / 100;
                  $after_per = $perr * $in->Tk;
  
                  DailyProfit::create([
                      'invest_money_id' => $in->id,
                      'invest_user_id' => $in->user_id,
                      'profit_percentage' => $profitPercentage,
                      'profitted_ammount' => $after_per,
                      'created_at' => $formattedDate,
                  ]);
              }
          } else {
              // Find the nearest smaller date from $allProfitPercentages
              $nearestSmallerDate = null;
              $nearestSmallerPercentage = null;
  
              foreach ($allProfitPercentages as $p) {
                  $pDate = Carbon::parse($p->created_at)->toDateString();
  
                  if ($pDate < $formattedDate) {
                      if (!$nearestSmallerDate || $nearestSmallerDate < $pDate) {
                          $nearestSmallerDate = $pDate;
                          $nearestSmallerPercentage = $p->profit_percentage;
                      }
                  }
              }
  
              if ($nearestSmallerDate !== null) {
                  // Insert data for non-matching dates using the nearest smaller date's profit percentage
                  $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                      ->whereDate('created_at', $formattedDate)
                      ->first();
  
                  if (!$existingDailyProfit) {
                      $perr = $nearestSmallerPercentage / 100;
                      $after_per = $perr * $in->Tk;
  
                      DailyProfit::create([
                          'invest_money_id' => $in->id,
                          'invest_user_id' => $in->user_id,
                          'profit_percentage' => $nearestSmallerPercentage,
                          'profitted_ammount' => $after_per,
                          'created_at' => $formattedDate,
                      ]);
                  }
              }
          }
  
          $processedDates[] = $formattedDate;
      }
  }
   
$total_invest_money = 0;
// $inn = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_deduct',null)->get();
$invest_money_record = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->get();
foreach($invest_money_record as $invested){
    $total_invest_money += $invested->Tk;
}
$money =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
if($money){
    $s = $money->total;
    $rest = $s - $total_invest_money;
    $money->update([
        'total'=>$rest,
     ]);
}else{
    $rest = 0;
    MoneyModel::create([
        'customer_id'=>Auth::guard('user_login')->user()->id,
        'total'=>$rest
    ]);
}

          $invest_money_record = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->get();
        $invest_limit = investlimit::first();
        $daily_profits = DailyProfit::where('invest_user_id',Auth::guard('user_login')->user()->id)->get();
        $user_id = Auth::guard('user_login')->user()->id;
        $total_d = 0;
        $ta = 0; 
        $reque =  RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();

        $total_invest_money= 0;
         $invest_money_record = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->get();

        //  $inn = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_deduct',null)->get();
        foreach($invest_money_record as $invested){
            $total_invest_money += $invested->Tk;
        }
        $money =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
        $total_amm = 0;
       $useraa =  UsersMoneyReqModel::where('customer_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
       foreach($useraa as $ssa){
        $total_amm += $ssa->ammount;
       }
        $total_amm;
       $t_m = 0;
     foreach($invest_money_record as $ia){
        $t_m += $ia->Tk;
     }
      $t_m;
 


        if($money){
            $s = $money->total;
            $rest = $total_amm - $t_m;
            $money->update([
                'total'=>$rest,
             ]);
        }else{
            $rest = 0;
            MoneyModel::create([
                'customer_id'=>Auth::guard('user_login')->user()->id,
                'total'=>$rest
            ]);
        }

        foreach($reque as $re){
            $ta += $re->ammount;
        }
         $ta;
        
        if ($daily_profits) {
            foreach ($daily_profits as $daiii) {
                $total_d += $daiii->profitted_ammount;
            }
        }
        $u = UserTotalDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->first();
        if($u){
            $u->update([
                'user_id'=>Auth::guard('user_login')->user()->id,
            'total'=>$total_d-$ta,
            ]);
        }else{
            UserTotalDailyProfit::create([
                'user_id'=>Auth::guard('user_login')->user()->id,
                'total'=>$total_d-$ta,
            ]);
        }
        
     
    
        
        return view('user.user_invest_money_page_1',[
            'invest_money_record'=>$invest_money_record,
            'invest_limit'=>$invest_limit,
            'al_mm'=>$al_mm,
            'ms'=>$ms,
          
        ]);
    }
    public function dob_format($user_dob){
        return $user_dob;
      }
    function invest_insert(Request $request){
     
        //  if($request->transaction_number == null){
        //     return back()->with('error',"Sorrry you have not given any Address Of your wallet");
        //  }

        $ms =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
        if (empty($ms) ) {
            return back()->with("error","Plaese Insert the Money First");
        }
       
        $request->validate([
         
            'taka'=>'required|integer',
            'time_period'=>'required',
            
          
         ]);
         if ($request->taka < 100) {
            return back()->with('error', 'Sorry, Your Amount Is Low');
        }
       
        $m = UsersMoneyReqModel::where('status',1)->where('customer_id',Auth::guard('user_login')->user()->id)->get();
        $p = 0;
        foreach($m as $l){
            $p += $l->ammount;
        }
          $p;
         
         if($request->taka>$ms->total){
            return back()->with('error',"Sorry You Dont Have Enough Balance!Please Insert Money First");
         }
       if($p>= 100 && $p>=$request->taka){
          $remain = $ms->total - $request->taka;
          $ms->update([
            'total'=>$remain
          ]);
        InvestMoney::create([
            'user_id'=>Auth::guard('user_login')->user()->id,
            'phone_number'=>null,
            'transaction_number'=>"nothing",
            'mobile_operator'=>"nothing",
            'Tk'=>$request->taka,
            'img'=>"testing.jpg",
            'time_period'=>$request->time_period,
            'status'=>1,

        ]);
        return back()->with('success',"Successfully Buy with ".$request->taka." $ package for ". $request->time_period. " months");
       }else{
        return back()->with('error',"Something Is Wrong");
       }
   

        $tcn_wallet = new Coinremitter('TCN');
         $balanceResponse = $tcn_wallet->get_balance();
        $param = [
            'address'=>$request->transaction_number
        ];
        
         $validate = $tcn_wallet->validate_address($param);
      
        if($validate['flag'] == 1){
            $balanceResponse;
               $check = $balanceResponse['data']['balance'];
               if($check >= $request->tcn){
                $withdrawalParams = [
                                'to_address' => $request->transaction_number,
                                'amount' =>  $request->tcn, 
                            ];

                            $withdrawalResponse = $tcn_wallet->withdraw($withdrawalParams);
                            if($withdrawalResponse['flag'] == 1){
                                            // return $withdrawalResponse['data']['amount'];
                                            InvestMoney::create([
                                                'user_id'=>Auth::guard('user_login')->user()->id,
                                                'phone_number'=>$request->phone_number,
                                                'transaction_number'=>$request->transaction_number,
                                                'mobile_operator'=>$request->mobile_operator,
                                                'Tk'=>$request->taka,
                                                'img'=>"testing.jpg",
                                                'time_period'=>$request->time_period,
                                    
                                            ]);
                                            return back()->with('success',"successfully Purchased");
                                        }else{
                                            $errorMessage = $withdrawalResponse['msg'];
                                            
                                            return response()->json(['error' => $errorMessage], 500);
                                        }
                    
               }
               else{
                return back()->with('error',"Sorry You Have Not Sufficient Balance");
               }
        }else{
            return back()->with('error',"Sorry Your Address Is Wrong");
        }
       
        
    }
    function invest_money_to_admin(Request $request){
        
         $request->transaction_number;
          InvestMoney::where('transaction_number',$request->transaction_number)->update([
            'time_period'=>$request->month,
         ]);
         return back()->with('success',"Successfully Requested To The Admin");
    }
    public function user_daily_porfit()
{ 
    $invested_money = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
         $today = Carbon::now();
       
         $take = [];
         $allProfitPercentages = ProfitPercentage::all();

        




foreach ($invested_money as $in) {
    $startingDate = Carbon::parse($in->created_at);
    $endDates = $startingDate->copy()->addMonths($in->time_period);

    $profitDates = [];
    $dates = [];

    foreach ($allProfitPercentages as $p) {
        $profitCreatedAt = Carbon::parse($p->created_at)->toDateString();
        $date = Carbon::parse($p->created_at)->toDateString();
        $dates[] = $date;
        $profitDates[$profitCreatedAt] = $p->profit_percentage;
       
    }

     $firstDate = min($dates);
     $lastDate = max($dates);

    $startDate = Carbon::parse($in->created_at)->startOfDay();
    $endDate = Carbon::now();

    $processedDates = [];
    $firstDaySkipped = false; // Flag to indicate whether the first day is skipped

    $period = CarbonPeriod::create($startDate, $endDate);

    foreach ($period as $date) {
        $formattedDate = $date->toDateString();

        if (!$firstDaySkipped) {
            // Skip the first day
            $firstDaySkipped = true;
            continue;
        }

        if ($date->greaterThan($endDates)) {
            InvestMoney::find($in->id)->update([
                'withdraw' => 1,
                'end_package_time' => $endDates,
            ]);
            break;
        }

        if ($date->isWeekend()) {
            continue; // Skip weekends
        }

        if (array_key_exists($formattedDate, $profitDates) && !in_array($formattedDate, $processedDates)) {
            $profitPercentage = $profitDates[$formattedDate];
            "Match found for date: $formattedDate with Profit Percentage: $profitPercentage\n";

            $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                ->whereDate('created_at', $formattedDate)
                ->first();

            if (!$existingDailyProfit) {
                $perr = $profitPercentage / 100;
                $after_per = $perr * $in->Tk;

                DailyProfit::create([
                    'invest_money_id' => $in->id,
                    'invest_user_id' => $in->user_id,
                    'profit_percentage' => $profitPercentage,
                    'profitted_ammount' => $after_per,
                    'created_at' => $formattedDate,
                ]);
            }
        } else {
            // Find the nearest smaller date from $allProfitPercentages
            $nearestSmallerDate = null;
            $nearestSmallerPercentage = null;

            foreach ($allProfitPercentages as $p) {
                $pDate = Carbon::parse($p->created_at)->toDateString();

                if ($pDate < $formattedDate) {
                    if (!$nearestSmallerDate || $nearestSmallerDate < $pDate) {
                        $nearestSmallerDate = $pDate;
                        $nearestSmallerPercentage = $p->profit_percentage;
                    }
                }
            }

            if ($nearestSmallerDate !== null) {
                // Insert data for non-matching dates using the nearest smaller date's profit percentage
                $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                    ->whereDate('created_at', $formattedDate)
                    ->first();

                if (!$existingDailyProfit) {
                    $perr = $nearestSmallerPercentage / 100;
                    $after_per = $perr * $in->Tk;

                    DailyProfit::create([
                        'invest_money_id' => $in->id,
                        'invest_user_id' => $in->user_id,
                        'profit_percentage' => $nearestSmallerPercentage,
                        'profitted_ammount' => $after_per,
                        'created_at' => $formattedDate,
                    ]);
                }
            }
        }

        $processedDates[] = $formattedDate;
    }
}
    $invested_money = InvestMoney::where('user_id', Auth::guard('user_login')->user()->id)->where('status', 1)->get();
    $ddd = [];
    foreach($invested_money as $invest){
        $daily_profits = DailyProfit::where('invest_money_id', $invest->id)
        ->orderBy('created_at', 'asc')
        ->get();
        foreach($daily_profits as $daily_profit){
            $ddd[] =  $daily_profit;
        }
    }
    $total  = 0;
    foreach($ddd as $d){
        $total += $d->profitted_ammount;
    }
     $total;
    

    


    return view('user.daily_profit', [
        'ddd' => $ddd,
    ]);
}
function user_daily_porfit_pertially($id){


    $invested_money = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
         $today = Carbon::now();
       
         $take = [];
         $allProfitPercentages = ProfitPercentage::all();

        




foreach ($invested_money as $in) {
    $startingDate = Carbon::parse($in->created_at);
    $endDates = $startingDate->copy()->addMonths($in->time_period);

    $profitDates = [];
    $dates = [];

    foreach ($allProfitPercentages as $p) {
        $profitCreatedAt = Carbon::parse($p->created_at)->toDateString();
        $date = Carbon::parse($p->created_at)->toDateString();
        $dates[] = $date;
        $profitDates[$profitCreatedAt] = $p->profit_percentage;
       
    }

     $firstDate = min($dates);
     $lastDate = max($dates);

    $startDate = Carbon::parse($in->created_at)->startOfDay();
    $endDate = Carbon::now();

    $processedDates = [];
    $firstDaySkipped = false; // Flag to indicate whether the first day is skipped

    $period = CarbonPeriod::create($startDate, $endDate);

    foreach ($period as $date) {
        $formattedDate = $date->toDateString();

        if (!$firstDaySkipped) {
            // Skip the first day
            $firstDaySkipped = true;
            continue;
        }

        if ($date->greaterThan($endDates)) {
            InvestMoney::find($in->id)->update([
                'withdraw' => 1,
                'end_package_time' => $endDates,
            ]);
            break;
        }

        if ($date->isWeekend()) {
            continue; // Skip weekends
        }

        if (array_key_exists($formattedDate, $profitDates) && !in_array($formattedDate, $processedDates)) {
            $profitPercentage = $profitDates[$formattedDate];
            "Match found for date: $formattedDate with Profit Percentage: $profitPercentage\n";

            $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                ->whereDate('created_at', $formattedDate)
                ->first();

            if (!$existingDailyProfit) {
                $perr = $profitPercentage / 100;
                $after_per = $perr * $in->Tk;

                DailyProfit::createOrUpdate([
                    'invest_money_id' => $in->id,
                    'invest_user_id' => $in->user_id,
                    'profit_percentage' => $profitPercentage,
                    'profitted_ammount' => $after_per,
                    'created_at' => $formattedDate,
                ]);
            }
        } else {
            // Find the nearest smaller date from $allProfitPercentages
            $nearestSmallerDate = null;
            $nearestSmallerPercentage = null;

            foreach ($allProfitPercentages as $p) {
                $pDate = Carbon::parse($p->created_at)->toDateString();

                if ($pDate < $formattedDate) {
                    if (!$nearestSmallerDate || $nearestSmallerDate < $pDate) {
                        $nearestSmallerDate = $pDate;
                        $nearestSmallerPercentage = $p->profit_percentage;
                    }
                }
            }

            if ($nearestSmallerDate !== null) {
                // Insert data for non-matching dates using the nearest smaller date's profit percentage
                $existingDailyProfit = DailyProfit::where('invest_money_id', $in->id)
                    ->whereDate('created_at', $formattedDate)
                    ->first();

                if (!$existingDailyProfit) {
                    $perr = $nearestSmallerPercentage / 100;
                    $after_per = $perr * $in->Tk;

                    DailyProfit::createOrUpdate([
                        'invest_money_id' => $in->id,
                        'invest_user_id' => $in->user_id,
                        'profit_percentage' => $nearestSmallerPercentage,
                        'profitted_ammount' => $after_per,
                        'created_at' => $formattedDate,
                    ]);
                }
            }
        }

        $processedDates[] = $formattedDate;
    }
}
   
     $pro_per =  DailyProfit::where('invest_money_id',$id)->
    get();
    
    $total = 0;
    foreach($pro_per as $ppp){
        $total += $ppp->profitted_ammount;
    }
     $total;

     

    return view('user.user_daily_profit_pertially',[
        'pro_per'=>$pro_per,
        'total'=>$total,
    ]);
}
}
