<?php

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

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

class QuarterAnalyticsController extends Controller
{
    public function index(QuarterListRequest $request)
    {
        $request_from = $request->request_from;
        $request_to = $request->request_to;
        if (auth()->user()->hasRole('sales-head')) {
            $branch_head_id = auth()->user()->id;
        } else {
            $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(DISTINCT sale_id) as total_sale_count')
        )
            ->whereNotNull('quarter')
            ->where('quarter', '<>', '')
            ->whereIn('quarter', [$quarter_from->name, $quarter_to->name])
            ->when($branch_head_id, function ($query) use ($branch_head_id) {
                return $query->where('branch_head_id', $branch_head_id);
            })
            ->when($team_leader_id, function ($query) use ($team_leader_id) {
                return $query->where('team_leader_id', $team_leader_id);
            })
            ->when($sales_person_id, function ($query) use ($sales_person_id) {
                return $query->where('sales_person_id', $sales_person_id);
            })
            ->when(
                $branch_head_id = '' && $team_leader_id = '' && $sales_person_id = '',
                function ($query) {
                    $query->where('user_active', 1);

                    return $query->orWhere('team_active', 1);
                }
            )
            ->first();

        // $totalSaleCountAll = SalesHistory::whereIn('quarter', [$quarter_from->name, $quarter_to->name])
        //     ->whereNotNull('quarter')
        //     ->where('quarter', '<>', '')
        //     ->when($branch_head_id, function ($query) use ($branch_head_id) {
        //         return $query->where('branch_head_id', $branch_head_id);
        //     })
        //     ->when($team_leader_id, function ($query) use ($team_leader_id) {
        //         return $query->where('team_leader_id', $team_leader_id);
        //     })
        //     ->when($sales_person_id, function ($query) use ($sales_person_id) {
        //         return $query->where('sales_person_id', $sales_person_id);
        //     })
        //     ->when(
        //         $branch_head_id = '' && $team_leader_id = '' && $sales_person_id = '',
        //         function ($query) {
        //             $query->where('user_active', 1);

        //             return $query->orWhere('team_active', 1);
        //         }
        //     )
        //     ->count('id');

        $date1 = Carbon::createFromDate($quarter_from->date_from);
        $date2 = Carbon::createFromDate($quarter_to->date_to);
        if ($date1->lessThan($date2)) {
            $smallerDate = $date1;
            $greaterDate = $date2;
        } else {
            $smallerDate = Carbon::createFromDate($quarter_to->date_from);
            $greaterDate = Carbon::createFromDate($quarter_from->date_to);
        }
        
        $monthsDifference = $smallerDate->diffInMonths($greaterDate);

        $quarters = Quarter::whereDate('date_from', '>=', $smallerDate)
            ->whereDate('date_to', '<=', $greaterDate)
            ->count();
       
        $monthsDifference = $quarters * 3;


        $color_code = [
            '#4285F4',
            '#EA4335',
            '#FBBC05',
            '#23DAE5',
            '#4A34BE',
            '#1CC96D',
            '#FF9228',
            '#279548',
        ];

        $quarters = SalesHistory::select('*', DB::raw('SUM(sale_value) as total_sale_value'))
            ->whereNotNull('quarter')
            ->where('quarter', '<>', '')
            ->whereIn('quarter', [$quarter_from->name, $quarter_to->name])
            ->when($branch_head_id, function ($query) use ($branch_head_id) {
                return $query->where('branch_head_id', $branch_head_id);
            })
            ->when($team_leader_id, function ($query) use ($team_leader_id) {
                return $query->where('team_leader_id', $team_leader_id);
            })
            ->when($sales_person_id, function ($query) use ($sales_person_id) {
                return $query->where('sales_person_id', $sales_person_id);
            })
            ->when(
                $branch_head_id = '' && $team_leader_id = '' && $sales_person_id = '',
                function ($query) {
                    $query->where('user_active', 1);

                    return $query->orWhere('team_active', 1);
                }
            )
            ->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);
                } elseif (($item->total_sale_value > 99999) && ($item->total_sale_value < 10000000)) {
                    $totalsalevalue = round($item->total_sale_value / 100000);
                } 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 {
        }

        $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);
    }

    private function generateRandomColor()
    {
        $color = sprintf('#%06x', rand(0, 0xFFFFFF));

        return $color;
    }
}
