<?php

namespace App\Http\Controllers\Admin;
use App\Models\Admin;
use Carbon\Carbon;
use App\Models\Followup;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\UserTimeline;

class DashboardController extends Controller
{
    public function agentDashboard(Request $request)
    {   
      abort_if(!userCan('dashboard.agent'), 403);


      $roleEnvNames = explode(',', env('AVAILABLE_LEAD_ROLES', 'Lead Manager,Operation Manager'));
      $admin_list = Admin::where('id', '!=', 1)
          ->whereHas('roles', function ($query) use ($roleEnvNames) {
              $query->whereIn('name', $roleEnvNames);
          })
          ->get()
          ->toArray();

    //   $admin_list = Admin::where('id', '!=', 1)
    //   ->whereHas('roles', function ($query) {
    //       $query->whereIn('name', ['Lead Manager','Operation Manager']);
    //   })
    //   ->get()->toArray(); 
      return view('admin.Dashboard.agent',compact('admin_list'));
    }


    public function agentDataDashboard(Request $request)
    {
      
        abort_if(!userCan('dashboard.agent'), 403);
        $weekNumber = $request->input('weekSelect');
        $selectMonth = $request->input('monthSelect');
        $yearSelect = $request->input('yearSelect');

        if ($weekNumber == 1) {
            $startDate = date("Y-m-d H:i:s", strtotime("1-" . $selectMonth . "-" . $yearSelect));
            $endDate = date("Y-m-d 23:59:59", strtotime("7-" . $selectMonth . "-" . $yearSelect));
        } elseif ($weekNumber == 2) {
            $startDate = date("Y-m-d H:i:s", strtotime("8-" . $selectMonth . "-" . $yearSelect));
            $endDate = date("Y-m-d 23:59:59", strtotime("14-" . $selectMonth . "-" . $yearSelect));
        } elseif ($weekNumber == 3) {
            $startDate = date("Y-m-d H:i:s", strtotime("15-" . $selectMonth . "-" . $yearSelect));
            $endDate = date("Y-m-d 23:59:59", strtotime("21-" . $selectMonth . "-" . $yearSelect));
        } elseif ($weekNumber == 4) {
            $startDate = date("Y-m-d H:i:s", strtotime("22-" . $selectMonth . "-" . $yearSelect));
            $endDate = date("Y-m-d 23:59:59", strtotime("31-" . $selectMonth . "-" . $yearSelect));
        } else {
            $startDate = Carbon::now()->startOfWeek();
            $endDate = Carbon::now()->endOfWeek();
        }
     
        $timeLineData = UserTimeline::whereBetween('created_at', [$startDate, $endDate])->where("auth_id", $request->admin_list_id)->whereNotIn('user_timeline.stages', ['Inquiry', 'Assign To'])->orderBy("created_at")->get();

        $getStagesArray = get_stages_array();

        $stages = [];
        foreach ($getStagesArray as $stage) {
            if ($stage['name'] != 'Inquiry')
                $stages[] = $stage['name'];
        }

        $dashboardData = [];

        foreach ($timeLineData as $wd) {
            $index = date('d F', strtotime($wd->created_at));

            // stages
            if (!isset($dashboardData[$index])) {
                foreach ($stages as $stage) {
                    if (!isset($dashboardData[$index][$stage])) {
                        $dashboardData[$index][$stage] = 0;
                    }
                }
            }

            // if ($wd->stages != null && in_array($wd->stages, $stages)) {
            //     if (isset($dashboardData[$index][$wd->stages])) {
            //         $dashboardData[$index][$wd->stages]++;
            //     } else {
            //         $dashboardData[$index][$wd->stages] = 1;
            //     }
            // }

            if (isset($dashboardData[$index][$wd->stages])) {
                $dashboardData[$index][$wd->stages]++;
            } else {
                $dashboardData[$index][$wd->stages] = 1;
            }
        }

        // dd($dashboardData);
        return response()->json($dashboardData);

  
  }  



