<?php

namespace App\Api\Http\Controllers\Api\V2\Users;

use App\Api\Http\Requests\Task\TaskListRequest;
use App\Api\Http\Resources\Tasks\TaskCollection;
use App\Api\Http\Resources\User\UserCollection;
use App\Http\Controllers\Controller;
use App\Lead;
use App\Quarter;
use App\SalesActivity;
use App\Source;
use App\Task;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;

class TeamLeaderController extends Controller
{
    public function TeamLeaderEfficiency(Request $request){

        $teamLeadersEfficiency = [];
    
        $teamleaders = User::with(['roles'])
            ->whereHas('roles', function ($q) {
                $q->where('role_id', 7);
            })->where('status',1)->get();
    
        $lists = $request->list;
        $week = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday()->toDateString();
        $seven = Carbon::today()->subDays(7);
        $currentDate = date('Y-m-d');
        $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();
            
            if($quarter){
                $from_date = $quarter->date_from;
                $to_date = $quarter->date_to;
            }
    
        foreach($teamleaders as $teamleader){
    
            $all_reporting_users_id_array = $teamleader->getAllReportingUsersIds();
            array_push($all_reporting_users_id_array, $teamleader->id);
    
            $tasks = Task::whereIn('created_by', $all_reporting_users_id_array)
                ->where('task_completed_status', 1)
                ->when($lists == 1, function ($query) {
                    $query->whereDate('schedule_date', today());
                })
                ->when($lists == 2, function ($query) use ($week) {
                    $query->whereDate('schedule_date', '>=', $week);
                })
                ->when($lists == 3, function ($query) use ($month) {
                    $query->whereDate('schedule_date', '>=', $month);
                })
                ->when($lists == 4, function ($query) use ($request) {
                    $from = $request->from_date;
                    $to = $request->to_date;
                    $query->whereBetween('schedule_date', [$from, $to]);
                })
                ->when($lists == 5, function ($query) use ($yesterday) {
                    $query->whereDate('schedule_date', '=', $yesterday);
                })
                ->when($lists == 6, function ($query) {
                    $query->whereBetween('schedule_date', ['2023-11-20', '2023-12-31']);
                })
                ->when($lists == 7, function ($query) use ($seven) {
                    $query->whereDate('schedule_date', '>=', $seven);
                })
                ->when($lists == 8, function ($query) use($from_date, $to_date){
                    $query->whereBetween('schedule_date', [$from_date, $to_date]);
                })
                ->whereIn('create_task_id', [2, 3, 13, 14, 12])
                ->where(function ($query) {
                    $query->whereIn('create_task_id', [2, 3, 13, 14, 12])
                        ->where('team_leader_approved', 1);
                })->get();
    
            $activityCount = $tasks->count();
            $convertedCount = 0;
    
            foreach ($tasks as $task){
                $sale = SalesActivity::where('lead_id', $task->lead_id)
                    ->whereNotIn('is_verified', [0, 5])
                    ->count();
    
                $convertedCount += $sale;
            }
    
            $convertedPercentage = ($activityCount > 0) ? round(($convertedCount / $activityCount) * 100, 2) . '%' : '0%';
            $pdfUrl = route('teamLeader.workReport.pdfnew', $teamleader->id);
    
            $teamLeadersEfficiency[] = [
                'team_leader' => strval($teamleader->name) ?? '',
                'Activity_count' => strval($activityCount),
                'Activity_converted' => strval($convertedCount),
                'converted_percentage' => strval($convertedPercentage),
                'report' =>  $pdfUrl,
            ];
        }

        usort($teamLeadersEfficiency, function ($a, $b) {
            $percentageA = floatval($a['converted_percentage']);
            $percentageB = floatval($b['converted_percentage']);
    
            return $percentageB <=> $percentageA;
        });

        $efficiencyPdf = route('teamLeader.workReport.allPdfnew');
    
        $response = [
            'status' => true,
            'message' => 'success',
            'data' => [
                
                    'efficiency_pdf' => $efficiencyPdf,
                    'efficiency' => $teamLeadersEfficiency,
                
            ],
        ];
    
        return response()->json($response);
    }

    public function sourceEfficiency(Request $request)
    {
        $lists = $request->list;
        $week = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday()->toDateString();
        $seven = Carbon::today()->subDays(7);
        $currentDate = date('Y-m-d');
        $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();
            
            if($quarter){
                $from_date = $quarter->date_from;
                $to_date = $quarter->date_to;
            }

        $sources = Source::with(['getLeads' => function ($query) use ($lists, $week, $month, $yesterday,$seven, $from_date, $to_date, $request) {
            $query->when($lists == 1, function ($query) {
                $query->whereDate('lead_date', today());
                })
                ->when($lists == 2, function ($query) use ($week) {
                    $query->whereDate('lead_date', '>=', $week);
                })
                ->when($lists == 3, function ($query) use ($month) {
                    $query->whereDate('lead_date', '>=', $month);
                })
                ->when($lists == 4, function ($query) use ($request) {
                    $from = $request->from_date;
                    $to = $request->to_date;
                    $query->whereBetween('lead_date', [$from, $to]);
                })
                ->when($lists == 5, function ($query) use ($yesterday) {
                    $query->whereDate('lead_date', '=', $yesterday);
                })
                ->when($lists == 6, function ($query) {
                    $query->whereBetween('lead_date', ['2023-11-20', '2023-12-31']);
                })
                ->when($lists == 7, function ($query) use ($seven) {
                    $query->whereDate('lead_date', '>=', $seven);
                })
                ->when($lists == 8, function ($query) use($from_date, $to_date){
                    $query->whereBetween('lead_date', [$from_date, $to_date]);
                });
            }])
            ->where('report_status', 1)
            ->get();

        $result = $sources->map(function ($source) {
            $convertedCount = 0;

            $leadIds = $source->getLeads->pluck('id')->toArray();

            $sales = SalesActivity::whereIn('lead_id', $leadIds)
                ->whereNotIn('is_verified', [0, 5])
                ->groupBy('lead_id')
                ->get(['lead_id', \DB::raw('COUNT(*) as count')]);

            foreach ($sales as $sale) {
                $convertedCount += $sale->count;
            }

            $convertedPercentage = ($source->getLeads->count() > 0) ? round(($convertedCount / $source->getLeads->count()) * 100, 2) . '%' : '0%';

            return [
                'lead_source' => $source->name,
                'lead_generated' => (string) $source->getLeads->count(),
                'lead_converted' => (string) $convertedCount,
                'converted_percentage' => $convertedPercentage,
            ];
        });
        
        $sort = $result->sortByDesc(function ($item) {
            return floatval($item['converted_percentage']);
        })->values()->all();
    
        return response()->json([
            'lead_analysis' => $sort
        ]);
    }
}

