<?php

namespace BitApps\SocialPro\HTTP\Services\Social\TelegramService;

use AllowDynamicProperties;
use BitApps\Social\HTTP\Services\Interfaces\SocialInterface;
use BitApps\Social\HTTP\Services\Traits\LoggerTrait;
use BitApps\Social\Model\Schedule;
use BitApps\Social\Utils\Common;
use BitApps\Social\Utils\Hash;
use BitApps\SocialPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

// use GuzzleHttp\Client;

#[AllowDynamicProperties]
class PostPublishTelegramService implements SocialInterface
{
    use Common, LoggerTrait;

    private $baseUrl = 'https://api.telegram.org/bot';

    private $httpClient;

    private $accessToken;

    private $mediaErrors = [];

    private $linkErrors = [];

    private $commentErrors = [];

    private $maxTextLength = 1024;

    public function __construct()
    {
        $this->httpClient = new HttpClient();
    }

    public function publishPost($data)
    {
        $post = $data['post'] ?? null;
        $template = (object) $data['template'];
        $scheduleType = $data['schedule_type'] ?? null;
        $accountDetails = $data['account_details'];
        $schedule_id = $data['schedule_id'] ?? null;
        $accountId = $accountDetails->account_id;
        $accountName = $accountDetails->account_name;

        $this->accessToken = Hash::decrypt($accountDetails->access_token);
        $this->chatId = $accountDetails->account_id;

        $postData = $this->postData($scheduleType, $post, $template);

        $postPublishResponse = $this->sendMessage($postData);

        if (\array_key_exists('keepLogs', $data) && !$data['keepLogs']) {
            return;
        }

        $status = \is_object($postPublishResponse) && $postPublishResponse->ok ? 1 : 0;

        $responseData = [
            'schedule_id' => $schedule_id,
            'details'     => [
                'account_id'   => $accountId,
                'account_name' => $accountName,
                'post_id'      => $post['ID'] ?? null,
                'response'     => $postPublishResponse,
                'post_url'     => null,
            ],
            'platform' => 'telegram',
            'status'   => $status
        ];

        if (\count($this->mediaErrors)) {
            $responseData['details']['mediaErrors'] = $this->mediaErrors;
        }

        if (\count($this->linkErrors)) {
            $responseData['details']['linkErrors'] = $this->linkErrors;
        }

        if (\count($this->commentErrors)) {
            $responseData['details']['commentErrors'] = $this->commentErrors;
        }

        $this->logCreate($responseData);
    }

    public function postData($scheduleType, $post, $template)
    {
        $postData = [];
        $template = (object) $template;

        if ($scheduleType === Schedule::scheduleType['DIRECT_SHARE']) {
            $templateMedia = array_map(function ($item) {
                return $item['url'];
            }, $template->media);

            $postData['content'] = $template->content ?? null;
            $postData['createdAt'] = date('c');
            $postData['media'] = $template->isAllImages ? $templateMedia : null;
            $postData['link'] = $template->isLinkCard ? $template->link : null;
        } else {
            $template->platform = 'telegram';
            $postData = $this->replacePostContent($post['ID'], $template);

            if (!empty($postData['featureImage'])) {
                $postData['media'] = [$postData['featureImage']];
            }
            if (!empty($postData['allImages'])) {
                $postData['media'] = $postData['allImages'];
            }
        }

        return $postData;
    }

    public function sendMessage($postData)
    {
        if (!empty($postData['media'])) {
            return $this->sendMediaGroup($postData);
        }
        $url = "{$this->baseUrl}{$this->accessToken}/sendMessage";

        $content = $postData['content'] ?? '';

        $body = [
            'chat_id'    => $this->chatId,
            'text'       => $content,
            'parse_mode' => 'HTML',
        ];

        if (!empty($postData['link'])) {
            $reservedLength = \strlen("\n\n" . $postData['link']);
            $availableLength = $this->maxTextLength - $reservedLength;

            // Trim content if necessary
            if (\strlen($content) > $availableLength) {
                $content = mb_substr($content, 0, $availableLength - 3) . '...';
            }

            $body['text'] = $content . "\n\n" . $postData['link'];
        }

        return $this->httpClient->request($url, 'POST', $body);
    }

    public function sendMediaGroup($postingData)
    {
        $url = "{$this->baseUrl}{$this->accessToken}/sendMediaGroup";

        $media = [];
        foreach ($postingData['media'] as $index => $mediaItem) {
            $media[] = [
                'type'       => 'photo',
                'media'      => $mediaItem,
                'parse_mode' => 'HTML',
            ];
        }

        if (!empty($postingData['content'])) {
            $media[0]['caption'] = $postingData['content'] ?? '';
        }

        $body = [
            'chat_id' => $this->chatId,
            'media'   => json_encode($media),
        ];

        return $this->httpClient->request($url, 'POST', $body);
    }
}