  public function agentGetDailyData(Request $request)
  {
  
      abort_if(!userCan('dashboard.agent'), 403);
      $selectMonth = $request->input('selectMonth');
      $yearSelect = $request->input('yearSelect');

      $startDate = Carbon::create($yearSelect, $selectMonth, 1)->startOfDay();
      $endDate = $startDate->copy()->endOfMonth()->endOfDay();

      $followups = Followup::whereBetween('created_at', [$startDate, $endDate])->where("assign_to", $request->admin_list_id)->orderBy("created_at")->get();

      $totalfollowups = $followups->count();
      $userCount = 0;
      $uniqueUserIds = []; 
      foreach ($followups as $followup) {
          if (!in_array($followup['user_id'], $uniqueUserIds)) {
              $uniqueUserIds[] = $followup['user_id'];
              $userCount++;
          }
      }

      $dashboardData = [
          'totalfollowups' => $totalfollowups,
          'totalusers' =>  $userCount,
      ];

      return response()->json($dashboardData);
  }


  public function agentGetWeeklyData(Request $request)
  {
    
      abort_if(!userCan('dashboard.agent'), 403);
      $weekNumber = $request->input('weekSelect');
      $selectMonth = $request->input('monthSelect');
      $yearSelect = $request->input('yearSelect');

      $now = Carbon::now();
      $startOfMonth = $now->startOfMonth();


      if ($weekNumber == 1) {
          $startDate = date("Y-m-d H:i:s", strtotime("1-" . $selectMonth . "-" . $yearSelect));
          $endDate = date("Y-m-d 23:59:59", strtotime("7-" . $selectMonth . "-" . $yearSelect));
      } elseif ($weekNumber == 2) {
          $startDate = date("Y-m-d H:i:s", strtotime("8-" . $selectMonth . "-" . $yearSelect));
          $endDate = date("Y-m-d 23:59:59", strtotime("14-" . $selectMonth . "-" . $yearSelect));
      } elseif ($weekNumber == 3) {
          $startDate = date("Y-m-d H:i:s", strtotime("15-" . $selectMonth . "-" . $yearSelect));
          $endDate = date("Y-m-d 23:59:59", strtotime("21-" . $selectMonth . "-" . $yearSelect));
      } elseif ($weekNumber == 4) {
          $startDate = date("Y-m-d H:i:s", strtotime("22-" . $selectMonth . "-" . $yearSelect));
          $endDate = date("Y-m-d 23:59:59", strtotime("31-" . $selectMonth . "-" . $yearSelect));
      } else {
          $startDate = Carbon::now()->startOfWeek();
          $endDate = Carbon::now()->endOfWeek();
      }

      $timeLineData = Followup::whereBetween('created_at', [$startDate, $endDate])->where("assign_to", $request->admin_list_id)->orderBy("created_at")->get();
        // dd($timeLineData->toArray());
      $getStagesArray = get_followup_type_array();
      $totalFollowup = $timeLineData->count();
      $userCount = 0;
      $uniqueUserIds = []; 
      foreach ($timeLineData as $followup) {
          if (!in_array($followup['user_id'], $uniqueUserIds)) {
              $uniqueUserIds[] = $followup['user_id'];
              $userCount++;
          }
      }

      $stages = [];
      foreach ($getStagesArray as $stage) {  
          // if ($stage['name'] != 'Inquiry')
              $stages[] = $stage['name'];
      // }
      }
      $dashboardData = [];
   
   
     
      foreach ($timeLineData as $wd){

          $index = date('d F', strtotime($wd->created_at));
        
          // stages
          if (!isset($dashboardData[$index])) {
              $dashboardData[$index] = [
                  'totalFollowUP' => 0,
                  'totalUsers' => 0,
              ];
              foreach ($stages as $stage) {
                  if (!isset($dashboardData[$index][$stage])) {
                      $dashboardData[$index][$stage] = 0;
                  }
              }
            
          }

  
          $dashboardData[$index]['totalFollowUP']++;

          if (is_object($wd) && isset($wd->user) && is_object($wd->user) && isset($wd->type)) {
            if (isset($dashboardData[$index][$wd->type])) {
                $dashboardData[$index][$wd->type]++;
            } else {
                $dashboardData[$index][$wd->type] = 1;
            }
            if (!isset($uniqueUserIds[$index][$wd->user_id])) {
              $uniqueUserIds[$index][$wd->user_id] = true;
              $dashboardData[$index]['totalUsers']++;
             }

          }else {
              if (!isset($uniqueUserIds[$index][$wd->user_id])) {
                  $uniqueUserIds[$index][$wd->user_id] = true;
                  $dashboardData[$index]['totalUsers']++;
                 }
          }
       
      //   $dashboardData[$index]['totalFollowUP'] =  $totalLeads;
        
      }     

      // return response()->json($dashboardData);
      $data2['userCount'] =  $userCount;
      $data2['totalFollowup'] =  $totalFollowup;
      return response()->json([
          'data' => $dashboardData,
          'data2' => $data2
      ]);
 
  }


//   public function agentGetMonthlyData(Request $request)
//   {
   
//     //   abort_if(!userCan('dashboard.monthly_details'), 403);
//       $selectMonth = $request->input('selectMonth');
//       $yearSelect = $request->input('yearSelect');

//       $startDate = Carbon::create($yearSelect, $selectMonth, 1)->startOfDay();
//       $endDate = $startDate->copy()->endOfMonth()->endOfDay();

//       $followups = Followup::whereBetween('created_at', [$startDate, $endDate])->where("assign_to", $request->admin_list_id)->orderBy("created_at")->get();

//       $totalfollowups = $followups->count();
//       $userCount = 0;
//       $uniqueUserIds = []; 
//       foreach ($followups as $followup) {
//           if (!in_array($followup['user_id'], $uniqueUserIds)) {
//               $uniqueUserIds[] = $followup['user_id'];
//               $userCount++;
//           }
//       }

//       $dashboardData = [
//           'totalfollowups' => $totalfollowups,
//           'totalusers' =>  $userCount,
//       ];

//       return response()->json($dashboardData);
//   }


