<?php

namespace App;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class BotAJSClient
{
    private $client;
    private $baseUrl = 'https://api.botajs.top/web/api';
    private $apiKey;

    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl . '/',
            'timeout' => 30,
        ]);
    }

    /**
     * Get bot details
     */
    public function getBot($botId)
    {
        try {
            // First get all bots
            $response = $this->client->get("bots", [
                'headers' => [
                    'X-API-KEY' => $this->apiKey,
                    'Accept' => 'application/json',
                    'Origin' => 'https://app.botajs.top',
                    'Referer' => 'https://app.botajs.top/',
                    'User-Agent' => 'BotAJS-Git-Integration/1.0'
                ]
            ]);

            $data = json_decode($response->getBody(), true);

            // Find the specific bot by botId
            if (isset($data['bots']) && is_array($data['bots'])) {
                foreach ($data['bots'] as $bot) {
                    if ($bot['botId'] === $botId) {
                        return ['bot' => $bot];
                    }
                }
            }

            throw new \Exception("Bot with ID '{$botId}' not found");
        } catch (GuzzleException $e) {
            throw new \Exception('Failed to fetch bot: ' . $e->getMessage());
        }
    }

    /**
     * Get all commands for a bot
     */
    public function getBotCommands($botId)
    {
        try {
            $response = $this->client->get("bots/{$botId}/commands", [
                'headers' => [
                    'X-API-KEY' => $this->apiKey,
                    'Accept' => 'application/json',
                    'Origin' => 'https://app.botajs.top',
                    'Referer' => 'https://app.botajs.top/',
                    'User-Agent' => 'BotAJS-Git-Integration/1.0'
                ]
            ]);

            return json_decode($response->getBody(), true);
        } catch (GuzzleException $e) {
            throw new \Exception('Failed to fetch commands: ' . $e->getMessage());
        }
    }

    /**
     * Create or update a command
     */
    public function createCommand($botId, $command, $code, $needReply = false)
    {
        try {
            // Try to create the command first
            $response = $this->client->post("bots/{$botId}/commands", [
                'headers' => [
                    'X-API-KEY' => $this->apiKey,
                    'Accept' => 'application/json',
                ],
                'form_params' => [
                    'command' => $command,
                    'code' => $code,
                    'need_reply' => $needReply ? 1 : 0,
                ]
            ]);

            return json_decode($response->getBody(), true);
        } catch (GuzzleException $e) {
            // If command already exists (409 Conflict), try to update it
            if ($e->getCode() === 409 || strpos($e->getMessage(), '409') !== false) {
                try {
                    $response = $this->client->post("bots/{$botId}/commands", [
                        'headers' => [
                            'X-API-KEY' => $this->apiKey,
                            'Accept' => 'application/json',
                        ],
                        'form_params' => [
                            'old_command' => $command,
                            'command' => $command,
                            'code' => $code,
                            'need_reply' => $needReply ? 1 : 0,
                        ]
                    ]);

                    return json_decode($response->getBody(), true);
                } catch (GuzzleException $updateError) {
                    throw new \Exception('Failed to update command: ' . $updateError->getMessage());
                }
            }

            throw new \Exception('Failed to create command: ' . $e->getMessage());
        }
    }
}