<?php

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

use App\Http\Controllers\Controller;
use App\Quarter;
use App\SalesHistory;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Api\Http\Requests\Analytics\UsersBasedQuarterListRequest;

class UsersBasedQuarterAnalyticsController extends Controller
{
    public function index(UsersBasedQuarterListRequest $request)
    {
        $request_from = $request->request_from;
        $request_to = $request->request_to;


        $branch_head_id = $request->branch_head_id;
        $sales_person_id = $request->sales_person_id;
        $team_leader_id = $request->team_leader_id;

        $quarter_from =  Quarter::where('name', $request_from)->first();
        $quarter_to =  Quarter::where('name', $request_to)->first();

        $totalSales = SalesHistory::select(
            DB::raw('SUM(sale_value) as total_sale_value'),
            DB::raw('COUNT(id) as total_sale_count')
        )
            ->whereNotNull('quarter')
            ->where('quarter', '<>', '')
            ->whereBetween('sale_date', [$quarter_from->date_from, $quarter_to->date_to])
            ->when(auth()->user()->hasRole('sales-head'), function ($query) {
                $query->where('branch_head_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('team-leader'), function ($query) {
                $query->where('team_leader_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('executive'), function ($query) {
                $query->where('sales_person_id', auth()->user()->id);
            })
            ->first();

        $totalSaleCountAll = SalesHistory::whereBetween('sale_date', [$quarter_from->date_from, $quarter_to->date_to])
            ->whereNotNull('quarter')
            ->where('quarter', '<>', '')
            ->when(auth()->user()->hasRole('sales-head'), function ($query) {
                $query->where('branch_head_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('team-leader'), function ($query) {
                $query->where('team_leader_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('executive'), function ($query) {
                $query->where('sales_person_id', auth()->user()->id);
            })
            ->count('id');





        $date1 = Carbon::createFromDate($quarter_from->date_from);
        $date2 = Carbon::createFromDate($quarter_to->date_to);
        $monthsDifference = $date1->diffInMonths($date2);
        $color_code = [
            '#4285F4',
            '#EA4335',
            '#FBBC05',
            '#23DAE5',
            '#4A34BE',
            '#1CC96D',
            '#FF9228',
            '#279548',
        ];

        $quarters = SalesHistory::select('quarter', DB::raw('SUM(sale_value) as total_sale_value'))
            ->whereNotNull('quarter')
            ->where('quarter', '<>', '')
            ->whereBetween('sale_date', [$quarter_from->date_from, $quarter_to->date_to])
            ->when(auth()->user()->hasRole('sales-head'), function ($query) {
                $query->where('branch_head_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('team-leader'), function ($query) {
                $query->where('team_leader_id', auth()->user()->id);
            })
            ->when(auth()->user()->hasRole('executive'), function ($query) {
                $query->where('sales_person_id', auth()->user()->id);
            })
            ->groupBy('quarter')
            ->havingRaw('quarter IS NOT NULL')
            ->orderByRaw("SUBSTRING_INDEX(quarter, '-', -1) ASC")
            ->get()
            ->map(function ($item, $index) use ($color_code) {
                $colorIndex = $index % count($color_code);

                if ($item->total_sale_value >= 10000000) {
                    $totalsalevalue =  round($item->total_sale_value /  10000000) . ' cr';
                } elseif (($item->total_sale_value > 99999) && ($item->total_sale_value < 10000000)) {
                    $totalsalevalue =  round($item->total_sale_value /  100000) . ' lakh';
                } else {
                    $totalsalevalue = $item->total_sale_value;
                }


                return [
                    'quarter_name' => $item->quarter,
                    'total_sale_value' => strval($totalsalevalue)  ?? '0',
                    'color_code' => $color_code[$colorIndex],
                ];
            })
            ->toArray();



        if ($totalSales->total_sale_value >= 10000000) {
            $total_sale_value =  round($totalSales->total_sale_value /  10000000) . ' cr';
        } elseif (($totalSales->total_sale_value > 99999) && ($totalSales->total_sale_value < 10000000)) {
            $total_sale_value =  round($totalSales->total_sale_value /  100000) . ' lakh';
        } else {
            $total_sale_value = $totalSales->total_sale_value;
        }

        $avrg_tot = round($totalSales->total_sale_value / $monthsDifference);


        if ($avrg_tot >= 10000000) {
            $avrg_tot = round($avrg_tot /  10000000) . ' Cr';
        } elseif (($avrg_tot > 99999) && ($avrg_tot < 10000000)) {
            $avrg_tot = round($avrg_tot /  100000) . ' Lakh';
        } else {
            $avrg_tot;
        }

        $jsonData = [
            'success' => true,
            'message' => '',
            'data' => [
                'total_sale' => strval($totalSales->total_sale_count) ?? '0',
                'total_sale_value' => strval($total_sale_value) ?? '0',
                'tenure' => strval($monthsDifference) ?? '0',
                'average_sale_value_tenure' => strval($avrg_tot) ?? '0',
                'quarters' => $quarters,
            ],
        ];

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