  public function agentGetMonthlyData(Request $request)
  {
      abort_if(!userCan('dashboard.agent'), 403);
      $selectMonth = $request->input('selectMonth');
      $yearSelect = $request->input('yearSelect');

      $startDate = Carbon::create($yearSelect, $selectMonth, 1)->startOfDay();
      $endDate = $startDate->copy()->endOfMonth()->endOfDay();

        $followups = Followup::whereBetween('created_at', [$startDate, $endDate])->where("assign_to", $request->admin_list_id)->orderBy("created_at")->get();

        $totalfollowups = $followups->count();
        $userCount = 0;
        $uniqueUserIds = []; 
        foreach ($followups as $followup) {
            if (!in_array($followup['user_id'], $uniqueUserIds)) {
                $uniqueUserIds[] = $followup['user_id'];
                $userCount++;
            }
        }

        $monthlyData = UserTimeline::join('users', 'user_timeline.user_id', '=', 'users.id')
        ->join('candidates', 'candidates.user_id', '=', 'users.id')
        ->whereBetween('user_timeline.created_at', [$startDate, $endDate])
        ->where("user_timeline.stages", "!=", "Assign To")
        ->where("users.assign_to", $request->admin_list_id)
        ->select('users.name as name', 'candidates.id as candidate_id', 'user_timeline.*',)
        ->get();


        $documentReceived = 0;
        $applicationSubmitted = 0;
        $uniOfferReceived = 0;
        $uniOfferAccepted = 0;

        $documentReceived_UserDetails = 0;
        $applicationSubmitted_UserDetails = 0;
        $uniOfferReceived_UserDetails = 0;
        $uniOfferAccepted_UserDetails = 0;
     
        if ($totalfollowups > 0) {

            $documentReceived = $monthlyData->whereIn('stages', ['University to be suggested', 'Documents Received','Application ready to submit'])->groupBy('user_id')->count();
            $applicationSubmitted = $monthlyData->where('stages', 'Application submitted')->groupBy('user_id')->count();
            $uniOfferReceived = $monthlyData->whereIn('stages', ['Offer Issued','Offer Accepted','Offer Rejected'])->groupBy('user_id')->count();
            $uniOfferAccepted = $monthlyData->where('stages', 'Admitted')->groupBy('user_id')->count();

            // $applicationSubmitted_UserDetails = $monthlyData->where('stages', 'Application submitted')->all();
            $applicationSubmitted_UserDetails = collect($monthlyData)->where('stages', 'Application submitted')->groupBy('user_id')
            ->map(function ($groupedItems) {
                return $groupedItems->first(); 
            })
            ->toArray(); 

            $documentReceived_UserDetails = collect($monthlyData)->whereIn('stages', ['University to be suggested','Documents Received','Application ready to submit'])->groupBy('user_id')
            ->map(function ($groupedItems) {
                return $groupedItems->first(); 
            })
            ->toArray(); 
            
            $uniOfferReceived_UserDetails = collect($monthlyData)->whereIn('stages', ['Offer Issued','Offer Accepted','Offer Rejected'])->groupBy('user_id')
            ->map(function ($groupedItems) {
                return $groupedItems->first(); 
            })
            ->toArray(); 

            $uniOfferAccepted_UserDetails = collect($monthlyData)->where('stages', 'Admitted')->groupBy('user_id')
            ->map(function ($groupedItems) {
                return $groupedItems->first(); 
            })
            ->toArray(); 
        }
    
        $dashboardData = [
            'totalfollowups' => $totalfollowups,
            'totalusers' =>  $userCount,
            'documentReceived' => $documentReceived,
            'applicationSubmitted' => $applicationSubmitted,
            'uniOfferReceived' => $uniOfferReceived,
            'uniOfferAccepted' => $uniOfferAccepted,
            'applicationSubmitted_UserDetails' => $applicationSubmitted_UserDetails,
            'documentReceived_UserDetails' => $documentReceived_UserDetails,
            'uniOfferReceived_UserDetails' => $uniOfferReceived_UserDetails,
            'uniOfferAccepted_UserDetails' => $uniOfferAccepted_UserDetails,
        ];

      return response()->json($dashboardData);
  }



