<?php

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

use App\Http\Controllers\Controller;
use App\IncentiveBracket;
use App\SalesQuarter;
use Illuminate\Http\Request;

class IncentiveController extends Controller
{

    public function calculateIncentive(Request $request)
    {
        try {
            $currentDate = date('Y-m-d');

            $target = SalesQuarter::where('user_id', auth()->user()->id)
                ->whereRaw('? between quarterly_start_date and quarterly_end_date', $currentDate)

                ->first();

            $target = $target->quarterly_target_amount;


            $achievedPercentage = ($request->achieved_amount / $target) * 100;

            $targetBracket = IncentiveBracket::whereRaw('? between achieved_percentage_from and achieved_percentage_to', ceil($achievedPercentage))->first();
            if($targetBracket){
                $incentiveAmount = ($request->achieved_amount * $targetBracket->incentive_bracket) / 100;

                $jsonData = [
                    'success' => true,
                    'message' => 'Incentive Amount',
                    'data' => [
                        'incentiveAmount' => strval($incentiveAmount),
                    ],
                ];
                return response()->json($jsonData);
            }
            $jsonData = [
                'success' => false,
                'message' => 'Incentive Amount',
                'data' => [
                    'incentiveAmount' => 'Incentive bracket does not exist !',
                ],
            ];
            return response()->json($jsonData);
        
        } catch (\Throwable $th) {
            $jsonData = [
                'success' => false,
                'message' => 'Incentive Amount',
                'data' => [
                    'incentiveAmount' => 'Incentive bracket does not exist !',
                ],
            ];
            return response()->json($jsonData);
          
        }
    }
}
