<?php

namespace Devsaadat\ShopGostardeh\Gostardeh;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;

class GostardehApi
{

    private string $apikey;
    private Client $client;
    private string $url = 'https://Gostardeyou.xyz/GostardeSazBot/api/';

    /**
     * @throws Exception
     */
    function __construct($apikey)
    {
        if (preg_match('/^[a-zA-Z0-9]+$/', $apikey)) {
            $this->apikey = $apikey;
            $this->client = new Client();
        } else {
            throw new Exception("apikey is not correct");
        }
    }

    /**
     * @param array $body
     * @return string
     * @throws Exception
     */
    private function request(array $body): mixed
    {

        $headers = [
            'X-API-KEY' => $this->apikey,
            'Content-Type' => 'application/json'
        ];
        try {

            $request = new Request('POST', $this->url, $headers, json_encode($body));
            $res = $this->client->sendAsync($request)->wait();

            // گرفتن HTTP Status Code
            //$statusCode = $res->getStatusCode();
            // گرفتن بدنه پاسخ
            return json_decode($res->getBody()->getContents(), true);

        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                //$statusCode = $e->getResponse()->getStatusCode();
                return json_decode($e->getResponse()->getBody()->getContents(), true);
            } else {
                throw new Exception("Request failed: " . $e->getMessage());
            }
        }

    }

    /**
     * @throws Exception
     */
    public function getBalance(): array
    {
        return $this->request(['action' => 'getBalance']);
    }

    /**
     * @throws Exception
     */
    public function newOrder(string $chat_id, int $quantity, ?int $amount = null, ?int $gift_amount = null, ?int $gift_count = null, ?string $callback_url = null): array
    {
        $params = [
            'action' => 'newOrder',
            'chat_id' => $chat_id,
            'quantity' => $quantity
        ];

        if($amount) $params['amount'] = $amount;
        if($gift_amount and $gift_amount > 0) $params['gift_amount'] = $gift_amount;
        if($gift_count and $gift_amount > 0) $params['gift_count'] = $gift_count;
        if($callback_url) $params['callback_url'] = $callback_url;

        return $this->request($params);
    }

    /**
     * @throws Exception
     */
    public function getOrdersList(?int $offset, ?int $limit, ?string $order): array
    {
        $params = [
            'action' => 'getOrdersList'
        ];

        if($order) $params['order'] = $order;
        if($offset) $params['offset'] = $offset;
        if($limit) $params['limit'] = $limit;

        return $this->request($params);
    }

    /**
     * @throws Exception
     */
    public function getOrderById(int $order_id): array
    {
        return $this->request([
            'action' => 'getOrderById',
            'order_id' => $order_id
        ]);
    }

    /**
     * @throws Exception
     */
    public function getOrderByIds(array $order_ids): array
    {
        return $this->request([
            'action' => 'getOrderByIds',
            'order_ids' => implode(',', $order_ids)
        ]);
    }

    /**
     * @throws Exception
     */
    public function cancelOrder(int $order_id): array
    {
        return $this->request([
            'action' => 'cancelOrder',
            'order_id' => $order_id
        ]);
    }

    /**
     * @throws Exception
     */
    public function inquiryChannelRate(int $members, ?bool $is_group): array
    {
        return $this->request([
            'action' => 'inquiry',
            'members' => $members,
            'is_group' => $is_group
        ]);
    }

    /**
     * @throws Exception
     */
    public function inquiryChannelRate2(int|string $chat_id): array
    {
        return $this->request([
            'action' => 'inquiry2',
            'chat_id' => $chat_id
        ]);
    }




}