<?php

header('Content-Type: application/json');

class ResponseFormatter {
    public static function formatResponse($data, $success = true) {
        return array_merge([
            "channel_rubika" => "@ID10101",
            "success" => $success
        ], $data);
    }
}

class CryptoPriceFetcher {
    private $crypto_name;
    private $amount;
    private $api_url = "https://api.nobitex.ir/market/stats";
    private $result = [];

    public function __construct($crypto_name, $amount) {
        $this->crypto_name = strtolower($crypto_name);
        $this->amount = floatval($amount);
    }

    private function rialToToman($rial) {
        return intval($rial / 10);
    }

    private function formatPrice($price) {
        return number_format($price, is_float($price) ? 2 : 0, '.', ',');
    }

    public function fetchPriceData() {
        $response = $this->makeApiRequest();

        if (!$response || !isset($response['stats'])) {
            $this->result["error"] = "API error";
            return;
        }

        $stats = $response['stats'];
        $price_rial = null;
        $price_usd = null;
        $change_percentage = null;

        foreach ($stats as $market => $details) {
            $market = strtolower($market);
            if ($this->crypto_name === 'usdt' && $market === 'usdt-rls') {
                $price_rial = floatval($details['latest']);
                $change_percentage = floatval($details['dayChange']);
                break;
            }
            if ("{$this->crypto_name}-rls" === $market) {
                $price_rial = floatval($details['latest']);
                $change_percentage = floatval($details['dayChange']);
            }
            if ("{$this->crypto_name}-usdt" === $market) {
                $price_usd = floatval($details['latest']);
            }
        }

        if ($this->crypto_name === 'usdt' && $price_rial !== null) {
            $price_toman = $this->rialToToman($price_rial);
            $total_price_toman = $price_toman * $this->amount;

            $this->result = [
                "crypto_name" => "USDT",
                "price_toman" => $this->formatPrice($total_price_toman),
                "change_24h" => number_format($change_percentage, 2) . "%",
                "trend" => $change_percentage > 0 ? "Up" : "Down",
                "currency" => "Toman",
                "message" => "{$this->amount} USDT equals " . $this->formatPrice($total_price_toman) . " Toman."
            ];
            return;
        }

        if ($price_rial !== null && $price_usd !== null) {
            $price_toman = $this->rialToToman($price_rial);
            $total_price_toman = $price_toman * $this->amount;
            $total_price_usd = $price_usd * $this->amount;

            $this->result = [
                "crypto_name" => strtoupper($this->crypto_name),
                "price_toman" => $this->formatPrice($total_price_toman),
                "price_usd" => $this->formatPrice($total_price_usd),
                "change_24h" => number_format($change_percentage, 2) . "%",
                "trend" => $change_percentage > 0 ? "Up" : "Down",
                "currency" => "Toman",
                "message" => "The price of " . strtoupper($this->crypto_name) . " is " . 
                             $this->formatPrice($total_price_toman) . " Toman and " . 
                             $this->formatPrice($total_price_usd) . " USD."
            ];
        }
    }

    private function makeApiRequest() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }

    public function getResult() {
        return $this->result;
    }
}

// Handling request
$crypto_name = isset($_GET['crypto_name']) ? $_GET['crypto_name'] : null;
$amount = isset($_GET['amount']) ? floatval($_GET['amount']) : 1;

if (!$crypto_name) {
    http_response_code(400);
    echo json_encode(ResponseFormatter::formatResponse(["error" => "crypto_name parameter is required"], false));
    exit;
}

$fetcher = new CryptoPriceFetcher($crypto_name, $amount);
$fetcher->fetchPriceData();
$result = $fetcher->getResult();
$success = !isset($result["error"]);

echo json_encode(ResponseFormatter::formatResponse($result, $success));
