<?php

namespace BitApps\PiPro\src\Integrations\Discord;

use BitApps\Pi\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\Pi\Helpers\Utility;

if (!\defined('ABSPATH')) {
    exit;
}

final class DiscordChannelService
{
    private $http;

    private $baseUrl;

    public function __construct($httpClient, $baseUrl)
    {
        $this->http = $httpClient;
        $this->baseUrl = $baseUrl;
    }

    public function createChannel($guildId, $data)
    {
        $response = $this->http->request(
            $this->baseUrl . "/guilds/{$guildId}/channels",
            'POST',
            JSON::encode($data),
            []
        );

        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;

        return Utility::formatResponseData(
            $responseCode,
            $data,
            $response,
            $success ? 'Channel created successfully' : $response->message
        );
    }

    public function updateChannel($channelId, $data)
    {
        $response = $this->http->request(
            $this->baseUrl . "/channels/{$channelId}",
            'PATCH',
            JSON::encode($data),
            []
        );


        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;

        return Utility::formatResponseData(
            $responseCode,
            $data,
            $response,
            $success ? 'Channel updated successfully' : $response->message
        );
    }

    public function getChannelByName($guildId, $channelName)
    {
        $channels = $this->http->request(
            $this->baseUrl . "/guilds/{$guildId}/channels",
            'GET',
            []
        );

        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;
        $payload = ['guild_id' => $guildId, 'name' => $channelName];

        if (empty($channels) || !\is_array($channels)) {
            return Utility::formatResponseData(
                $responseCode,
                $payload,
                null,
                'Error: No channels found'
            );
        }

        foreach ($channels as $channel) {
            if (isset($channel->name) && $channel->name === $channelName['name']) {
                $errorMessage = (\is_object($channels) && isset($channels->message)) ? $channels->message : 'Error';
                return Utility::formatResponseData(
                    $responseCode,
                    ['guild_id' => $guildId, 'name' => $channelName],
                    $channel,
                    $success ? 'Channel found successfully' : $errorMessage
                );
            }
        }
    }

    public function findChannel($guildId, $searchQuery, $channelType = '')
    {
        $channels = $this->http->request(
            $this->baseUrl . "/guilds/{$guildId}/channels",
            'GET',
            []
        );

        $payload = ['guild_id' => $guildId, 'search_query' => $searchQuery, 'channel_type' => $channelType];
        $results = [];

        if (!empty($channels) && \is_array($channels)) {
            foreach ($channels as $channel) {
                $channelArray = \is_object($channel) ? (array) $channel : $channel;
                $matchesName = isset($channelArray['name']) && stripos($channelArray['name'], $searchQuery) !== false;
                $matchesId = isset($channelArray['id']) && $channelArray['id'] === $searchQuery;
                $matchesType = empty($channelType) || (isset($channelArray['type']) && $channelArray['type'] == $channelType);

                if (($matchesName || $matchesId) && $matchesType) {
                    $results[] = $channelArray;
                }
            }
        }

        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;

        $errorMessage = (\is_object($channels) && isset($channels->message)) ? $channels->message : 'Error';
        return Utility::formatResponseData(
            $responseCode,
            $payload,
            $results,
            $success ? 'Channel found successfully' : $errorMessage
        );
    }

    public function createChannelInvite($channelId, $data)
    {
        $response = $this->http->request(
            $this->baseUrl . "/channels/{$channelId}/invites",
            'POST',
            JSON::encode($data),
            []
        );

        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;

        return Utility::formatResponseData(
            $responseCode,
            $data,
            $response,
            $success ? 'Channel invite created successfully' : $response->message
        );
    }

    public function createForumPost($channelId, $data)
    {
        $response = $this->http->request(
            $this->baseUrl . "/channels/{$channelId}/threads",
            'POST',
            JSON::encode($data),
            []
        );

        $responseCode = $this->http->getResponseCode();
        $success = $responseCode >= 200 && $responseCode < 300;

        return Utility::formatResponseData(
            $responseCode,
            $data,
            $response,
            $success ? 'Forum post created successfully' : $response->message
        );
    }
}
