<?php

namespace App\Http\Controllers;

use App\Models\DailyLevelComission;
use App\Models\DailyProfit;
use App\Models\DailySecondLevelCommission;
use App\Models\InvestMoney;
use App\Models\MoneyModel;
use App\Models\ProfitPercentage;
use App\Models\ReferenceBalanceModel;
use App\Models\ReferWithdrawReq;
use App\Models\RequestWithdrawDailyProfit;
use App\Models\SecondLevelRequestMoney;
use App\Models\SecondLevelTotal;
use App\Models\TotalReferModels;
use App\Models\UserFirstLevelTotal;
use App\Models\UserFirstLevelTotalWithdraws;
use App\Models\UserLogin;
use App\Models\UsersMoneyReqModel;
use App\Models\UserTotalDailyProfit;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserProfittedController extends Controller
{
    //
    function user_profit(){
         // $daily_profit = DailyProfit::where('invest_user_id',Auth::guard('user_login')->user()->id)->get();

         $asdasd = InvestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
         $sssa = 0;
         foreach($asdasd as $sda){
            $sssa += $sda->Tk;
         }
          $sssa;
     
         $first_level = DailyLevelComission::where('user_id',Auth::guard('user_login')->user()->id)->get();
         $second_level = DailySecondLevelCommission::where('user_id',Auth::guard('user_login')->user()->id)->get();
         $refer_balance = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->get();

         $total_second_level = 0;
         $total_daily_lvl = 0;
         $total = 0;
         $total_refer_blce = 0;
         $total_req_refer_blce = 0;

             //Refer Balance

             $total_refer_request = ReferWithdrawReq::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
             $total_refer_request_check = ReferWithdrawReq::where('user_id',Auth::guard('user_login')->user()->id)->where('status',0)->first();
             $total_refer_request_reject = ReferWithdrawReq::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();

             $total_reffer = 0 ;
             foreach($refer_balance as $reee){
               $total_reffer += $reee->after_percentage;
             }
              $total_reffer;

              foreach($total_refer_request as $tas){
               $total_req_refer_blce += $tas->ammount;
              }
               $total_req_refer_blce;

              $too = TotalReferModels::where('user_id',Auth::guard('user_login')->user()->id)->first();
              if($too){
               $too->update([
                  'ammount'=>$total_reffer-$total_req_refer_blce,
               ]);
              }else{
               TotalReferModels::create([
                  'user_id'=>Auth::guard('user_login')->user()->id,
                  'ammount'=>$total_reffer-$total_req_refer_blce,
                 ]);
              }
             


             //End Refer Balance

         $second_total = 0;
         $second_req = 0;
          $secondss = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
           $sas = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',0)->first();
            $reje_se = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();

         foreach($second_level as $second){
            $second_total += $second->seceond_level_commission_ammount_after_per;
         }

         foreach($secondss as $sssa){
            $second_req += $sssa->ammount;
         }
 
         $second_left = $second_total-$second_req;
         
          
         $u_s = SecondLevelTotal::where('user_id',Auth::guard('user_login')->user()->id)->first();
         if ($u_s) {
            $u_s->update([
                'total' => $second_left,
            ]);
        }else{
            SecondLevelTotal::create([
               'user_id'=>Auth::guard('user_login')->user()->id,
               'total'=>$second_left,
             ]);
         }
          



        
         foreach($first_level as $first){
            $total_daily_lvl += $first->fist_level_commission_ammount_after_per;
         }
         foreach($second_level as $second){
            $total_second_level += $second->seceond_level_commission_ammount_after_per;
         }
         foreach($refer_balance as $refff){
            $total_refer_blce += $refff->after_percentage;
         }
         $total_daily_lvl;
         $total_second_level;
          $total;
          $total_refer_blce;


          $ree = RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',0)->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();
          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,
              ]);
          }
          $daily_profit = UserTotalDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->first();
         $daily_reject = RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();


         

         //First Level Commission
          $total_first_level  = DailyLevelComission::where('user_id',Auth::guard('user_login')->user()->id)->get();
          $first_check = UserFirstLevelTotal::where('user_id',Auth::guard('user_login')->user()->id)->first();
          $first_total_withdrwa_req = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
       $sad = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',0)->first();
          $first_level_req = 0;
          $total_first = 0;
          $total_with_req = 0;
          foreach($total_first_level as $tott){
            $total_first += $tott->fist_level_commission_ammount_after_per;
          }
          foreach($first_total_withdrwa_req as $totyy){
            $total_with_req += $totyy->ammount;
          }
           $total_with_req;



          if($first_check){
            UserFirstLevelTotal::find($first_check->id)->update([
               'user_id'=>Auth::guard('user_login')->user()->id,
               'total'=>$total_first-$total_with_req,
            ]);
            
            
          }else{
            UserFirstLevelTotal::create([
               'user_id'=>Auth::guard('user_login')->user()->id,
               'total'=>$total_first-$total_with_req,
             ]);
           
          }
          
      $first_lvl_reject = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();
         

        return view('user.user_profit',[
            'total'=>$total,
            'total_daily_lvl'=>$total_daily_lvl,
            'total_second_level'=>$total_second_level,
            'total_refer_blce'=>$total_refer_blce,
            'ree'=>$ree,
            'daily_profit'=>$daily_profit,
            'daily_reject'=>$daily_reject,
            'first_check'=>$first_check,
            'sad'=>$sad,
            'first_lvl_reject'=>$first_lvl_reject,
            'u_s'=>$u_s,
            'sas'=>$sas,
            'reje_se'=>$reje_se,
            'too'=>$too,
            'total_refer_request_check'=>$total_refer_request_check,
            'total_refer_request_reject'=>$total_refer_request_reject,
            'sssa'=>$sssa,
        ]);
    }
    function request_daily_profit(Request $request){
      $ree = RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',0)->first();
      if($ree){
         if($request->ammount){
            return back()->with('error',"Sorry The Pending Ammount must be accepted by the admin");
         }
      }else{
         RequestWithdrawDailyProfit::create([
            'user_id'=>Auth::guard('user_login')->user()->id,
            'ammount'=>$request->ammount,
            'status'=>0,
         ]);
         return back()->with('success',"Successfully Inserted");
      }
      
    }
    function request_first_level(Request $request){
      UserFirstLevelTotalWithdraws::create([
         'user_id'=>Auth::guard('user_login')->user()->id,
         'ammount'=>$request->ammount,
         'status'=>0,
      ]);
      return back()->with('success',"successfully Requested");
    
    }
    function user_daily_profit_accept(){
       $daily_profit = RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
       $reject_daily_profit = RequestWithdrawDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();
       return view('user.daily_profit_accept',[
         'daily_profit'=>$daily_profit,
         'reject_daily_profit'=>$reject_daily_profit,
       ]);
      
    }
    function first_level_commission_record(){
      $accept  = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
      $reject = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();
      return view('user.first_level_commission_record',[
         'accept'=>$accept,
         'reject'=>$reject,
      ]);
    }
    function request_second_level(Request $request){
      SecondLevelRequestMoney::create([
         'user_id'=>Auth::guard('user_login')->user()->id,
         'ammount'=>$request->ammount,
         'status'=>0,
      ]);
      return back()->with('success',"Successfully Inserted");
    }
    function second_level_commission_record(){
      $accepted = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
      $rejected = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();
     return view('user.second_level_commisiion_record',[
      'accepted'=>$accepted,
      'rejected'=>$rejected,
     ]);
    }
    function req_refer_withdraw(Request $request){
      $checking = TotalReferModels::where('user_id',Auth::guard('user_login')->user()->id)->first();
      if($request->ammount > $checking->ammount){
         return back()->with('error',"You Have Given Much More Than You Have");
      }else{
            ReferWithdrawReq::create([
               'user_id'=>Auth::guard('user_login')->user()->id,
               'ammount'=>$request->ammount,
               'status'=>0
            ]);
            return back()->with('success',"Successfully Requested");
      }

    }
    function refer_record(){
      $accepted = ReferWithdrawReq::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
      $rejected = ReferWithdrawReq::where('user_id',Auth::guard('user_login')->user()->id)->where('status',2)->get();
      return view('user.refer_blnce_record',[
         'accepted'=>$accepted,
         'rejected'=>$rejected,
      ]);
    }
    function user_profile(){
      return view('user.user_profile');
    }
    function user_profile_change(Request $request){
      $request->validate([
         
         'password'=>'required|min:8',
       
      ]);
       $request->name;
       $user = Auth::guard('user_login')->user()->id;
       if($request->name && $request->password){
         UserLogin::find($user)->update([
            'name'=>$request->name,
            'password'=>bcrypt($request->password),
         ]);
         return back()->with('success',"Successfully Changed The Name And The Password");
      }
      elseif($request->password){
               UserLogin::find($user)->update([
                  'password'=>bcrypt($request->password),
               ]);
               return back()->with('success',"Successfully Changed The Password");
      }elseif($request->name){
         UserLogin::find($user)->update([
            'name'=>$request->name,
         ]);
         return back()->with('success',"Successfully Changed The Name");
      }
    
     
    }
    function req_money_frm_cus(Request $request){

      $request->validate([
         
         'ammount'=>'required|integer',
         'transaction_id'=>'required|string'
       
      ]);
    
      UsersMoneyReqModel::create([
         'customer_id'=>Auth::guard('user_login')->user()->id,
         'status'=>'0',
         'ammount'=>$request->ammount,
         'transaction_number'=>$request->transaction_id,
      ]);
      return back()->with('success',"Successfully Inserted");     

    }
    function list_of_req(){

      $list = UsersMoneyReqModel::where('customer_id',Auth::guard('user_login')->user()->id)->get();
      return view('user.req_money_list',[
         'list'=>$list
      ]);
    }
    function lvl1(){
      $daily_level_commission =  DailyLevelComission::where('user_id',Auth::guard('user_login')->user()->id)->get();
      $user_first_level_withdraw = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
      $total_with = 0;
      $total = 0;
      foreach($daily_level_commission as $ddd){
          $total += $ddd->fist_level_commission_ammount_after_per;
      }
      foreach($user_first_level_withdraw as $uuu){
          $total_with += $uuu->ammount;
      }
      
      return view('user.lvl1',[
         'daily_level_commission'=>$daily_level_commission,
            'total'=>$total,
            'total_with'=>$total_with,
      ]);
    }
    function lvl2(){
       $second_level = DailySecondLevelCommission::where('user_id',Auth::guard('user_login')->user()->id)->get();
         $second_level_withdraw = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
         $total_re = 0;
        $total_secon_lvl = 0;
        foreach($second_level as $see){
            $total_secon_lvl += $see->seceond_level_commission_ammount_after_per;
        }
        $total_secon_lvl;
        foreach($second_level_withdraw as $sas){
          $total_re += $sas->ammount;
        }
        $total_re;
      return view('user.lvl2',[
         'second_level'=>$second_level,
            'total_secon_lvl'=>$total_secon_lvl,
            'total_re'=>$total_re,
      ]);
    }
    function ai(){
      $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;
          }
      }
      return view('user.ai',[
         'ddd' => $ddd,
      ]);
    }
    function invite(){
      $sd =  UserLogin::where('Refer_by',Auth::guard('user_login')->user()->Refer_id)->get();

        foreach($sd as $w){
              $ree =  InvestMoney::where('user_id',$w->id)->where('time_period','!=',null)->where('status',1)->get();
            
              
            foreach($ree as $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
                    ]);
                }
                
                   
              
               
            }
        }
        $reference_balance = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->get();
      return view('user.invite',[
         'reference_balance'=>$reference_balance
      ]);
    }
    function total(){
      $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_ai  = 0;
      foreach($ddd as $d){
          $total_ai += $d->profitted_ammount;
      }
       $total_ai;
       //end of total ai

       //start of total invite income

       $sd =  UserLogin::where('Refer_by',Auth::guard('user_login')->user()->Refer_id)->get();

       foreach($sd as $w){
             $ree =  InvestMoney::where('user_id',$w->id)->where('time_period','!=',null)->where('status',1)->get();
           
             
           foreach($ree as $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.05
                   ]);
               }
               
                  
             
              
           }
       }
       $reference_balance = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->get();
       $total_refer = 0;
       foreach($reference_balance as $refer){
         $total_refer += $refer->after_percentage;
       }
       $total_refer;
       //end of refer

       //lvl 1
       $daily_level_commission =  DailyLevelComission::where('user_id',Auth::guard('user_login')->user()->id)->get();
        $user_first_level_withdraw = UserFirstLevelTotalWithdraws::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
        $total_with = 0;
        $total = 0;
        foreach($daily_level_commission as $ddd){
            $total += $ddd->fist_level_commission_ammount_after_per;
        }
        foreach($user_first_level_withdraw as $uuu){
            $total_with += $uuu->ammount;
        }
        //lvl1

        //lvl2
        $second_level = DailySecondLevelCommission::where('user_id',Auth::guard('user_login')->user()->id)->get();
        $second_level_withdraw = SecondLevelRequestMoney::where('user_id',Auth::guard('user_login')->user()->id)->where('status',1)->get();
        $total_re = 0;
       $total_secon_lvl = 0;
       foreach($second_level as $see){
           $total_secon_lvl += $see->seceond_level_commission_ammount_after_per;
       }
       $total_secon_lvl;
       foreach($second_level_withdraw as $sas){
         $total_re += $sas->ammount;
       }
       $total_re;
        //lvl2


        //Total

         $all = $total_ai + $total_refer + $total + $total_secon_lvl;
      return view('user.total',[
         'total_ai'=>$total_ai,
         'total_refer'=>$total_refer,
         'total_lvl_1'=>$total,
         'total_secon_lvl'=>$total_secon_lvl,
         'all'=>$all,
      ]);
    }
    function refer_link(){
      return view('user.refer_link');
    }
    function remaining_deposit(){
      $ms =  MoneyModel::where('customer_id',Auth::guard('user_login')->user()->id)->first();
      if($ms){
         $remain = $ms->total;
      }else{
         $remain = 0;
      }
      
       return view('user.remaining_deposit',[
         'remain'=>$remain,
       ]);
      
    }
}