  public function getMonthlyDataApplication(Request $request)
  {
   
      $selectMonth = $request->input('selectMonth');
      $yearSelect = $request->input('yearSelect');

      $startDate = Carbon::create($yearSelect, $selectMonth, 1)->startOfDay();
      $endDate = $startDate->copy()->endOfMonth()->endOfDay();


    //   $monthlyData = UserTimeline::whereBetween('created_at', [$startDate, $endDate])
    //   ->where("auth_id", $request->admin_list_id)->get();

      $applicationSubmitted = 0;

      $monthlyData = UserTimeline::join('users', 'user_timeline.user_id', '=', 'users.id')
      ->whereBetween('user_timeline.created_at', [$startDate, $endDate])
    //   ->where('user_timeline.auth_id', $request->admin_list_id)
      ->where('users.assign_to', $request->admin_list_id)
      ->whereNotNull('users.assign_to')
      ->where('user_timeline.stages', 'Application submitted')
      ->count();

      $applicationSubmitted = $monthlyData;

    //   $applicationSubmitted = $monthlyData->where('stages', 'Application submitted')->count();
 

      $dashboardData = [
          'applicationSubmitted' => $applicationSubmitted,
      ];

      return response()->json($dashboardData);
  }

  public function getMonthlyDataConversion(Request $request)
  {
   
      $selectMonth = $request->input('selectMonth');
      $yearSelect = $request->input('yearSelect');

      $startDate = Carbon::create($yearSelect, $selectMonth, 1)->startOfDay();
      $endDate = $startDate->copy()->endOfMonth()->endOfDay();


    //   $monthlyData = UserTimeline::whereBetween('created_at', [$startDate, $endDate])
    //   ->where("auth_id", $request->admin_list_id)->get();

        $applicationAdmitted = 0;
        $monthlyData = UserTimeline::join('users', 'user_timeline.user_id', '=', 'users.id')
        ->whereBetween('user_timeline.created_at', [$startDate, $endDate])
        // ->where('user_timeline.auth_id', $request->admin_list_id)
        ->where('users.assign_to', $request->admin_list_id)
        ->whereNotNull('users.assign_to')
        ->where('user_timeline.stages', 'Admitted')
        ->count();
   
        $applicationAdmitted = $monthlyData;


      $dashboardData = [
          'applicationAdmitted' => $applicationAdmitted,
        
      ];

      return response()->json($dashboardData);
  }



    
}
