<?php

declare(strict_types=1);

namespace KupShop\CoworkersBundle\Util;

use KupShop\AdminBundle\Util\ActivityLog;
use Query\Operator;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Service\Attribute\Required;

class CoworkersUtil
{
    private HttpClientInterface $httpClient;
    private ActivityLog $activityLog;

    #[Required]
    public function setHttpClient(HttpClientInterface $httpClient): void
    {
        $this->httpClient = $httpClient;
    }

    #[Required]
    final public function setActivityLog(ActivityLog $activityLog): void
    {
        $this->activityLog = $activityLog;
    }

    public function sendToVoicebot(): void
    {
        if (isDevelopment()) {
            return;
        }

        $settings = $this->getVoicebotSettings();

        $requestData = [];
        foreach ($this->getOrdersToSend() as $order) {
            $data['campaign_id'] = (int) $settings['campaign_id'];
            $data['phone_number'] = $order['invoice_phone'];
            $data['properties']['$order_number'] = $order['order_no'];
            $data['properties']['$last_change'] = $order['date_updated'] ?? '';

            $requestData[] = $data;
        }

        if ($this->sendRequest($requestData)) {
            $this->activityLog->addActivityLog(ActivityLog::SEVERITY_SUCCESS, ActivityLog::TYPE_SYNC, 'Podařilo se vytvořit kontakty do Voicebotu');
        }
    }

    protected function sendRequest(array $requestData): bool
    {
        $settings = $this->getVoicebotSettings();

        $url = $settings['api_url'].'contacts?instanceId='.$settings['instance_id'];

        $response = $this->httpClient->request(
            'POST',
            $url,
            [
                'headers' => [
                    'Authorization' => 'Api-Key '.$settings['api_key'],
                    'Content-Type' => 'application/json',
                ],
                'body' => json_encode($requestData),
            ]
        );

        if ($response->getStatusCode() != 200) {
            $this->activityLog->addActivityLog(ActivityLog::SEVERITY_ERROR, ActivityLog::TYPE_SYNC, 'Nepodařilo se vytvořit kontakty do Voicebotu', ['response' => $response->getContent(false)]);

            return false;
        }

        return true;
    }

    protected function getVoicebotSettings(): array
    {
        return \Settings::getDefault()->voicebot ?? [];
    }

    protected function getOrdersToSend(): iterable
    {
        $settings = $this->getVoicebotSettings();
        $qb = sqlQueryBuilder()
            ->select('o.order_no as order_no, o.invoice_phone as invoice_phone, o.invoice_email as invoice_email, o.date_updated as date_updated')
            ->from('orders', 'o')
            ->where(Operator::inIntArray($settings['order_statuses'], 'o.status'))
            ->andWhere('(SELECT MIN(oh.date) FROM orders_history oh WHERE oh.id_order = o.id 
            AND o.status = oh.id_status ORDER BY oh.date) < NOW() - INTERVAL :days DAY')
            ->andWhere(Operator::not(Operator::equals(['o.invoice_phone' => ''])))
            ->setParameter('days', $settings['days']);

        return $qb->execute();
    }
}
