<?php

namespace External\SprintBundle\Util;

use FTP\Connection;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Query\Operator;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class InvoicesDownloader
{
    public static $baseDir = '/';
    private $ftpconn;
    public static $username = 'sprint_XML30';
    public static $password = 'bwhCAm4C';
    public static $server = 'ftp.sprint.cz';
    private $pathFinder;

    /** @var HeliosAPI */
    private $heliosAPI;

    public function getDocumentIdFromOrder($order_id)
    {
        return sqlQueryBuilder()->select('id_money')->from('money_orders')->where(
            Operator::equals([
                'id_order' => $order_id,
            ])
        )->execute()->fetchOne();
    }

    public function hasOdd(int $id_order): bool
    {
        $order = new \Order();
        if (!$order->createFromDB($id_order)) {
            return false;
        }
        if (!$id_document = $this->getDocumentIdFromOrder($id_order)) {
            return false;
        }

        if ($this->getOddFileName($id_document)) {
            return true;
        }

        return false;
    }

    public function getInvoiceFileName($id_invoice): ?string
    {
        return $this->heliosAPI->getOrderInvoice((int) $id_invoice);
    }

    public function getOddFileName($id_invoice): ?string
    {
        return $this->heliosAPI->getOrderODD((int) $id_invoice);
    }

    public function processData(string $invoiceFile)
    {
        $result = $this->ftpDownload($invoiceFile);

        if ($result) {
            $response = new StreamedResponse(function () use ($result) {
                echo file_get_contents($result);
            });
            $response->headers->set('Content-Type', 'application/pdf; charset=utf8');

            return $response;
        }

        throw new NotFoundHttpException('Order does not have invoice');
    }

    private function getFTP(): false|Connection
    {
        if (!$this->ftpconn) {
            $this->ftpconn = ftp_connect(self::$server, '21');
            ftp_login($this->ftpconn, static::$username, static::$password);
            ftp_pasv($this->ftpconn, true);
            ftp_chdir($this->ftpconn, static::$baseDir);
        }

        return $this->ftpconn;
    }

    private function ftpDownload($filename)
    {
        $pathFinder = $this->getPathFinder();
        $lDir = $pathFinder->getDataDir().'/';
        $lPath = $lDir.$filename;
        $rPath = '/'.$filename;
        if (file_exists($lPath)) {
            return $lPath;
        }
        if (!file_exists($lDir)) {
            mkdir($lDir, 0777, true);
        }

        if (ftp_get($this->getFTP(), $lPath, $rPath)) {
            return $lPath;
        }

        return false;
    }

    private function getPathFinder()
    {
        if (!$this->pathFinder) {
            $this->pathFinder = PathFinder::getService();
        }

        return $this->pathFinder;
    }

    /**
     * @required
     */
    public function setHeliosAPI(HeliosAPI $heliosAPI): void
    {
        $this->heliosAPI = $heliosAPI;
    }
}
