<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\Sendmail;
use App\Models\AdminModel;
use App\Models\DailyProfit;
use App\Models\InvestMoney;
use App\Models\Money_model_withdraw;
use App\Models\MoneyModel;
use App\Models\ProfitPercentage;
use App\Models\SecondLevelTotal;
use App\Models\TotalIncomeModel;
use App\Models\TotalReferModels;
use App\Models\UserFirstLevelTotal;
use App\Models\UserLogin;
use App\Models\UsersMoneyReqModel;
use App\Models\UserTotalDailyProfit;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Support\Facades\Auth;

class MailControlller extends Controller
{
    //
    public function index(){
        $mailData = [
            'title'=>'MianwaliCodeHouse',
            'body'=>'This mail is for test',

        ];
        Mail::to('eidascheaugeste@gmail.com')->send(new Sendmail($mailData));
        echo "mail send successfully";
    }
    
    

    

    public function n_level_test() {
        $user = Auth::guard('user_login')->user();
        $referralData = $this->printReferralLevels($user->Refer_id);
    
        return view('user.n_level', compact('referralData'));
    }
    
    private function printReferralLevels($referId, $indentation = "") {
        $referrals = UserLogin::where('Refer_by', $referId)->get();
        $data = [];
    
        foreach ($referrals as $referral) {
        
            $data[] = [
                'id' => $referral->id,
                'indentation' => $indentation,
                'investments' => InvestMoney::where('user_id', $referral->id)->get(),
            ];
            //  $data['investments'];
    
            $data = array_merge($data, $this->printReferralLevels($referral->Refer_id, $indentation . "&nbsp;&nbsp;&nbsp;"));
        }
    
        return $data;
    }
    public function getWalletBalance(Request $request)
    {
        // For testing, simply return a "Hello" message
        if ($request->wallet_type == 'deposit') {
            $ms = MoneyModel::where('customer_id', Auth::guard('user_login')->user()->id)->first();
            $balance = $ms ? $ms->total : 0; // Assuming 'total' is the property you want to retrieve

            return response()->json(['balance' => $balance]);
        } elseif($request->wallet_type == 'select_option'){
            return response()->json(['balance' => 0.00]);
        }
        else {
            // $daily_profit = UserTotalDailyProfit::where('user_id',Auth::guard('user_login')->user()->id)->first();
            // $total_daily_profit = $daily_profit->total;
            // $first = UserFirstLevelTotal::where('user_id',Auth::guard('user_login')->user()->id)->first();
            // $total_first_level = $first->total;
            // $second = SecondLevelTotal::where('user_id',Auth::guard('user_login')->user()->id)->first();
            // $second_total = $second->total;
            // $refer = TotalReferModels::where('user_id',Auth::guard('user_login')->user()->id)->first();
            // $total_refer = $refer->ammount;
            // $totals = $total_daily_profit + $total_first_level +  $second_total + $total_refer;
            $t = TotalIncomeModel::where('user_id',Auth::guard('user_login')->user()->id)->first();
            $totals = $t->total;
            return response()->json(['balance' => $totals]);
        }
    }
function withdraw_request(Request $request){
    
    $ms = MoneyModel::where('customer_id', Auth::guard('user_login')->user()->id)->first();
    if($ms){

   
    if($request->ammount >30){
        $per = $request->ammount * 0.05;
        $after_per =  $request->ammount - $per;
        if($ms->total >= $request->ammount){
            if($request->wallettypes == "deposit"){
                Money_model_withdraw::create([
                  'user_id'=>Auth::guard('user_login')->user()->id,
                  'email'=>$request->email,
                  'requested_money'=>$request->ammount ,
                  'wallet_type'=>'deposit',
                  'status'=>'requested',
                ]);
                return back()->with('success',"Successfully Requested");
              }
        }else{
            return back()->with('error',"Sorry You Have Entered Much More Than You Have");
        }
        $t = TotalIncomeModel::where('user_id',Auth::guard('user_login')->user()->id)->first();
    $totals = $t->total;
    if($t->total >= $request->ammount){
        if($request->wallettypes == "balance"){
           
            Money_model_withdraw::create([
              'user_id'=>Auth::guard('user_login')->user()->id,
              'email'=>$request->email,
              'requested_money'=>$request->ammount  ,
              'wallet_type'=>'balance',
              'status'=>'requested',
            ]);
            return back()->with('success',"Successfully Requested");
          }
    }else{
        return back()->with('error',"Sorry You Have Entered Much More Than You Have");
    }
    
    }
}else{
    return back()->with('error',"Sorry Something is problem");
}
    

    
}
function accept_deposit($id){
     $money = Money_model_withdraw::find($id);
     $money->requested_money;
     $ms = MoneyModel::where('customer_id', $money->user_id)->first();
      $ms->total-$money->requested_money;
    Money_model_withdraw::find($id)->update([
        'status'=>'accepted'
    ]);
    $ms->update([
        'total'=>$ms->total-$money->requested_money,
    ]);
    return back()->with('success',"Successfully Accepted");
 
}
function reject_deposit($id){
    $money = Money_model_withdraw::find($id);
    $ms = MoneyModel::where('customer_id', $money->user_id)->first();
    if($money->status == 'accepted'){
        $ms->total+$money->requested_money;
        $ms->update([
            'total'=> $ms->total+$money->requested_money,
        ]);
        $money->update([
            'status'=>'rejected',
        ]);

    }
    return back()->with('success',"Successfully Rejected");
    
}
function reject_balance($id){
    $money = Money_model_withdraw::find($id);
     $ms = TotalIncomeModel::where('user_id', $money->user_id)->first();
    if($money->status == 'accepted'){
        $ms->total+$money->requested_money;
        $ms->update([
            'total'=> $ms->total+$money->requested_money,
        ]);
        $money->update([
            'status'=>'rejected',
        ]);

    }
    return back()->with('success',"Successfully Rejected");
}
    
   function balance_withdraw(){
   $money =  Money_model_withdraw::where('wallet_type','balance')->get();
    return view('Admin.balance_withdraw',[
        'money'=>$money,
    ]);
   }

   function accept_balance($id){
    $m = Money_model_withdraw::find($id);

    $t = TotalIncomeModel::where('user_id',$m->user_id)->first();

    $m->update([
        'status'=>'accepted',
    ]);
    $t->update([
        'total'=>$t->total - $m->requested_money,
    ]);
    return back()->with('success',"Successfully Accepted");
   }
    
   function send_money_by_admin(Request $request,$id){
    UsersMoneyReqModel::create([
        'customer_id'=>$id,
        'status'=>1,
        'ammount'=>$request->ammount,
        'transaction_number'=>'by_admin',
    ]);
    $total = 0;
    $money = UsersMoneyReqModel::where('customer_id',$id)->where('status',1)->get();
    foreach($money as $mm){
        $total += $mm->ammount;
    }
    $invest = 0;
    $in = InvestMoney::where('user_id',$id)->get();
    foreach($in as $i){
        $invest += $i->Tk;
    }
    $l = MoneyModel::where('customer_id',$id)->first();
    if($l){
        $l->update([
            'total'=>$total - $invest,
        ]);
    }else{
        MoneyModel::create([
            'customer_id'=>$id,
            'total'=>$request->ammount
        ]);
    }

   
    return back()->with('success',"Successfully Inserted");
   }
function admin_logout(){
    Auth::guard('admin_login')->logout();
    return redirect()->route('admin.login');
}


function practise_daily(){
    $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->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;
}
}
}
   
}
