<?php

namespace App\Http\Controllers\Web;


use Illuminate\Http\Request;
use Illuminate\View\View;
use App\Http\Controllers\Controller;
use Modules\User\Services\UserService;
use Modules\Deal\Services\DealService;
use Modules\Target\Services\TargetService;
use Modules\DailyLog\Services\DailyLogService;
use Modules\ContactList\Enums\ContactStatusEnum;
use Carbon\Carbon;

class CronController extends Controller
{
    
    public function __construct(
        private UserService $userService,
        private DealService $dealService,
        private TargetService $targetService,
        private DailyLogService $dailyLogService,
    ){}
    
    
    public function DeadlineReminder()
    {
        $deals = $this->dealService->get(['end_date'=>Carbon::tomorrow()->format('Y-m-d')]);
        foreach($deals as $row)
        {
            $this->dealService->sendReminder($row);
        }
    }
    
    public function DailyReminder()
    {
        $logs = $this->dailyLogService->get(['expire_date'=>Carbon::now()->format('Y-m-d'),'type_contact'=>ContactStatusEnum::FOLLOW_UP->value]);
        foreach($logs as $row)
        {
            $this->dailyLogService->sendReminder($row);
        }
    }
    
    public function TargetNotMetAlarm()
    {
        $now = now();
    
        if ($now->isLastOfMonth() || $now->isFriday() || (in_array($now->month, [3, 6, 9, 12]) && $now->isLastOfMonth()) )
        {
            
            $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;
            
            $employees = $this->userService->get(['roles'=> UserRoleEnum::employees()]);
            
            foreach($employees as $row)
            {
                $target = $this->targetService->get(['employee_id'=>$row->id,'date_from'=>$startOfQuarter,'date_to'=>$endOfQuarter,'sum'=>'target']);
                $achieved = $this->dealService->get(['employee_id'=>$row->id,'date_from'=>$startOfQuarter,'date_to'=>$endOfQuarter,'typeStatus'=>$typeStatus,'sum'=>'amount']);
                if($achieved < $target && $target != 0)
                {
                    $this->userService->NotTargetAlarm($row);
                }
            }
        }
    
    }
    
}
