<?php 
 
namespace App\EventSubscriber; 
 
use ApiPlatform\Symfony\EventListener\EventPriorities; 
use App\Entity\ActionPlan; 
use App\ActionPlan\ActionPlanPrepare; 
use App\Repository\ActionPlanRepository; 
use Doctrine\ORM\EntityManagerInterface; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpKernel\Event\ViewEvent; 
use Symfony\Component\HttpKernel\KernelEvents; 
 
final class ActionPlanSubscriber implements EventSubscriberInterface 
{ 
    public function __construct(private ActionPlanPrepare $actionPlanPrepare, private EntityManagerInterface $entityManager,private ActionPlanRepository $actionPlanRepository) 
    { 
    } 
 
    public static function getSubscribedEvents() 
    { 
        return [ 
            KernelEvents::VIEW => [ 
                ['preWriteActionPlan', EventPriorities::POST_WRITE] 
            ], 
        ]; 
    } 
 
    public function preWriteActionPlan(ViewEvent $event): void 
    { 
        $actionPlan = $event->getControllerResult(); 
        $method = $event->getRequest()->getMethod(); 
 
        if(($actionPlan instanceof ActionPlan) && Request::METHOD_PUT === $method){ 
            $idActionPlan = $actionPlan->getId(); 
            $sql = "select * from action_plan where id = $idActionPlan"; 
            $conn = $this->entityManager->getConnection(); 
            $stmt = $conn->prepare($sql); 
            $oldActionPlan = $stmt->executeQuery(); 
            $oldActionPlan = $oldActionPlan->fetchAssociative(); 
            $this->actionPlanRepository->save($actionPlan, true); 
            if($oldActionPlan['user_in_charge_id'] != $actionPlan->getUserInCharge()?->getId()){ 
                $description_log = 'edit action plan ' . $actionPlan->getId() .'change user '. $oldActionPlan['user_in_charge_id'] . ' to ' . $actionPlan->getUserInCharge()?->getId() . 'created by user ' . $actionPlan->getCreatedBy()->getId() . 'created at '. $actionPlan->getCreatedAt()->format('d/m/Y H:i:s'); 
                $this->actionPlanPrepare->sendActionPlanEmail($actionPlan, $description_log); 
            } 
            else{ 
                return; 
            } 
        } 
        if (!($actionPlan instanceof ActionPlan) || (Request::METHOD_POST !== $method)) { 
            return; 
        } 
        $description_log = 'add action plan' . $actionPlan->getId() . 'change user '. $actionPlan->getUserInCharge()?->getId() . 'created by user ' . $actionPlan->getCreatedBy()->getId(). 'created at '. $actionPlan->getCreatedAt()->format('d/m/Y H:i:s'); 
 
        $this->actionPlanPrepare->sendActionPlanEmail($actionPlan, $description_log); 
    } 
}