<?php

class Am_Plugin_Xrp extends Am_Plugin
{
    public function getTitle()
    {
        return 'XRP Email Price';
    }

    public function getDescription()
    {
        return 'Adds cached live XRP price from CoinGecko to emails';
    }

    public function init()
    {
        Am_Di::getInstance()->hook->add(
            Am_Event::MAIL_TEMPLATE_BEFORE_PARSE,
            [$this, 'addXrpVars']
        );
    }

    public function addXrpVars(Am_Event $event)
    {
        $tmpl = $event->getTemplate();

        if (empty($tmpl->invoice)) {
            $this->setNa($tmpl);
            return;
        }

        $invoice = $tmpl->invoice;
        $baseEur = (float)$invoice->first_total;

        if ($baseEur <= 0) {
            $this->setNa($tmpl);
            return;
        }

        // 🔥 Προσαύξηση στο ποσό EUR: +10%
        $markupPercent = 10;
        $finalEur = $baseEur * (1 + ($markupPercent / 100));

        // XRP price με cache
        $xrpPriceEur = $this->getCachedXrpPrice();

        if (!$xrpPriceEur || $xrpPriceEur <= 0) {
            $this->setNa($tmpl);
            return;
        }

        // Βασικός υπολογισμός XRP
        $xrpAmount = $finalEur / $xrpPriceEur;

        // Extra XRP buffer για να μειωθεί ο κίνδυνος χασούρας
        $extraPercent = 0.04; // +4%
        $extraFlat = 0.10;    // minimum +0.10 XRP
        $extraMax = 0.30;     // maximum +0.30 XRP

        $extraXrp = max($extraFlat, $xrpAmount * $extraPercent);
        $extraXrp = min($extraXrp, $extraMax);

        $xrpAmount = $xrpAmount + $extraXrp;

        // Ώρα λήψης τιμής & ισχύς 15 λεπτά
        $fetchedAt = date('H:i:s');
        $validUntil = date('H:i', time() + (15 * 60));

        $tmpl->setXrp_total_eur(number_format($finalEur, 2, '.', ''));
        $tmpl->setXrp_price_eur(number_format($xrpPriceEur, 4, '.', ''));
        $tmpl->setXrp_amount(number_format($xrpAmount, 2, '.', ''));
        $tmpl->setXrp_fetched_at($fetchedAt);
        $tmpl->setXrp_valid_until($validUntil);
    }

    private function getCachedXrpPrice()
    {
        $cacheFile = APPLICATION_PATH . '/data/xrp_price_cache.json';
        $cacheTtl = 120; // 2 λεπτά cache

        if (file_exists($cacheFile)) {
            $cache = json_decode(file_get_contents($cacheFile), true);

            if (
                !empty($cache['price']) &&
                !empty($cache['time']) &&
                (time() - (int)$cache['time']) < $cacheTtl
            ) {
                return (float)$cache['price'];
            }
        }

        $apiUrl = 'https://api.coingecko.com/api/v3/simple/price?ids=ripple&vs_currencies=eur';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        if (!$response || $httpCode !== 200) {
            return null;
        }

        $data = json_decode($response, true);

        if (empty($data['ripple']['eur'])) {
            return null;
        }

        $price = (float)$data['ripple']['eur'];

        if ($price <= 0) {
            return null;
        }

        file_put_contents($cacheFile, json_encode([
            'price' => $price,
            'time' => time()
        ]));

        return $price;
    }

    private function setNa($tmpl)
    {
        $tmpl->setXrp_total_eur('N/A');
        $tmpl->setXrp_price_eur('N/A');
        $tmpl->setXrp_amount('N/A');
        $tmpl->setXrp_fetched_at('N/A');
        $tmpl->setXrp_valid_until('N/A');
    }
}