<?php

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

use App\Branch;
use App\Http\Controllers\Controller;
use App\SalesHistory;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\DsrBooking;
use App\PerformanceTarget;
use App\Api\Http\Requests\Analytics\PerformanceTargetListRequest;

class PerformanceTargetsController extends Controller
{
    public function index(PerformanceTargetListRequest $request)
    {

        $request_type = $request->type;
        $tot_target = 0;
        $tot_achieved = 0;

        $performanceData = PerformanceTarget::with(['getBranch', 'getBranch.getDsrBookings','getBranch.getDsrSplits'])->where('type', $request_type)->where('status', 1)->get()
            ->map(function ($item) use (&$tot_target, &$tot_achieved, &$tot_achievement) {
                $targetQuarter = $item->quarter;

                        $dsrBookingsForQuarter = $item->getBranch->getDsrBookings
                            ->where('quarter', $targetQuarter)
                            ->where('split', 1)
                            ->where('status', 'AGREEMENTED');

                        $dsrSplitBookingsForQuarter = $item->getBranch->getDsrSplits
                            ->where('quarter', $targetQuarter)
                            // ->whereBetween('agreement_date', [$item->start_date, $item->end_date])
                             ->where('status', 'AGREEMENTED');
                  

                    $totalSaleValueFrmSplit = $dsrSplitBookingsForQuarter->sum('amount');
                    $totalSaleValueFrmDsr = $dsrBookingsForQuarter->sum('sale_value');

                    $totalSaleValue = $totalSaleValueFrmDsr+$totalSaleValueFrmSplit;
               

                $salePercentage = $item->target != 0 ? round(($totalSaleValue / $item->target) * 100, 2) : null;
                $target = $item->target;

                $tot_target += $target;
                $tot_achieved += $totalSaleValue;

                $lst_achieved = number_format($totalSaleValue / $item->lakh,2);
               

                return [
                    'region'      => $item->title,
                    'target'      => round($target / $item->lakh, 0),
                    'achieved'    => strval($lst_achieved) ?? '0',
                    'achievement_withot_sim' => $salePercentage !== null ? $salePercentage : 0,
                    'achievement' => $salePercentage !== null ? $salePercentage . '%' : 'N/A',
                    'position' => ''
                ];
            })
            ->toArray();




            $performanceDataFiltered = array_filter($performanceData, function ($item) {
                return $item['region'] !== "Management";
            });
            
           
            usort($performanceDataFiltered, function ($a, $b) {
                return $b['achievement_withot_sim'] - $a['achievement_withot_sim'];
            });
            
            
            $positionCounter = 0; 
            foreach ($performanceDataFiltered as $key => $item) {
                $positionCounter++;
                $performanceDataFiltered[$key]['position'] = $this->getOrdinalNumber($positionCounter);
            }
            
   
            foreach ($performanceData as $key => $item) {
                if ($item['region'] !== "Management") {
                    foreach ($performanceDataFiltered as $filteredItem) {
                        if ($item['region'] === $filteredItem['region']) {
                            $performanceData[$key]['position'] = $filteredItem['position'];
                            break;
                        }
                    }
                }
            }

            $totals = [
                'target'      => ($tot_target != 0) ? round($tot_target / 10000000, 0) : 0,
                'achieved'    => ($tot_achieved != 0) ? strval(number_format($tot_achieved / 10000000, 2)) : '0',
                'achievement' => ($tot_target != 0) ? round(($tot_achieved / $tot_target) * 100, 2) . '%' : '0%',
            ];
            

        usort($performanceData, function ($a, $b) {
            return $b['achievement_withot_sim'] - $a['achievement_withot_sim'];
        });


        $managementEntry = null;
        foreach ($performanceData as $key => $item) {
            if ($item['region'] === "Management") {
                $managementEntry = $performanceData[$key];
                unset($performanceData[$key]);
                break;
            }
        }

        if ($managementEntry !== null) {
            $performanceData[] = $managementEntry;
        }

        

        $jsonData = [
            'success' => true,
            'message' => '',
            'data' => [
                'performance_comparison' => [
                    'total'            => $totals,
                    'performance_data' => array_values($performanceData),
                ],
            ],
        ];
        

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

    private function getOrdinalNumber($number)
    {
        $suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
        if (($number % 100) >= 11 && ($number % 100) <= 13) {
            $abbreviation = $number . 'th';
        } else {
            $abbreviation = $number . $suffix[$number % 10];
        }
        return $abbreviation;
    }
}
