<?php

namespace Modules\User\Services;
use App\Jobs\SendMailJob;
use Modules\User\Mails\TargetAchievedMail;
use Modules\User\Mails\NotTargetAchievedMail;
use Modules\Deal\Services\DealService;
use Modules\Target\Services\TargetService;
use Modules\Deal\Enums\DealStatusEnum;

class UserTargetAchieveService
{

    private string $veiwDirectoryMail = 'admin.users.mails.';
    public function __construct(
        private DealService $dealService,
        private TargetService $targetService,
    ){}

    public function CheckTargetAchieved($user)
    {
        $today = date('Y-m-d');
        $month = date('n');
        $year = date('Y');
        $quarter = ceil($month / 3);
        $startMonth = ($quarter - 1) * 3 + 1;
        $startOfQuarter = date('Y-m-d', strtotime("$year-$startMonth-01"));
        $endMonth = $startMonth + 2;
        $endOfQuarter = date('Y-m-t', strtotime("$year-$endMonth-01"));
        $typeStatus = DealStatusEnum::Payment_Received->value;
        $target = $this->targetService->get(['employee_id'=>$user->id,'date_from'=>$startOfQuarter,'date_to'=>$endOfQuarter,'sum'=>'target']);
        $achieved = $this->dealService->get(['employee_id'=>$user->id,'date_from'=>$startOfQuarter,'date_to'=>$endOfQuarter,'typeStatus'=>$typeStatus,'sum'=>'amount']);
        return ['target'=>$target,'achieved'=>$achieved];
    }
    
    public function TargetAchieved($user,$target,$achieved)
    {
        SendMailJob::dispatch
        (
            $user->email,
            TargetAchievedMail::class,
            $this->veiwDirectoryMail.'target_achieved',
            'Congratulations! Target Achieved',
            [
                'employee'=>$user,
                'target'=>$target,
                'achieved'=>$achieved
            ],
        );
    }
    
    public function NotTargetAlarm($user,$target,$achieved)
    {
        SendMailJob::dispatch
        (
            $user->email,
            NotTargetAchievedMail::class,
            $this->veiwDirectoryMail.'not_target_achieved',
            'Target Not Achieved — Action Required',
            [
                'employee'=>$user,
                'target'=>$target,
                'achieved'=>$achieved
            ],
        );
    }
    
}