<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Helper\Slack;
use App\Entity\Order;
use Maknz\Slack\Client;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Notifier\ChatterInterface;


class SlackNotifySubscriber implements EventSubscriberInterface
{
    /**
     * @var Slack
     */
    public $logger;

    private $slackWebhookUrl;

    public function __construct(string  $slackWebhookUrl, LoggerInterface $logger)
    {
        $this->slackWebhookUrl = $slackWebhookUrl;
        $this->logger = $logger;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['sendSlack', EventPriorities::POST_WRITE],
        ];
    }


    /**
     * @param ViewEvent $event
     * @return void
     */
    public function sendSlack(ViewEvent $event): void
    {
        $slack = new Client($this->slackWebhookUrl, [
            'username' => 'CDS-Notify',
            'channel' => '#general',
            'link_names' => true
        ]);

        $order = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

       //wenn es keine Bestellung ist oder es kein POST Request ist, dann return
       if (!$order instanceof Order || Request::METHOD_POST !== $method) {
            return;
       }

       $msg = "Bestellung {$order->getId()}: ";

       foreach($order->getData() as $item) {
           if($item['menge'] > 0 && strlen($item['sku']) > 0) {
               $msg .= ' '.$item['name'];
               $msg .= ' - '.$item['sku'];
               $msg .= ' Menge: '.$item['menge'];
           }
       }

       if($order->getStatus() == 1) {
           $slack->from('CDS-Notify')
               ->send($msg);
       }
    }
}