<?php

namespace KupShop\LLMBundle\Util;

use KupShop\ContentBundle\Util\BlocksTrait;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Query\Operator;

class PlaceholdersCreator
{
    use BlocksTrait;
    public const EMPTY_LINE = '-emptyline-';

    public function __construct(private UrlFinder $urlFinder)
    {
    }

    public function getProductParameters(\Product $product): string
    {
        $output = [];
        foreach ($product->param ?? [] as $param) {
            if (empty($param['name'])) {
                continue;
            }

            $paramOut = $param['name'];

            if ($param['values'] ?? false) {
                $paramOut .= ': ';
                $outValues = [];
                foreach ($param['values'] as $value) {
                    $out = $value['value'] ?? '';
                    if (!empty($value['descr'])) {
                        $out .= ' ('.$value['descr'].')';
                    }
                    $outValues[] = $out;
                }

                $paramOut .= implode(', ', $outValues);
            }

            $output[] = $paramOut;

            if (!empty($param['descr'])) {
                $output[] = 'Popis parametru '.$param['name'].': '.$param['descr'];
            }
        }

        return $this->implodeOutput($output);
    }

    public function getProductsTemplates(int $idProduct): string
    {
        if (!$idProduct) {
            return '';
        }

        $blockIds = sqlQueryBuilder()->select('id_block')->from('templates_products', 'tp')
            ->innerJoin('tp', 'templates', 't', 't.id = tp.id_template')
            ->where(Operator::equals(['tp.id_product' => $idProduct]))
            ->execute()->fetchFirstColumn();

        $output = [];
        foreach ($blockIds as $blockId) {
            $output[] = $this->getTextFromBlockId($blockId);
            $output[] = self::EMPTY_LINE;
        }

        return $this->implodeOutput($output);
    }

    public function getTextFromBlockId(?int $idBlock): string
    {
        if (!$idBlock) {
            return '';
        }
        $output = [];
        foreach ($this->getBlocks($idBlock) as $block) {
            $output = array_merge($output, $this->extractTextFromBlocekJson($block['json_content'] ?? []));
            $output[] = self::EMPTY_LINE;
        }

        return $this->implodeOutput($output);
    }

    public function getImageFromArray(?array $image): string
    {
        if (empty($image['src'])) {
            return 'žádný obrázek';
        }
        $url = $this->urlFinder->staticUrlAbsolute($image['src']);

        return "{image:{$url}}";
    }

    protected function extractTextFromBlocekJson(string|array $jsonContent): array
    {
        $blocks = is_array($jsonContent) ? $jsonContent : (json_decode($jsonContent, true) ?? []);
        $output = [];

        foreach ($blocks as $block) {
            if (in_array($block['type'], ['legacy', 'text', 'heading'])) {
                $output[] = $block['settings']['html'] ?? $block['settings']['text'] ?? null;
            }

            if (isset($block['children']) && is_array($block['children'])) {
                $output = array_merge($output, $this->extractTextFromBlocekJson($block['children']));
            }
        }

        return $output;
    }

    public function getOrderHistory(\Order $order): string
    {
        $output = [];
        foreach ($order->getHistory() ?? [] as $message) {
            if ($message['comment']) {
                $output[] = "{$message['date']} (Status: {$message['status_text']}): {$message['comment']}";
            }
        }

        if (empty($output)) {
            return 'Prázdná';
        }

        return $this->implodeOutput($output);
    }

    public function getOrderData(\Order $order): string
    {
        $output = [];

        $output[] = 'Číslo objednávky: '.$order->order_no;
        $output[] = 'Datum vytvoření : '.$order->date_created->format('Y-m-d H:i:s');
        $output[] = 'Celková cena s DPH: '.printPrice($order->total_price);
        $output[] = 'Celková cena bez DPH: '.printPrice($order->total_price_without_vat);

        $output[] = self::EMPTY_LINE;
        $output[] = 'Fakturační údaje:';
        $output[] = $order->invoice_name.' '.$order->invoice_surname;
        $order->invoice_firm && ($output[] = 'Firma: '.$order->invoice_firm);
        $output[] = $order->invoice_street.' '.$order->invoice_city.' '.$order->invoice_zip.' '.$order->invoice_country;
        $output[] = $order->invoice_phone;
        $output[] = $order->invoice_email;

        $output[] = self::EMPTY_LINE;
        $output[] = 'Doručovací údaje:';
        $output[] = $order->delivery_name.' '.$order->delivery_surname;
        $order->delivery_firm && ($output[] = 'Firma: '.$order->delivery_firm);
        $output[] = $order->delivery_street.' '.$order->delivery_city.' '.$order->delivery_zip.' '.$order->delivery_country;
        $output[] = $order->delivery_phone;
        $output[] = self::EMPTY_LINE;
        $output[] = 'Položky objednávky:';
        foreach ($order->getItems() as $item) {
            $output[] = $item->getPieces().'x '.$item->getDescr().' Cena: '.printPrice($item->getTotalPrice());
        }

        return $this->implodeOutput($output);
    }

    public function getAdminUserInfo(): string
    {
        $output = [];
        $admin = getAdminUser();
        if ($admin['name'] ?? false) {
            $output[] = 'Jméno: '.$admin['name'];
        }
        if ($admin['email'] ?? false) {
            $output[] = 'Email: '.$admin['email'];
        }

        return $this->implodeOutput($output);
    }

    public function implodeOutput(array $output): string
    {
        $output = array_map(fn ($val) => StringUtil::unicode_trim($val), $output);
        $output = array_map(fn ($val) => str_replace(self::EMPTY_LINE, '', $val), array_filter($output));

        return implode(PHP_EOL, $output);
    }
}
